blob: 794d354ed6d255434aee37ef4ede7f9fde795cdf [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/CommandLine.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000035#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"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000138#include "llvm/IR/Intrinsics.h"
139#include "llvm/IR/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 ||
John McCall9fbd3182011-06-15 23:37:01 +0000429 Class == IC_AutoreleaseRV;
430}
431
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000432/// \brief Test if the given class represents instructions which are never safe
433/// to mark with the "tail" keyword.
434static bool IsNeverTail(InstructionClass Class) {
435 /// It is never safe to tail call objc_autorelease since by tail calling
436 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
437 /// fast autoreleasing causing our object to be potentially reclaimed from the
438 /// autorelease pool which violates the semantics of __autoreleasing types in
439 /// ARC.
440 return Class == IC_Autorelease;
441}
442
John McCall9fbd3182011-06-15 23:37:01 +0000443/// IsNoThrow - Test if the given class represents instructions which are always
444/// safe to mark with the nounwind attribute..
445static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000446 // objc_retainBlock is not nounwind because it calls user copy constructors
447 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000448 return Class == IC_Retain ||
449 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000450 Class == IC_Release ||
451 Class == IC_Autorelease ||
452 Class == IC_AutoreleaseRV ||
453 Class == IC_AutoreleasepoolPush ||
454 Class == IC_AutoreleasepoolPop;
455}
456
Dan Gohman447989c2012-04-27 18:56:31 +0000457/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000458/// argument verbatim, so if it's such a call and the return value has users,
459/// replace them with the argument value.
460static void EraseInstruction(Instruction *CI) {
461 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
462
463 bool Unused = CI->use_empty();
464
465 if (!Unused) {
466 // Replace the return value with the argument.
467 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
468 "Can't delete non-forwarding instruction with users!");
469 CI->replaceAllUsesWith(OldArg);
470 }
471
472 CI->eraseFromParent();
473
474 if (Unused)
475 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
476}
477
478/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
479/// also knows how to look through objc_retain and objc_autorelease calls, which
480/// we know to return their argument verbatim.
481static const Value *GetUnderlyingObjCPtr(const Value *V) {
482 for (;;) {
483 V = GetUnderlyingObject(V);
484 if (!IsForwarding(GetBasicInstructionClass(V)))
485 break;
486 V = cast<CallInst>(V)->getArgOperand(0);
487 }
488
489 return V;
490}
491
492/// StripPointerCastsAndObjCCalls - This is a wrapper around
493/// Value::stripPointerCasts which also knows how to look through objc_retain
494/// and objc_autorelease calls, which we know to return their argument verbatim.
495static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
496 for (;;) {
497 V = V->stripPointerCasts();
498 if (!IsForwarding(GetBasicInstructionClass(V)))
499 break;
500 V = cast<CallInst>(V)->getArgOperand(0);
501 }
502 return V;
503}
504
505/// StripPointerCastsAndObjCCalls - This is a wrapper around
506/// Value::stripPointerCasts which also knows how to look through objc_retain
507/// and objc_autorelease calls, which we know to return their argument verbatim.
508static Value *StripPointerCastsAndObjCCalls(Value *V) {
509 for (;;) {
510 V = V->stripPointerCasts();
511 if (!IsForwarding(GetBasicInstructionClass(V)))
512 break;
513 V = cast<CallInst>(V)->getArgOperand(0);
514 }
515 return V;
516}
517
518/// GetObjCArg - Assuming the given instruction is one of the special calls such
519/// as objc_retain or objc_release, return the argument value, stripped of no-op
520/// casts and forwarding calls.
521static Value *GetObjCArg(Value *Inst) {
522 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
523}
524
525/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
526/// isObjCIdentifiedObject, except that it uses special knowledge of
527/// ObjC conventions...
528static bool IsObjCIdentifiedObject(const Value *V) {
529 // Assume that call results and arguments have their own "provenance".
530 // Constants (including GlobalVariables) and Allocas are never
531 // reference-counted.
532 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
533 isa<Argument>(V) || isa<Constant>(V) ||
534 isa<AllocaInst>(V))
535 return true;
536
537 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
538 const Value *Pointer =
539 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
540 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000541 // A constant pointer can't be pointing to an object on the heap. It may
542 // be reference-counted, but it won't be deleted.
543 if (GV->isConstant())
544 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000545 StringRef Name = GV->getName();
546 // These special variables are known to hold values which are not
547 // reference-counted pointers.
548 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
549 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
551 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
552 Name.startswith("\01l_objc_msgSend_fixup_"))
553 return true;
554 }
555 }
556
557 return false;
558}
559
560/// FindSingleUseIdentifiedObject - This is similar to
561/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
562/// with multiple uses.
563static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564 if (Arg->hasOneUse()) {
565 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566 return FindSingleUseIdentifiedObject(BC->getOperand(0));
567 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568 if (GEP->hasAllZeroIndices())
569 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570 if (IsForwarding(GetBasicInstructionClass(Arg)))
571 return FindSingleUseIdentifiedObject(
572 cast<CallInst>(Arg)->getArgOperand(0));
573 if (!IsObjCIdentifiedObject(Arg))
574 return 0;
575 return Arg;
576 }
577
Dan Gohman0daef3d2012-05-08 23:39:44 +0000578 // If we found an identifiable object but it has multiple uses, but they are
579 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000580 if (IsObjCIdentifiedObject(Arg)) {
581 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
582 UI != UE; ++UI) {
583 const User *U = *UI;
584 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585 return 0;
586 }
587
588 return Arg;
589 }
590
591 return 0;
592}
593
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000594/// ModuleHasARC - Test if the given module looks interesting to run ARC
595/// optimization on.
596static bool ModuleHasARC(const Module &M) {
597 return
598 M.getNamedValue("objc_retain") ||
599 M.getNamedValue("objc_release") ||
600 M.getNamedValue("objc_autorelease") ||
601 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602 M.getNamedValue("objc_retainBlock") ||
603 M.getNamedValue("objc_autoreleaseReturnValue") ||
604 M.getNamedValue("objc_autoreleasePoolPush") ||
605 M.getNamedValue("objc_loadWeakRetained") ||
606 M.getNamedValue("objc_loadWeak") ||
607 M.getNamedValue("objc_destroyWeak") ||
608 M.getNamedValue("objc_storeWeak") ||
609 M.getNamedValue("objc_initWeak") ||
610 M.getNamedValue("objc_moveWeak") ||
611 M.getNamedValue("objc_copyWeak") ||
612 M.getNamedValue("objc_retainedObject") ||
613 M.getNamedValue("objc_unretainedObject") ||
614 M.getNamedValue("objc_unretainedPointer");
615}
616
Dan Gohman79522dc2012-01-13 00:39:07 +0000617/// DoesObjCBlockEscape - Test whether the given pointer, which is an
618/// Objective C block pointer, does not "escape". This differs from regular
619/// escape analysis in that a use as an argument to a call is not considered
620/// an escape.
621static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman981308c2013-01-13 07:47:32 +0000622
623 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
624
Dan Gohman79522dc2012-01-13 00:39:07 +0000625 // Walk the def-use chains.
626 SmallVector<const Value *, 4> Worklist;
627 Worklist.push_back(BlockPtr);
628 do {
629 const Value *V = Worklist.pop_back_val();
Michael Gottesman981308c2013-01-13 07:47:32 +0000630
631 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
632
Dan Gohman79522dc2012-01-13 00:39:07 +0000633 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
634 UI != UE; ++UI) {
635 const User *UUser = *UI;
Michael Gottesman981308c2013-01-13 07:47:32 +0000636
637 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
638
Dan Gohman79522dc2012-01-13 00:39:07 +0000639 // Special - Use by a call (callee or argument) is not considered
640 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000641 switch (GetBasicInstructionClass(UUser)) {
642 case IC_StoreWeak:
643 case IC_InitWeak:
644 case IC_StoreStrong:
645 case IC_Autorelease:
Michael Gottesman981308c2013-01-13 07:47:32 +0000646 case IC_AutoreleaseRV: {
647 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
648 "Block Escapes!\n");
Dan Gohman44234772012-04-13 18:28:58 +0000649 // These special functions make copies of their pointer arguments.
650 return true;
Michael Gottesman981308c2013-01-13 07:47:32 +0000651 }
Dan Gohman44234772012-04-13 18:28:58 +0000652 case IC_User:
653 case IC_None:
654 // Use by an instruction which copies the value is an escape if the
655 // result is an escape.
656 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
657 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesman981308c2013-01-13 07:47:32 +0000658 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes if "
659 "result escapes. Adding to list.\n");
Dan Gohman44234772012-04-13 18:28:58 +0000660 Worklist.push_back(UUser);
661 continue;
662 }
663 // Use by a load is not an escape.
664 if (isa<LoadInst>(UUser))
665 continue;
666 // Use by a store is not an escape if the use is the address.
667 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
668 if (V != SI->getValueOperand())
669 continue;
670 break;
671 default:
672 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000673 continue;
674 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000675 // Otherwise, conservatively assume an escape.
Michael Gottesman981308c2013-01-13 07:47:32 +0000676 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000677 return true;
678 }
679 } while (!Worklist.empty());
680
681 // No escapes found.
Michael Gottesman981308c2013-01-13 07:47:32 +0000682 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000683 return false;
684}
685
John McCall9fbd3182011-06-15 23:37:01 +0000686//===----------------------------------------------------------------------===//
687// ARC AliasAnalysis.
688//===----------------------------------------------------------------------===//
689
John McCall9fbd3182011-06-15 23:37:01 +0000690#include "llvm/Analysis/AliasAnalysis.h"
691#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000692#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000693
694namespace {
695 /// ObjCARCAliasAnalysis - This is a simple alias analysis
696 /// implementation that uses knowledge of ARC constructs to answer queries.
697 ///
698 /// TODO: This class could be generalized to know about other ObjC-specific
699 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
700 /// even though their offsets are dynamic.
701 class ObjCARCAliasAnalysis : public ImmutablePass,
702 public AliasAnalysis {
703 public:
704 static char ID; // Class identification, replacement for typeinfo
705 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
706 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
707 }
708
709 private:
710 virtual void initializePass() {
711 InitializeAliasAnalysis(this);
712 }
713
714 /// getAdjustedAnalysisPointer - This method is used when a pass implements
715 /// an analysis interface through multiple inheritance. If needed, it
716 /// should override this to adjust the this pointer as needed for the
717 /// specified pass info.
718 virtual void *getAdjustedAnalysisPointer(const void *PI) {
719 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000720 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000721 return this;
722 }
723
724 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
725 virtual AliasResult alias(const Location &LocA, const Location &LocB);
726 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
727 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
728 virtual ModRefBehavior getModRefBehavior(const Function *F);
729 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
730 const Location &Loc);
731 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
732 ImmutableCallSite CS2);
733 };
734} // End of anonymous namespace
735
736// Register this pass...
737char ObjCARCAliasAnalysis::ID = 0;
738INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
739 "ObjC-ARC-Based Alias Analysis", false, true, false)
740
741ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
742 return new ObjCARCAliasAnalysis();
743}
744
745void
746ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
747 AU.setPreservesAll();
748 AliasAnalysis::getAnalysisUsage(AU);
749}
750
751AliasAnalysis::AliasResult
752ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
753 if (!EnableARCOpts)
754 return AliasAnalysis::alias(LocA, LocB);
755
756 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
757 // precise alias query.
758 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
759 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
760 AliasResult Result =
761 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
762 Location(SB, LocB.Size, LocB.TBAATag));
763 if (Result != MayAlias)
764 return Result;
765
766 // If that failed, climb to the underlying object, including climbing through
767 // ObjC-specific no-ops, and try making an imprecise alias query.
768 const Value *UA = GetUnderlyingObjCPtr(SA);
769 const Value *UB = GetUnderlyingObjCPtr(SB);
770 if (UA != SA || UB != SB) {
771 Result = AliasAnalysis::alias(Location(UA), Location(UB));
772 // We can't use MustAlias or PartialAlias results here because
773 // GetUnderlyingObjCPtr may return an offsetted pointer value.
774 if (Result == NoAlias)
775 return NoAlias;
776 }
777
778 // If that failed, fail. We don't need to chain here, since that's covered
779 // by the earlier precise query.
780 return MayAlias;
781}
782
783bool
784ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
785 bool OrLocal) {
786 if (!EnableARCOpts)
787 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
788
789 // First, strip off no-ops, including ObjC-specific no-ops, and try making
790 // a precise alias query.
791 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
792 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
793 OrLocal))
794 return true;
795
796 // If that failed, climb to the underlying object, including climbing through
797 // ObjC-specific no-ops, and try making an imprecise alias query.
798 const Value *U = GetUnderlyingObjCPtr(S);
799 if (U != S)
800 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
801
802 // If that failed, fail. We don't need to chain here, since that's covered
803 // by the earlier precise query.
804 return false;
805}
806
807AliasAnalysis::ModRefBehavior
808ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
809 // We have nothing to do. Just chain to the next AliasAnalysis.
810 return AliasAnalysis::getModRefBehavior(CS);
811}
812
813AliasAnalysis::ModRefBehavior
814ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
815 if (!EnableARCOpts)
816 return AliasAnalysis::getModRefBehavior(F);
817
818 switch (GetFunctionClass(F)) {
819 case IC_NoopCast:
820 return DoesNotAccessMemory;
821 default:
822 break;
823 }
824
825 return AliasAnalysis::getModRefBehavior(F);
826}
827
828AliasAnalysis::ModRefResult
829ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
830 if (!EnableARCOpts)
831 return AliasAnalysis::getModRefInfo(CS, Loc);
832
833 switch (GetBasicInstructionClass(CS.getInstruction())) {
834 case IC_Retain:
835 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000836 case IC_Autorelease:
837 case IC_AutoreleaseRV:
838 case IC_NoopCast:
839 case IC_AutoreleasepoolPush:
840 case IC_FusedRetainAutorelease:
841 case IC_FusedRetainAutoreleaseRV:
842 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000843 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000844 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000845 return NoModRef;
846 default:
847 break;
848 }
849
850 return AliasAnalysis::getModRefInfo(CS, Loc);
851}
852
853AliasAnalysis::ModRefResult
854ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
855 ImmutableCallSite CS2) {
856 // TODO: Theoretically we could check for dependencies between objc_* calls
857 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
858 return AliasAnalysis::getModRefInfo(CS1, CS2);
859}
860
861//===----------------------------------------------------------------------===//
862// ARC expansion.
863//===----------------------------------------------------------------------===//
864
865#include "llvm/Support/InstIterator.h"
866#include "llvm/Transforms/Scalar.h"
867
868namespace {
869 /// ObjCARCExpand - Early ARC transformations.
870 class ObjCARCExpand : public FunctionPass {
871 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000872 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000873 virtual bool runOnFunction(Function &F);
874
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000875 /// Run - A flag indicating whether this optimization pass should run.
876 bool Run;
877
John McCall9fbd3182011-06-15 23:37:01 +0000878 public:
879 static char ID;
880 ObjCARCExpand() : FunctionPass(ID) {
881 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
882 }
883 };
884}
885
886char ObjCARCExpand::ID = 0;
887INITIALIZE_PASS(ObjCARCExpand,
888 "objc-arc-expand", "ObjC ARC expansion", false, false)
889
890Pass *llvm::createObjCARCExpandPass() {
891 return new ObjCARCExpand();
892}
893
894void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
895 AU.setPreservesCFG();
896}
897
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000898bool ObjCARCExpand::doInitialization(Module &M) {
899 Run = ModuleHasARC(M);
900 return false;
901}
902
John McCall9fbd3182011-06-15 23:37:01 +0000903bool ObjCARCExpand::runOnFunction(Function &F) {
904 if (!EnableARCOpts)
905 return false;
906
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000907 // If nothing in the Module uses ARC, don't do anything.
908 if (!Run)
909 return false;
910
John McCall9fbd3182011-06-15 23:37:01 +0000911 bool Changed = false;
912
Michael Gottesmancf140052013-01-13 07:00:51 +0000913 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
914
John McCall9fbd3182011-06-15 23:37:01 +0000915 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
916 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000917
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000918 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000919
John McCall9fbd3182011-06-15 23:37:01 +0000920 switch (GetBasicInstructionClass(Inst)) {
921 case IC_Retain:
922 case IC_RetainRV:
923 case IC_Autorelease:
924 case IC_AutoreleaseRV:
925 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000926 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000927 // These calls return their argument verbatim, as a low-level
928 // optimization. However, this makes high-level optimizations
929 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000930 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000931 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000932 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
933 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
934 " New = " << *Value << "\n");
935 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000936 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000937 }
John McCall9fbd3182011-06-15 23:37:01 +0000938 default:
939 break;
940 }
941 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000942
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000943 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000944
John McCall9fbd3182011-06-15 23:37:01 +0000945 return Changed;
946}
947
948//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000949// ARC autorelease pool elimination.
950//===----------------------------------------------------------------------===//
951
Dan Gohman0daef3d2012-05-08 23:39:44 +0000952#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000953#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000954
Dan Gohman2f6263c2012-01-17 20:52:24 +0000955namespace {
956 /// ObjCARCAPElim - Autorelease pool elimination.
957 class ObjCARCAPElim : public ModulePass {
958 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
959 virtual bool runOnModule(Module &M);
960
Dan Gohman447989c2012-04-27 18:56:31 +0000961 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
962 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000963
964 public:
965 static char ID;
966 ObjCARCAPElim() : ModulePass(ID) {
967 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
968 }
969 };
970}
971
972char ObjCARCAPElim::ID = 0;
973INITIALIZE_PASS(ObjCARCAPElim,
974 "objc-arc-apelim",
975 "ObjC ARC autorelease pool elimination",
976 false, false)
977
978Pass *llvm::createObjCARCAPElimPass() {
979 return new ObjCARCAPElim();
980}
981
982void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
983 AU.setPreservesCFG();
984}
985
986/// MayAutorelease - Interprocedurally determine if calls made by the
987/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000988bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
989 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000990 if (Callee->isDeclaration() || Callee->mayBeOverridden())
991 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000992 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000993 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000994 const BasicBlock *BB = I;
995 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
996 J != F; ++J)
997 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000998 // This recursion depth limit is arbitrary. It's just great
999 // enough to cover known interesting testcases.
1000 if (Depth < 3 &&
1001 !JCS.onlyReadsMemory() &&
1002 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001003 return true;
1004 }
1005 return false;
1006 }
1007
1008 return true;
1009}
1010
1011bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1012 bool Changed = false;
1013
1014 Instruction *Push = 0;
1015 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1016 Instruction *Inst = I++;
1017 switch (GetBasicInstructionClass(Inst)) {
1018 case IC_AutoreleasepoolPush:
1019 Push = Inst;
1020 break;
1021 case IC_AutoreleasepoolPop:
1022 // If this pop matches a push and nothing in between can autorelease,
1023 // zap the pair.
1024 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1025 Changed = true;
Michael Gottesman5c0ae472013-01-04 21:29:57 +00001026 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001027 << " Pop: " << *Inst << "\n"
1028 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001029 Inst->eraseFromParent();
1030 Push->eraseFromParent();
1031 }
1032 Push = 0;
1033 break;
1034 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001035 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001036 Push = 0;
1037 break;
1038 default:
1039 break;
1040 }
1041 }
1042
1043 return Changed;
1044}
1045
1046bool ObjCARCAPElim::runOnModule(Module &M) {
1047 if (!EnableARCOpts)
1048 return false;
1049
1050 // If nothing in the Module uses ARC, don't do anything.
1051 if (!ModuleHasARC(M))
1052 return false;
1053
Dan Gohman1dae3e92012-01-18 21:19:38 +00001054 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001055 // identifying the global constructors. In theory, unnecessary autorelease
1056 // pools could occur anywhere, but in practice it's pretty rare. Global
1057 // ctors are a place where autorelease pools get inserted automatically,
1058 // so it's pretty common for them to be unnecessary, and it's pretty
1059 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001060 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1061 if (!GV)
1062 return false;
1063
1064 assert(GV->hasDefinitiveInitializer() &&
1065 "llvm.global_ctors is uncooperative!");
1066
Dan Gohman2f6263c2012-01-17 20:52:24 +00001067 bool Changed = false;
1068
Dan Gohman1dae3e92012-01-18 21:19:38 +00001069 // Dig the constructor functions out of GV's initializer.
1070 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1071 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1072 OI != OE; ++OI) {
1073 Value *Op = *OI;
1074 // llvm.global_ctors is an array of pairs where the second members
1075 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001076 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1077 // If the user used a constructor function with the wrong signature and
1078 // it got bitcasted or whatever, look the other way.
1079 if (!F)
1080 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001081 // Only look at function definitions.
1082 if (F->isDeclaration())
1083 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001084 // Only look at functions with one basic block.
1085 if (llvm::next(F->begin()) != F->end())
1086 continue;
1087 // Ok, a single-block constructor function definition. Try to optimize it.
1088 Changed |= OptimizeBB(F->begin());
1089 }
1090
1091 return Changed;
1092}
1093
1094//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001095// ARC optimization.
1096//===----------------------------------------------------------------------===//
1097
1098// TODO: On code like this:
1099//
1100// objc_retain(%x)
1101// stuff_that_cannot_release()
1102// objc_autorelease(%x)
1103// stuff_that_cannot_release()
1104// objc_retain(%x)
1105// stuff_that_cannot_release()
1106// objc_autorelease(%x)
1107//
1108// The second retain and autorelease can be deleted.
1109
1110// TODO: It should be possible to delete
1111// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1112// pairs if nothing is actually autoreleased between them. Also, autorelease
1113// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1114// after inlining) can be turned into plain release calls.
1115
1116// TODO: Critical-edge splitting. If the optimial insertion point is
1117// a critical edge, the current algorithm has to fail, because it doesn't
1118// know how to split edges. It should be possible to make the optimizer
1119// think in terms of edges, rather than blocks, and then split critical
1120// edges on demand.
1121
1122// TODO: OptimizeSequences could generalized to be Interprocedural.
1123
1124// TODO: Recognize that a bunch of other objc runtime calls have
1125// non-escaping arguments and non-releasing arguments, and may be
1126// non-autoreleasing.
1127
1128// TODO: Sink autorelease calls as far as possible. Unfortunately we
1129// usually can't sink them past other calls, which would be the main
1130// case where it would be useful.
1131
Dan Gohmane6d5e882011-08-19 00:26:36 +00001132// TODO: The pointer returned from objc_loadWeakRetained is retained.
1133
1134// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001135
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001136#include "llvm/ADT/SmallPtrSet.h"
1137#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001138#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001139#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001140
1141STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1142STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1143STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1144STATISTIC(NumRets, "Number of return value forwarding "
1145 "retain+autoreleaes eliminated");
1146STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1147STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1148
1149namespace {
1150 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1151 /// uses many of the same techniques, except it uses special ObjC-specific
1152 /// reasoning about pointer relationships.
1153 class ProvenanceAnalysis {
1154 AliasAnalysis *AA;
1155
1156 typedef std::pair<const Value *, const Value *> ValuePairTy;
1157 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1158 CachedResultsTy CachedResults;
1159
1160 bool relatedCheck(const Value *A, const Value *B);
1161 bool relatedSelect(const SelectInst *A, const Value *B);
1162 bool relatedPHI(const PHINode *A, const Value *B);
1163
Craig Topperc2945e42012-09-18 02:01:41 +00001164 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1165 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001166
1167 public:
1168 ProvenanceAnalysis() {}
1169
1170 void setAA(AliasAnalysis *aa) { AA = aa; }
1171
1172 AliasAnalysis *getAA() const { return AA; }
1173
1174 bool related(const Value *A, const Value *B);
1175
1176 void clear() {
1177 CachedResults.clear();
1178 }
1179 };
1180}
1181
1182bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1183 // If the values are Selects with the same condition, we can do a more precise
1184 // check: just check for relations between the values on corresponding arms.
1185 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001186 if (A->getCondition() == SB->getCondition())
1187 return related(A->getTrueValue(), SB->getTrueValue()) ||
1188 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001189
1190 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001191 return related(A->getTrueValue(), B) ||
1192 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001193}
1194
1195bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1196 // If the values are PHIs in the same block, we can do a more precise as well
1197 // as efficient check: just check for relations between the values on
1198 // corresponding edges.
1199 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1200 if (PNB->getParent() == A->getParent()) {
1201 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1202 if (related(A->getIncomingValue(i),
1203 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1204 return true;
1205 return false;
1206 }
1207
1208 // Check each unique source of the PHI node against B.
1209 SmallPtrSet<const Value *, 4> UniqueSrc;
1210 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1211 const Value *PV1 = A->getIncomingValue(i);
1212 if (UniqueSrc.insert(PV1) && related(PV1, B))
1213 return true;
1214 }
1215
1216 // All of the arms checked out.
1217 return false;
1218}
1219
1220/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1221/// provenance, is ever stored within the function (not counting callees).
1222static bool isStoredObjCPointer(const Value *P) {
1223 SmallPtrSet<const Value *, 8> Visited;
1224 SmallVector<const Value *, 8> Worklist;
1225 Worklist.push_back(P);
1226 Visited.insert(P);
1227 do {
1228 P = Worklist.pop_back_val();
1229 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1230 UI != UE; ++UI) {
1231 const User *Ur = *UI;
1232 if (isa<StoreInst>(Ur)) {
1233 if (UI.getOperandNo() == 0)
1234 // The pointer is stored.
1235 return true;
1236 // The pointed is stored through.
1237 continue;
1238 }
1239 if (isa<CallInst>(Ur))
1240 // The pointer is passed as an argument, ignore this.
1241 continue;
1242 if (isa<PtrToIntInst>(P))
1243 // Assume the worst.
1244 return true;
1245 if (Visited.insert(Ur))
1246 Worklist.push_back(Ur);
1247 }
1248 } while (!Worklist.empty());
1249
1250 // Everything checked out.
1251 return false;
1252}
1253
1254bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1255 // Skip past provenance pass-throughs.
1256 A = GetUnderlyingObjCPtr(A);
1257 B = GetUnderlyingObjCPtr(B);
1258
1259 // Quick check.
1260 if (A == B)
1261 return true;
1262
1263 // Ask regular AliasAnalysis, for a first approximation.
1264 switch (AA->alias(A, B)) {
1265 case AliasAnalysis::NoAlias:
1266 return false;
1267 case AliasAnalysis::MustAlias:
1268 case AliasAnalysis::PartialAlias:
1269 return true;
1270 case AliasAnalysis::MayAlias:
1271 break;
1272 }
1273
1274 bool AIsIdentified = IsObjCIdentifiedObject(A);
1275 bool BIsIdentified = IsObjCIdentifiedObject(B);
1276
1277 // An ObjC-Identified object can't alias a load if it is never locally stored.
1278 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001279 // Check for an obvious escape.
1280 if (isa<LoadInst>(B))
1281 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001282 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001283 // Check for an obvious escape.
1284 if (isa<LoadInst>(A))
1285 return isStoredObjCPointer(B);
1286 // Both pointers are identified and escapes aren't an evident problem.
1287 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001288 }
Dan Gohman230768b2012-09-04 23:16:20 +00001289 } else if (BIsIdentified) {
1290 // Check for an obvious escape.
1291 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001292 return isStoredObjCPointer(B);
1293 }
1294
1295 // Special handling for PHI and Select.
1296 if (const PHINode *PN = dyn_cast<PHINode>(A))
1297 return relatedPHI(PN, B);
1298 if (const PHINode *PN = dyn_cast<PHINode>(B))
1299 return relatedPHI(PN, A);
1300 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1301 return relatedSelect(S, B);
1302 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1303 return relatedSelect(S, A);
1304
1305 // Conservative.
1306 return true;
1307}
1308
1309bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1310 // Begin by inserting a conservative value into the map. If the insertion
1311 // fails, we have the answer already. If it succeeds, leave it there until we
1312 // compute the real answer to guard against recursive queries.
1313 if (A > B) std::swap(A, B);
1314 std::pair<CachedResultsTy::iterator, bool> Pair =
1315 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1316 if (!Pair.second)
1317 return Pair.first->second;
1318
1319 bool Result = relatedCheck(A, B);
1320 CachedResults[ValuePairTy(A, B)] = Result;
1321 return Result;
1322}
1323
1324namespace {
1325 // Sequence - A sequence of states that a pointer may go through in which an
1326 // objc_retain and objc_release are actually needed.
1327 enum Sequence {
1328 S_None,
1329 S_Retain, ///< objc_retain(x)
1330 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1331 S_Use, ///< any use of x
1332 S_Stop, ///< like S_Release, but code motion is stopped
1333 S_Release, ///< objc_release(x)
1334 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1335 };
1336}
1337
1338static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1339 // The easy cases.
1340 if (A == B)
1341 return A;
1342 if (A == S_None || B == S_None)
1343 return S_None;
1344
John McCall9fbd3182011-06-15 23:37:01 +00001345 if (A > B) std::swap(A, B);
1346 if (TopDown) {
1347 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001348 if ((A == S_Retain || A == S_CanRelease) &&
1349 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001350 return B;
1351 } else {
1352 // Choose the side which is further along in the sequence.
1353 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001354 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001355 return A;
1356 // If both sides are releases, choose the more conservative one.
1357 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1358 return A;
1359 if (A == S_Release && B == S_MovableRelease)
1360 return A;
1361 }
1362
1363 return S_None;
1364}
1365
1366namespace {
1367 /// RRInfo - Unidirectional information about either a
1368 /// retain-decrement-use-release sequence or release-use-decrement-retain
1369 /// reverese sequence.
1370 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001371 /// KnownSafe - After an objc_retain, the reference count of the referenced
1372 /// object is known to be positive. Similarly, before an objc_release, the
1373 /// reference count of the referenced object is known to be positive. If
1374 /// there are retain-release pairs in code regions where the retain count
1375 /// is known to be positive, they can be eliminated, regardless of any side
1376 /// effects between them.
1377 ///
1378 /// Also, a retain+release pair nested within another retain+release
1379 /// pair all on the known same pointer value can be eliminated, regardless
1380 /// of any intervening side effects.
1381 ///
1382 /// KnownSafe is true when either of these conditions is satisfied.
1383 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001384
1385 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1386 /// opposed to objc_retain calls).
1387 bool IsRetainBlock;
1388
1389 /// IsTailCallRelease - True of the objc_release calls are all marked
1390 /// with the "tail" keyword.
1391 bool IsTailCallRelease;
1392
1393 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1394 /// a clang.imprecise_release tag, this is the metadata tag.
1395 MDNode *ReleaseMetadata;
1396
1397 /// Calls - For a top-down sequence, the set of objc_retains or
1398 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1399 SmallPtrSet<Instruction *, 2> Calls;
1400
1401 /// ReverseInsertPts - The set of optimal insert positions for
1402 /// moving calls in the opposite sequence.
1403 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1404
1405 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001406 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001407 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001408 ReleaseMetadata(0) {}
1409
1410 void clear();
1411 };
1412}
1413
1414void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001415 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001416 IsRetainBlock = false;
1417 IsTailCallRelease = false;
1418 ReleaseMetadata = 0;
1419 Calls.clear();
1420 ReverseInsertPts.clear();
1421}
1422
1423namespace {
1424 /// PtrState - This class summarizes several per-pointer runtime properties
1425 /// which are propogated through the flow graph.
1426 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001427 /// KnownPositiveRefCount - True if the reference count is known to
1428 /// be incremented.
1429 bool KnownPositiveRefCount;
1430
1431 /// Partial - True of we've seen an opportunity for partial RR elimination,
1432 /// such as pushing calls into a CFG triangle or into one side of a
1433 /// CFG diamond.
1434 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001435
1436 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001437 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001438
1439 public:
1440 /// RRI - Unidirectional information about the current sequence.
1441 /// TODO: Encapsulate this better.
1442 RRInfo RRI;
1443
Dan Gohman230768b2012-09-04 23:16:20 +00001444 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001445 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001446
Dan Gohman50ade652012-04-25 00:50:46 +00001447 void SetKnownPositiveRefCount() {
1448 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001449 }
1450
Dan Gohman50ade652012-04-25 00:50:46 +00001451 void ClearRefCount() {
1452 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001453 }
1454
John McCall9fbd3182011-06-15 23:37:01 +00001455 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001456 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001457 }
1458
1459 void SetSeq(Sequence NewSeq) {
1460 Seq = NewSeq;
1461 }
1462
John McCall9fbd3182011-06-15 23:37:01 +00001463 Sequence GetSeq() const {
1464 return Seq;
1465 }
1466
1467 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001468 ResetSequenceProgress(S_None);
1469 }
1470
1471 void ResetSequenceProgress(Sequence NewSeq) {
1472 Seq = NewSeq;
1473 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001474 RRI.clear();
1475 }
1476
1477 void Merge(const PtrState &Other, bool TopDown);
1478 };
1479}
1480
1481void
1482PtrState::Merge(const PtrState &Other, bool TopDown) {
1483 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001484 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001485
1486 // We can't merge a plain objc_retain with an objc_retainBlock.
1487 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1488 Seq = S_None;
1489
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001490 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001491 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001492 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001493 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001494 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001495 // If we're doing a merge on a path that's previously seen a partial
1496 // merge, conservatively drop the sequence, to avoid doing partial
1497 // RR elimination. If the branch predicates for the two merge differ,
1498 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001499 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001500 } else {
1501 // Conservatively merge the ReleaseMetadata information.
1502 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1503 RRI.ReleaseMetadata = 0;
1504
Dan Gohmane6d5e882011-08-19 00:26:36 +00001505 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001506 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1507 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001508 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001509
1510 // Merge the insert point sets. If there are any differences,
1511 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001512 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001513 for (SmallPtrSet<Instruction *, 2>::const_iterator
1514 I = Other.RRI.ReverseInsertPts.begin(),
1515 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001516 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001517 }
1518}
1519
1520namespace {
1521 /// BBState - Per-BasicBlock state.
1522 class BBState {
1523 /// TopDownPathCount - The number of unique control paths from the entry
1524 /// which can reach this block.
1525 unsigned TopDownPathCount;
1526
1527 /// BottomUpPathCount - The number of unique control paths to exits
1528 /// from this block.
1529 unsigned BottomUpPathCount;
1530
1531 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1532 typedef MapVector<const Value *, PtrState> MapTy;
1533
1534 /// PerPtrTopDown - The top-down traversal uses this to record information
1535 /// known about a pointer at the bottom of each block.
1536 MapTy PerPtrTopDown;
1537
1538 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1539 /// known about a pointer at the top of each block.
1540 MapTy PerPtrBottomUp;
1541
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001542 /// Preds, Succs - Effective successors and predecessors of the current
1543 /// block (this ignores ignorable edges and ignored backedges).
1544 SmallVector<BasicBlock *, 2> Preds;
1545 SmallVector<BasicBlock *, 2> Succs;
1546
John McCall9fbd3182011-06-15 23:37:01 +00001547 public:
1548 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1549
1550 typedef MapTy::iterator ptr_iterator;
1551 typedef MapTy::const_iterator ptr_const_iterator;
1552
1553 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1554 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1555 ptr_const_iterator top_down_ptr_begin() const {
1556 return PerPtrTopDown.begin();
1557 }
1558 ptr_const_iterator top_down_ptr_end() const {
1559 return PerPtrTopDown.end();
1560 }
1561
1562 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1563 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1564 ptr_const_iterator bottom_up_ptr_begin() const {
1565 return PerPtrBottomUp.begin();
1566 }
1567 ptr_const_iterator bottom_up_ptr_end() const {
1568 return PerPtrBottomUp.end();
1569 }
1570
1571 /// SetAsEntry - Mark this block as being an entry block, which has one
1572 /// path from the entry by definition.
1573 void SetAsEntry() { TopDownPathCount = 1; }
1574
1575 /// SetAsExit - Mark this block as being an exit block, which has one
1576 /// path to an exit by definition.
1577 void SetAsExit() { BottomUpPathCount = 1; }
1578
1579 PtrState &getPtrTopDownState(const Value *Arg) {
1580 return PerPtrTopDown[Arg];
1581 }
1582
1583 PtrState &getPtrBottomUpState(const Value *Arg) {
1584 return PerPtrBottomUp[Arg];
1585 }
1586
1587 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001588 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001589 }
1590
1591 void clearTopDownPointers() {
1592 PerPtrTopDown.clear();
1593 }
1594
1595 void InitFromPred(const BBState &Other);
1596 void InitFromSucc(const BBState &Other);
1597 void MergePred(const BBState &Other);
1598 void MergeSucc(const BBState &Other);
1599
1600 /// GetAllPathCount - Return the number of possible unique paths from an
1601 /// entry to an exit which pass through this block. This is only valid
1602 /// after both the top-down and bottom-up traversals are complete.
1603 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001604 assert(TopDownPathCount != 0);
1605 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001606 return TopDownPathCount * BottomUpPathCount;
1607 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001608
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001609 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001610 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001611 edge_iterator pred_begin() { return Preds.begin(); }
1612 edge_iterator pred_end() { return Preds.end(); }
1613 edge_iterator succ_begin() { return Succs.begin(); }
1614 edge_iterator succ_end() { return Succs.end(); }
1615
1616 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1617 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1618
1619 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001620 };
1621}
1622
1623void BBState::InitFromPred(const BBState &Other) {
1624 PerPtrTopDown = Other.PerPtrTopDown;
1625 TopDownPathCount = Other.TopDownPathCount;
1626}
1627
1628void BBState::InitFromSucc(const BBState &Other) {
1629 PerPtrBottomUp = Other.PerPtrBottomUp;
1630 BottomUpPathCount = Other.BottomUpPathCount;
1631}
1632
1633/// MergePred - The top-down traversal uses this to merge information about
1634/// predecessors to form the initial state for a new block.
1635void BBState::MergePred(const BBState &Other) {
1636 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1637 // loop backedge. Loop backedges are special.
1638 TopDownPathCount += Other.TopDownPathCount;
1639
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001640 // Check for overflow. If we have overflow, fall back to conservative behavior.
1641 if (TopDownPathCount < Other.TopDownPathCount) {
1642 clearTopDownPointers();
1643 return;
1644 }
1645
John McCall9fbd3182011-06-15 23:37:01 +00001646 // For each entry in the other set, if our set has an entry with the same key,
1647 // merge the entries. Otherwise, copy the entry and merge it with an empty
1648 // entry.
1649 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1650 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1651 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1652 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1653 /*TopDown=*/true);
1654 }
1655
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001656 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001657 // same key, force it to merge with an empty entry.
1658 for (ptr_iterator MI = top_down_ptr_begin(),
1659 ME = top_down_ptr_end(); MI != ME; ++MI)
1660 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1661 MI->second.Merge(PtrState(), /*TopDown=*/true);
1662}
1663
1664/// MergeSucc - The bottom-up traversal uses this to merge information about
1665/// successors to form the initial state for a new block.
1666void BBState::MergeSucc(const BBState &Other) {
1667 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1668 // loop backedge. Loop backedges are special.
1669 BottomUpPathCount += Other.BottomUpPathCount;
1670
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001671 // Check for overflow. If we have overflow, fall back to conservative behavior.
1672 if (BottomUpPathCount < Other.BottomUpPathCount) {
1673 clearBottomUpPointers();
1674 return;
1675 }
1676
John McCall9fbd3182011-06-15 23:37:01 +00001677 // For each entry in the other set, if our set has an entry with the
1678 // same key, merge the entries. Otherwise, copy the entry and merge
1679 // it with an empty entry.
1680 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1681 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1682 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1683 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1684 /*TopDown=*/false);
1685 }
1686
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001687 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001688 // with the same key, force it to merge with an empty entry.
1689 for (ptr_iterator MI = bottom_up_ptr_begin(),
1690 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1691 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1692 MI->second.Merge(PtrState(), /*TopDown=*/false);
1693}
1694
1695namespace {
1696 /// ObjCARCOpt - The main ARC optimization pass.
1697 class ObjCARCOpt : public FunctionPass {
1698 bool Changed;
1699 ProvenanceAnalysis PA;
1700
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001701 /// Run - A flag indicating whether this optimization pass should run.
1702 bool Run;
1703
John McCall9fbd3182011-06-15 23:37:01 +00001704 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1705 /// functions, for use in creating calls to them. These are initialized
1706 /// lazily to avoid cluttering up the Module with unused declarations.
1707 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001708 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001709
1710 /// UsedInThisFunciton - Flags which determine whether each of the
1711 /// interesting runtine functions is in fact used in the current function.
1712 unsigned UsedInThisFunction;
1713
1714 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1715 /// metadata.
1716 unsigned ImpreciseReleaseMDKind;
1717
Dan Gohman62e5b402011-12-12 18:20:00 +00001718 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001719 /// metadata.
1720 unsigned CopyOnEscapeMDKind;
1721
Dan Gohmandbe266b2012-02-17 18:59:53 +00001722 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1723 /// clang.arc.no_objc_arc_exceptions metadata.
1724 unsigned NoObjCARCExceptionsMDKind;
1725
John McCall9fbd3182011-06-15 23:37:01 +00001726 Constant *getRetainRVCallee(Module *M);
1727 Constant *getAutoreleaseRVCallee(Module *M);
1728 Constant *getReleaseCallee(Module *M);
1729 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001730 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001731 Constant *getAutoreleaseCallee(Module *M);
1732
Dan Gohman79522dc2012-01-13 00:39:07 +00001733 bool IsRetainBlockOptimizable(const Instruction *Inst);
1734
John McCall9fbd3182011-06-15 23:37:01 +00001735 void OptimizeRetainCall(Function &F, Instruction *Retain);
1736 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001737 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1738 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001739 void OptimizeIndividualCalls(Function &F);
1740
1741 void CheckForCFGHazards(const BasicBlock *BB,
1742 DenseMap<const BasicBlock *, BBState> &BBStates,
1743 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001744 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001745 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001746 MapVector<Value *, RRInfo> &Retains,
1747 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001748 bool VisitBottomUp(BasicBlock *BB,
1749 DenseMap<const BasicBlock *, BBState> &BBStates,
1750 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001751 bool VisitInstructionTopDown(Instruction *Inst,
1752 DenseMap<Value *, RRInfo> &Releases,
1753 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001754 bool VisitTopDown(BasicBlock *BB,
1755 DenseMap<const BasicBlock *, BBState> &BBStates,
1756 DenseMap<Value *, RRInfo> &Releases);
1757 bool Visit(Function &F,
1758 DenseMap<const BasicBlock *, BBState> &BBStates,
1759 MapVector<Value *, RRInfo> &Retains,
1760 DenseMap<Value *, RRInfo> &Releases);
1761
1762 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1763 MapVector<Value *, RRInfo> &Retains,
1764 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001765 SmallVectorImpl<Instruction *> &DeadInsts,
1766 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001767
1768 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1769 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001770 DenseMap<Value *, RRInfo> &Releases,
1771 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001772
1773 void OptimizeWeakCalls(Function &F);
1774
1775 bool OptimizeSequences(Function &F);
1776
1777 void OptimizeReturns(Function &F);
1778
1779 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1780 virtual bool doInitialization(Module &M);
1781 virtual bool runOnFunction(Function &F);
1782 virtual void releaseMemory();
1783
1784 public:
1785 static char ID;
1786 ObjCARCOpt() : FunctionPass(ID) {
1787 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1788 }
1789 };
1790}
1791
1792char ObjCARCOpt::ID = 0;
1793INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1794 "objc-arc", "ObjC ARC optimization", false, false)
1795INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1796INITIALIZE_PASS_END(ObjCARCOpt,
1797 "objc-arc", "ObjC ARC optimization", false, false)
1798
1799Pass *llvm::createObjCARCOptPass() {
1800 return new ObjCARCOpt();
1801}
1802
1803void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1804 AU.addRequired<ObjCARCAliasAnalysis>();
1805 AU.addRequired<AliasAnalysis>();
1806 // ARC optimization doesn't currently split critical edges.
1807 AU.setPreservesCFG();
1808}
1809
Dan Gohman79522dc2012-01-13 00:39:07 +00001810bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1811 // Without the magic metadata tag, we have to assume this might be an
1812 // objc_retainBlock call inserted to convert a block pointer to an id,
1813 // in which case it really is needed.
1814 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1815 return false;
1816
1817 // If the pointer "escapes" (not including being used in a call),
1818 // the copy may be needed.
1819 if (DoesObjCBlockEscape(Inst))
1820 return false;
1821
1822 // Otherwise, it's not needed.
1823 return true;
1824}
1825
John McCall9fbd3182011-06-15 23:37:01 +00001826Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1827 if (!RetainRVCallee) {
1828 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001829 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001830 Type *Params[] = { I8X };
1831 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001832 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001833 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001834 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001835 RetainRVCallee =
1836 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001837 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001838 }
1839 return RetainRVCallee;
1840}
1841
1842Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1843 if (!AutoreleaseRVCallee) {
1844 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001845 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001846 Type *Params[] = { I8X };
1847 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001848 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001849 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001850 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001851 AutoreleaseRVCallee =
1852 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001853 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001854 }
1855 return AutoreleaseRVCallee;
1856}
1857
1858Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1859 if (!ReleaseCallee) {
1860 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001861 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001862 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001863 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001864 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001865 ReleaseCallee =
1866 M->getOrInsertFunction(
1867 "objc_release",
1868 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001869 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001870 }
1871 return ReleaseCallee;
1872}
1873
1874Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1875 if (!RetainCallee) {
1876 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001877 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001878 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001879 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001880 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001881 RetainCallee =
1882 M->getOrInsertFunction(
1883 "objc_retain",
1884 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001885 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001886 }
1887 return RetainCallee;
1888}
1889
Dan Gohman44280692011-07-22 22:29:21 +00001890Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1891 if (!RetainBlockCallee) {
1892 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001893 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001894 // objc_retainBlock is not nounwind because it calls user copy constructors
1895 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001896 RetainBlockCallee =
1897 M->getOrInsertFunction(
1898 "objc_retainBlock",
1899 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001900 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001901 }
1902 return RetainBlockCallee;
1903}
1904
John McCall9fbd3182011-06-15 23:37:01 +00001905Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1906 if (!AutoreleaseCallee) {
1907 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001908 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001909 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001910 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001911 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001912 AutoreleaseCallee =
1913 M->getOrInsertFunction(
1914 "objc_autorelease",
1915 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001916 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001917 }
1918 return AutoreleaseCallee;
1919}
1920
Dan Gohman230768b2012-09-04 23:16:20 +00001921/// IsPotentialUse - Test whether the given value is possible a
1922/// reference-counted pointer, including tests which utilize AliasAnalysis.
1923static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1924 // First make the rudimentary check.
1925 if (!IsPotentialUse(Op))
1926 return false;
1927
1928 // Objects in constant memory are not reference-counted.
1929 if (AA.pointsToConstantMemory(Op))
1930 return false;
1931
1932 // Pointers in constant memory are not pointing to reference-counted objects.
1933 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1934 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1935 return false;
1936
1937 // Otherwise assume the worst.
1938 return true;
1939}
1940
John McCall9fbd3182011-06-15 23:37:01 +00001941/// CanAlterRefCount - Test whether the given instruction can result in a
1942/// reference count modification (positive or negative) for the pointer's
1943/// object.
1944static bool
1945CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1946 ProvenanceAnalysis &PA, InstructionClass Class) {
1947 switch (Class) {
1948 case IC_Autorelease:
1949 case IC_AutoreleaseRV:
1950 case IC_User:
1951 // These operations never directly modify a reference count.
1952 return false;
1953 default: break;
1954 }
1955
1956 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1957 assert(CS && "Only calls can alter reference counts!");
1958
1959 // See if AliasAnalysis can help us with the call.
1960 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1961 if (AliasAnalysis::onlyReadsMemory(MRB))
1962 return false;
1963 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1964 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1965 I != E; ++I) {
1966 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001967 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001968 return true;
1969 }
1970 return false;
1971 }
1972
1973 // Assume the worst.
1974 return true;
1975}
1976
1977/// CanUse - Test whether the given instruction can "use" the given pointer's
1978/// object in a way that requires the reference count to be positive.
1979static bool
1980CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1981 InstructionClass Class) {
1982 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1983 if (Class == IC_Call)
1984 return false;
1985
1986 // Consider various instructions which may have pointer arguments which are
1987 // not "uses".
1988 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1989 // Comparing a pointer with null, or any other constant, isn't really a use,
1990 // because we don't care what the pointer points to, or about the values
1991 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001992 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001993 return false;
1994 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1995 // For calls, just check the arguments (and not the callee operand).
1996 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1997 OE = CS.arg_end(); OI != OE; ++OI) {
1998 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001999 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002000 return true;
2001 }
2002 return false;
2003 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2004 // Special-case stores, because we don't care about the stored value, just
2005 // the store address.
2006 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2007 // If we can't tell what the underlying object was, assume there is a
2008 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00002009 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00002010 }
2011
2012 // Check each operand for a match.
2013 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2014 OI != OE; ++OI) {
2015 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002016 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002017 return true;
2018 }
2019 return false;
2020}
2021
2022/// CanInterruptRV - Test whether the given instruction can autorelease
2023/// any pointer or cause an autoreleasepool pop.
2024static bool
2025CanInterruptRV(InstructionClass Class) {
2026 switch (Class) {
2027 case IC_AutoreleasepoolPop:
2028 case IC_CallOrUser:
2029 case IC_Call:
2030 case IC_Autorelease:
2031 case IC_AutoreleaseRV:
2032 case IC_FusedRetainAutorelease:
2033 case IC_FusedRetainAutoreleaseRV:
2034 return true;
2035 default:
2036 return false;
2037 }
2038}
2039
2040namespace {
2041 /// DependenceKind - There are several kinds of dependence-like concepts in
2042 /// use here.
2043 enum DependenceKind {
2044 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002045 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002046 CanChangeRetainCount,
2047 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2048 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2049 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2050 };
2051}
2052
2053/// Depends - Test if there can be dependencies on Inst through Arg. This
2054/// function only tests dependencies relevant for removing pairs of calls.
2055static bool
2056Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2057 ProvenanceAnalysis &PA) {
2058 // If we've reached the definition of Arg, stop.
2059 if (Inst == Arg)
2060 return true;
2061
2062 switch (Flavor) {
2063 case NeedsPositiveRetainCount: {
2064 InstructionClass Class = GetInstructionClass(Inst);
2065 switch (Class) {
2066 case IC_AutoreleasepoolPop:
2067 case IC_AutoreleasepoolPush:
2068 case IC_None:
2069 return false;
2070 default:
2071 return CanUse(Inst, Arg, PA, Class);
2072 }
2073 }
2074
Dan Gohman511568d2012-04-13 00:59:57 +00002075 case AutoreleasePoolBoundary: {
2076 InstructionClass Class = GetInstructionClass(Inst);
2077 switch (Class) {
2078 case IC_AutoreleasepoolPop:
2079 case IC_AutoreleasepoolPush:
2080 // These mark the end and begin of an autorelease pool scope.
2081 return true;
2082 default:
2083 // Nothing else does this.
2084 return false;
2085 }
2086 }
2087
John McCall9fbd3182011-06-15 23:37:01 +00002088 case CanChangeRetainCount: {
2089 InstructionClass Class = GetInstructionClass(Inst);
2090 switch (Class) {
2091 case IC_AutoreleasepoolPop:
2092 // Conservatively assume this can decrement any count.
2093 return true;
2094 case IC_AutoreleasepoolPush:
2095 case IC_None:
2096 return false;
2097 default:
2098 return CanAlterRefCount(Inst, Arg, PA, Class);
2099 }
2100 }
2101
2102 case RetainAutoreleaseDep:
2103 switch (GetBasicInstructionClass(Inst)) {
2104 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002105 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002106 // Don't merge an objc_autorelease with an objc_retain inside a different
2107 // autoreleasepool scope.
2108 return true;
2109 case IC_Retain:
2110 case IC_RetainRV:
2111 // Check for a retain of the same pointer for merging.
2112 return GetObjCArg(Inst) == Arg;
2113 default:
2114 // Nothing else matters for objc_retainAutorelease formation.
2115 return false;
2116 }
John McCall9fbd3182011-06-15 23:37:01 +00002117
2118 case RetainAutoreleaseRVDep: {
2119 InstructionClass Class = GetBasicInstructionClass(Inst);
2120 switch (Class) {
2121 case IC_Retain:
2122 case IC_RetainRV:
2123 // Check for a retain of the same pointer for merging.
2124 return GetObjCArg(Inst) == Arg;
2125 default:
2126 // Anything that can autorelease interrupts
2127 // retainAutoreleaseReturnValue formation.
2128 return CanInterruptRV(Class);
2129 }
John McCall9fbd3182011-06-15 23:37:01 +00002130 }
2131
2132 case RetainRVDep:
2133 return CanInterruptRV(GetBasicInstructionClass(Inst));
2134 }
2135
2136 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002137}
2138
2139/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2140/// find local and non-local dependencies on Arg.
2141/// TODO: Cache results?
2142static void
2143FindDependencies(DependenceKind Flavor,
2144 const Value *Arg,
2145 BasicBlock *StartBB, Instruction *StartInst,
2146 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2147 SmallPtrSet<const BasicBlock *, 4> &Visited,
2148 ProvenanceAnalysis &PA) {
2149 BasicBlock::iterator StartPos = StartInst;
2150
2151 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2152 Worklist.push_back(std::make_pair(StartBB, StartPos));
2153 do {
2154 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2155 Worklist.pop_back_val();
2156 BasicBlock *LocalStartBB = Pair.first;
2157 BasicBlock::iterator LocalStartPos = Pair.second;
2158 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2159 for (;;) {
2160 if (LocalStartPos == StartBBBegin) {
2161 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2162 if (PI == PE)
2163 // If we've reached the function entry, produce a null dependence.
2164 DependingInstructions.insert(0);
2165 else
2166 // Add the predecessors to the worklist.
2167 do {
2168 BasicBlock *PredBB = *PI;
2169 if (Visited.insert(PredBB))
2170 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2171 } while (++PI != PE);
2172 break;
2173 }
2174
2175 Instruction *Inst = --LocalStartPos;
2176 if (Depends(Flavor, Inst, Arg, PA)) {
2177 DependingInstructions.insert(Inst);
2178 break;
2179 }
2180 }
2181 } while (!Worklist.empty());
2182
2183 // Determine whether the original StartBB post-dominates all of the blocks we
2184 // visited. If not, insert a sentinal indicating that most optimizations are
2185 // not safe.
2186 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2187 E = Visited.end(); I != E; ++I) {
2188 const BasicBlock *BB = *I;
2189 if (BB == StartBB)
2190 continue;
2191 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2192 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2193 const BasicBlock *Succ = *SI;
2194 if (Succ != StartBB && !Visited.count(Succ)) {
2195 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2196 return;
2197 }
2198 }
2199 }
2200}
2201
2202static bool isNullOrUndef(const Value *V) {
2203 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2204}
2205
2206static bool isNoopInstruction(const Instruction *I) {
2207 return isa<BitCastInst>(I) ||
2208 (isa<GetElementPtrInst>(I) &&
2209 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2210}
2211
2212/// OptimizeRetainCall - Turn objc_retain into
2213/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2214void
2215ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002216 ImmutableCallSite CS(GetObjCArg(Retain));
2217 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002218 if (!Call) return;
2219 if (Call->getParent() != Retain->getParent()) return;
2220
2221 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002222 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002223 ++I;
2224 while (isNoopInstruction(I)) ++I;
2225 if (&*I != Retain)
2226 return;
2227
2228 // Turn it to an objc_retainAutoreleasedReturnValue..
2229 Changed = true;
2230 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002231
Michael Gottesman715f6a62013-01-04 21:30:38 +00002232 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002233 "objc_retain => objc_retainAutoreleasedReturnValue"
2234 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002235 " Old: "
2236 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002237
John McCall9fbd3182011-06-15 23:37:01 +00002238 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002239
2240 DEBUG(dbgs() << " New: "
2241 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002242}
2243
2244/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002245/// objc_retain if the operand is not a return value. Or, if it can be paired
2246/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002247bool
2248ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002249 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002250 const Value *Arg = GetObjCArg(RetainRV);
2251 ImmutableCallSite CS(Arg);
2252 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002253 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002254 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002255 ++I;
2256 while (isNoopInstruction(I)) ++I;
2257 if (&*I == RetainRV)
2258 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002259 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002260 BasicBlock *RetainRVParent = RetainRV->getParent();
2261 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002262 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002263 while (isNoopInstruction(I)) ++I;
2264 if (&*I == RetainRV)
2265 return false;
2266 }
John McCall9fbd3182011-06-15 23:37:01 +00002267 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002268 }
John McCall9fbd3182011-06-15 23:37:01 +00002269
2270 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2271 // pointer. In this case, we can delete the pair.
2272 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2273 if (I != Begin) {
2274 do --I; while (I != Begin && isNoopInstruction(I));
2275 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2276 GetObjCArg(I) == Arg) {
2277 Changed = true;
2278 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002279
Michael Gottesman87a0f022013-01-05 17:55:35 +00002280 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2281 << " Erasing " << *RetainRV
2282 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002283
John McCall9fbd3182011-06-15 23:37:01 +00002284 EraseInstruction(I);
2285 EraseInstruction(RetainRV);
2286 return true;
2287 }
2288 }
2289
2290 // Turn it to a plain objc_retain.
2291 Changed = true;
2292 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002293
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002294 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2295 "objc_retainAutoreleasedReturnValue => "
2296 "objc_retain since the operand is not a return value.\n"
2297 " Old: "
2298 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002299
John McCall9fbd3182011-06-15 23:37:01 +00002300 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002301
2302 DEBUG(dbgs() << " New: "
2303 << *RetainRV << "\n");
2304
John McCall9fbd3182011-06-15 23:37:01 +00002305 return false;
2306}
2307
2308/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2309/// objc_autorelease if the result is not used as a return value.
2310void
Michael Gottesman0e385452013-01-12 01:25:19 +00002311ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2312 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002313 // Check for a return of the pointer value.
2314 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002315 SmallVector<const Value *, 2> Users;
2316 Users.push_back(Ptr);
2317 do {
2318 Ptr = Users.pop_back_val();
2319 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2320 UI != UE; ++UI) {
2321 const User *I = *UI;
2322 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2323 return;
2324 if (isa<BitCastInst>(I))
2325 Users.push_back(I);
2326 }
2327 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002328
2329 Changed = true;
2330 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002331
2332 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2333 "objc_autoreleaseReturnValue => "
2334 "objc_autorelease since its operand is not used as a return "
2335 "value.\n"
2336 " Old: "
2337 << *AutoreleaseRV << "\n");
2338
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002339 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2340 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002341 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002342 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002343 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002344
Michael Gottesman48239c72013-01-06 21:07:11 +00002345 DEBUG(dbgs() << " New: "
2346 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002347
John McCall9fbd3182011-06-15 23:37:01 +00002348}
2349
2350/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2351/// simplifications without doing any additional analysis.
2352void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2353 // Reset all the flags in preparation for recomputing them.
2354 UsedInThisFunction = 0;
2355
2356 // Visit all objc_* calls in F.
2357 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2358 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002359
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002360 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002361 *Inst << "\n");
2362
John McCall9fbd3182011-06-15 23:37:01 +00002363 InstructionClass Class = GetBasicInstructionClass(Inst);
2364
2365 switch (Class) {
2366 default: break;
2367
2368 // Delete no-op casts. These function calls have special semantics, but
2369 // the semantics are entirely implemented via lowering in the front-end,
2370 // so by the time they reach the optimizer, they are just no-op calls
2371 // which return their argument.
2372 //
2373 // There are gray areas here, as the ability to cast reference-counted
2374 // pointers to raw void* and back allows code to break ARC assumptions,
2375 // however these are currently considered to be unimportant.
2376 case IC_NoopCast:
2377 Changed = true;
2378 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002379 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2380 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002381 EraseInstruction(Inst);
2382 continue;
2383
2384 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2385 case IC_StoreWeak:
2386 case IC_LoadWeak:
2387 case IC_LoadWeakRetained:
2388 case IC_InitWeak:
2389 case IC_DestroyWeak: {
2390 CallInst *CI = cast<CallInst>(Inst);
2391 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002392 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002393 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002394 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2395 Constant::getNullValue(Ty),
2396 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002397 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002398 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2399 "pointer-to-weak-pointer is undefined behavior.\n"
2400 " Old = " << *CI <<
2401 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002402 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002403 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002404 CI->eraseFromParent();
2405 continue;
2406 }
2407 break;
2408 }
2409 case IC_CopyWeak:
2410 case IC_MoveWeak: {
2411 CallInst *CI = cast<CallInst>(Inst);
2412 if (isNullOrUndef(CI->getArgOperand(0)) ||
2413 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002414 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002415 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002416 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2417 Constant::getNullValue(Ty),
2418 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002419
2420 llvm::Value *NewValue = UndefValue::get(CI->getType());
2421 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2422 "pointer-to-weak-pointer is undefined behavior.\n"
2423 " Old = " << *CI <<
2424 "\n New = " <<
2425 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002426
Michael Gottesmane5494922013-01-06 21:54:30 +00002427 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002428 CI->eraseFromParent();
2429 continue;
2430 }
2431 break;
2432 }
2433 case IC_Retain:
2434 OptimizeRetainCall(F, Inst);
2435 break;
2436 case IC_RetainRV:
2437 if (OptimizeRetainRVCall(F, Inst))
2438 continue;
2439 break;
2440 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002441 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002442 break;
2443 }
2444
2445 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2446 if (IsAutorelease(Class) && Inst->use_empty()) {
2447 CallInst *Call = cast<CallInst>(Inst);
2448 const Value *Arg = Call->getArgOperand(0);
2449 Arg = FindSingleUseIdentifiedObject(Arg);
2450 if (Arg) {
2451 Changed = true;
2452 ++NumAutoreleases;
2453
2454 // Create the declaration lazily.
2455 LLVMContext &C = Inst->getContext();
2456 CallInst *NewCall =
2457 CallInst::Create(getReleaseCallee(F.getParent()),
2458 Call->getArgOperand(0), "", Call);
2459 NewCall->setMetadata(ImpreciseReleaseMDKind,
2460 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002461
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002462 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2463 "objc_autorelease(x) with objc_release(x) since x is "
2464 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002465 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002466 "\n New: " <<
2467 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002468
John McCall9fbd3182011-06-15 23:37:01 +00002469 EraseInstruction(Call);
2470 Inst = NewCall;
2471 Class = IC_Release;
2472 }
2473 }
2474
2475 // For functions which can never be passed stack arguments, add
2476 // a tail keyword.
2477 if (IsAlwaysTail(Class)) {
2478 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002479 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2480 " to function since it can never be passed stack args: " << *Inst <<
2481 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002482 cast<CallInst>(Inst)->setTailCall();
2483 }
2484
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002485 // Ensure that functions that can never have a "tail" keyword due to the
2486 // semantics of ARC truly do not do so.
2487 if (IsNeverTail(Class)) {
2488 Changed = true;
2489 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2490 " from function: " << *Inst <<
2491 "\n");
2492 cast<CallInst>(Inst)->setTailCall(false);
2493 }
2494
John McCall9fbd3182011-06-15 23:37:01 +00002495 // Set nounwind as needed.
2496 if (IsNoThrow(Class)) {
2497 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002498 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2499 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002500 cast<CallInst>(Inst)->setDoesNotThrow();
2501 }
2502
2503 if (!IsNoopOnNull(Class)) {
2504 UsedInThisFunction |= 1 << Class;
2505 continue;
2506 }
2507
2508 const Value *Arg = GetObjCArg(Inst);
2509
2510 // ARC calls with null are no-ops. Delete them.
2511 if (isNullOrUndef(Arg)) {
2512 Changed = true;
2513 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002514 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2515 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002516 EraseInstruction(Inst);
2517 continue;
2518 }
2519
2520 // Keep track of which of retain, release, autorelease, and retain_block
2521 // are actually present in this function.
2522 UsedInThisFunction |= 1 << Class;
2523
2524 // If Arg is a PHI, and one or more incoming values to the
2525 // PHI are null, and the call is control-equivalent to the PHI, and there
2526 // are no relevant side effects between the PHI and the call, the call
2527 // could be pushed up to just those paths with non-null incoming values.
2528 // For now, don't bother splitting critical edges for this.
2529 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2530 Worklist.push_back(std::make_pair(Inst, Arg));
2531 do {
2532 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2533 Inst = Pair.first;
2534 Arg = Pair.second;
2535
2536 const PHINode *PN = dyn_cast<PHINode>(Arg);
2537 if (!PN) continue;
2538
2539 // Determine if the PHI has any null operands, or any incoming
2540 // critical edges.
2541 bool HasNull = false;
2542 bool HasCriticalEdges = false;
2543 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2544 Value *Incoming =
2545 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2546 if (isNullOrUndef(Incoming))
2547 HasNull = true;
2548 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2549 .getNumSuccessors() != 1) {
2550 HasCriticalEdges = true;
2551 break;
2552 }
2553 }
2554 // If we have null operands and no critical edges, optimize.
2555 if (!HasCriticalEdges && HasNull) {
2556 SmallPtrSet<Instruction *, 4> DependingInstructions;
2557 SmallPtrSet<const BasicBlock *, 4> Visited;
2558
2559 // Check that there is nothing that cares about the reference
2560 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002561 switch (Class) {
2562 case IC_Retain:
2563 case IC_RetainBlock:
2564 // These can always be moved up.
2565 break;
2566 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002567 // These can't be moved across things that care about the retain
2568 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002569 FindDependencies(NeedsPositiveRetainCount, Arg,
2570 Inst->getParent(), Inst,
2571 DependingInstructions, Visited, PA);
2572 break;
2573 case IC_Autorelease:
2574 // These can't be moved across autorelease pool scope boundaries.
2575 FindDependencies(AutoreleasePoolBoundary, Arg,
2576 Inst->getParent(), Inst,
2577 DependingInstructions, Visited, PA);
2578 break;
2579 case IC_RetainRV:
2580 case IC_AutoreleaseRV:
2581 // Don't move these; the RV optimization depends on the autoreleaseRV
2582 // being tail called, and the retainRV being immediately after a call
2583 // (which might still happen if we get lucky with codegen layout, but
2584 // it's not worth taking the chance).
2585 continue;
2586 default:
2587 llvm_unreachable("Invalid dependence flavor");
2588 }
2589
John McCall9fbd3182011-06-15 23:37:01 +00002590 if (DependingInstructions.size() == 1 &&
2591 *DependingInstructions.begin() == PN) {
2592 Changed = true;
2593 ++NumPartialNoops;
2594 // Clone the call into each predecessor that has a non-null value.
2595 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002596 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002597 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2598 Value *Incoming =
2599 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2600 if (!isNullOrUndef(Incoming)) {
2601 CallInst *Clone = cast<CallInst>(CInst->clone());
2602 Value *Op = PN->getIncomingValue(i);
2603 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2604 if (Op->getType() != ParamTy)
2605 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2606 Clone->setArgOperand(0, Op);
2607 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002608
2609 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2610 << *CInst << "\n"
2611 " And inserting "
2612 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002613 Worklist.push_back(std::make_pair(Clone, Incoming));
2614 }
2615 }
2616 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002617 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002618 EraseInstruction(CInst);
2619 continue;
2620 }
2621 }
2622 } while (!Worklist.empty());
2623 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002624 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002625}
2626
2627/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2628/// control flow, or other CFG structures where moving code across the edge
2629/// would result in it being executed more.
2630void
2631ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2632 DenseMap<const BasicBlock *, BBState> &BBStates,
2633 BBState &MyStates) const {
2634 // If any top-down local-use or possible-dec has a succ which is earlier in
2635 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002636 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002637 E = MyStates.top_down_ptr_end(); I != E; ++I)
2638 switch (I->second.GetSeq()) {
2639 default: break;
2640 case S_Use: {
2641 const Value *Arg = I->first;
2642 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2643 bool SomeSuccHasSame = false;
2644 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002645 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002646 succ_const_iterator SI(TI), SE(TI, false);
2647
2648 // If the terminator is an invoke marked with the
2649 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2650 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002651 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2652 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2653 "terminator marked with "
2654 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2655 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002656 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002657 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002658
2659 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002660 Sequence SuccSSeq = S_None;
2661 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002662 // If VisitBottomUp has pointer information for this successor, take
2663 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002664 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2665 BBStates.find(*SI);
2666 assert(BBI != BBStates.end());
2667 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2668 SuccSSeq = SuccS.GetSeq();
2669 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002670 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002671 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002672 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002673 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002674 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002675 break;
2676 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002677 continue;
2678 }
John McCall9fbd3182011-06-15 23:37:01 +00002679 case S_Use:
2680 SomeSuccHasSame = true;
2681 break;
2682 case S_Stop:
2683 case S_Release:
2684 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002685 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002686 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002687 break;
2688 case S_Retain:
2689 llvm_unreachable("bottom-up pointer in retain state!");
2690 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002691 }
John McCall9fbd3182011-06-15 23:37:01 +00002692 // If the state at the other end of any of the successor edges
2693 // matches the current state, require all edges to match. This
2694 // guards against loops in the middle of a sequence.
2695 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002696 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002697 break;
John McCall9fbd3182011-06-15 23:37:01 +00002698 }
2699 case S_CanRelease: {
2700 const Value *Arg = I->first;
2701 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2702 bool SomeSuccHasSame = false;
2703 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002704 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002705 succ_const_iterator SI(TI), SE(TI, false);
2706
2707 // If the terminator is an invoke marked with the
2708 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2709 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002710 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2711 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2712 "terminator marked with "
2713 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2714 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002715 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002716 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002717
2718 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002719 Sequence SuccSSeq = S_None;
2720 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002721 // If VisitBottomUp has pointer information for this successor, take
2722 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002723 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2724 BBStates.find(*SI);
2725 assert(BBI != BBStates.end());
2726 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2727 SuccSSeq = SuccS.GetSeq();
2728 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002729 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002730 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002731 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002732 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002733 break;
2734 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002735 continue;
2736 }
John McCall9fbd3182011-06-15 23:37:01 +00002737 case S_CanRelease:
2738 SomeSuccHasSame = true;
2739 break;
2740 case S_Stop:
2741 case S_Release:
2742 case S_MovableRelease:
2743 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002744 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002745 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002746 break;
2747 case S_Retain:
2748 llvm_unreachable("bottom-up pointer in retain state!");
2749 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002750 }
John McCall9fbd3182011-06-15 23:37:01 +00002751 // If the state at the other end of any of the successor edges
2752 // matches the current state, require all edges to match. This
2753 // guards against loops in the middle of a sequence.
2754 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002755 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002756 break;
John McCall9fbd3182011-06-15 23:37:01 +00002757 }
2758 }
2759}
2760
2761bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002762ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002763 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002764 MapVector<Value *, RRInfo> &Retains,
2765 BBState &MyStates) {
2766 bool NestingDetected = false;
2767 InstructionClass Class = GetInstructionClass(Inst);
2768 const Value *Arg = 0;
2769
2770 switch (Class) {
2771 case IC_Release: {
2772 Arg = GetObjCArg(Inst);
2773
2774 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2775
2776 // If we see two releases in a row on the same pointer. If so, make
2777 // a note, and we'll cicle back to revisit it after we've
2778 // hopefully eliminated the second release, which may allow us to
2779 // eliminate the first release too.
2780 // Theoretically we could implement removal of nested retain+release
2781 // pairs by making PtrState hold a stack of states, but this is
2782 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmancf140052013-01-13 07:00:51 +00002783 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2784 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2785 "releases (i.e. a release pair)\n");
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002786 NestingDetected = true;
Michael Gottesmancf140052013-01-13 07:00:51 +00002787 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002788
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002789 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002790 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002791 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002792 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002793 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2794 S.RRI.Calls.insert(Inst);
2795
Dan Gohman230768b2012-09-04 23:16:20 +00002796 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002797 break;
2798 }
2799 case IC_RetainBlock:
2800 // An objc_retainBlock call with just a use may need to be kept,
2801 // because it may be copying a block from the stack to the heap.
2802 if (!IsRetainBlockOptimizable(Inst))
2803 break;
2804 // FALLTHROUGH
2805 case IC_Retain:
2806 case IC_RetainRV: {
2807 Arg = GetObjCArg(Inst);
2808
2809 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002810 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002811
2812 switch (S.GetSeq()) {
2813 case S_Stop:
2814 case S_Release:
2815 case S_MovableRelease:
2816 case S_Use:
2817 S.RRI.ReverseInsertPts.clear();
2818 // FALL THROUGH
2819 case S_CanRelease:
2820 // Don't do retain+release tracking for IC_RetainRV, because it's
2821 // better to let it remain as the first instruction after a call.
2822 if (Class != IC_RetainRV) {
2823 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2824 Retains[Inst] = S.RRI;
2825 }
2826 S.ClearSequenceProgress();
2827 break;
2828 case S_None:
2829 break;
2830 case S_Retain:
2831 llvm_unreachable("bottom-up pointer in retain state!");
2832 }
2833 return NestingDetected;
2834 }
2835 case IC_AutoreleasepoolPop:
2836 // Conservatively, clear MyStates for all known pointers.
2837 MyStates.clearBottomUpPointers();
2838 return NestingDetected;
2839 case IC_AutoreleasepoolPush:
2840 case IC_None:
2841 // These are irrelevant.
2842 return NestingDetected;
2843 default:
2844 break;
2845 }
2846
2847 // Consider any other possible effects of this instruction on each
2848 // pointer being tracked.
2849 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2850 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2851 const Value *Ptr = MI->first;
2852 if (Ptr == Arg)
2853 continue; // Handled above.
2854 PtrState &S = MI->second;
2855 Sequence Seq = S.GetSeq();
2856
2857 // Check for possible releases.
2858 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002859 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002860 switch (Seq) {
2861 case S_Use:
2862 S.SetSeq(S_CanRelease);
2863 continue;
2864 case S_CanRelease:
2865 case S_Release:
2866 case S_MovableRelease:
2867 case S_Stop:
2868 case S_None:
2869 break;
2870 case S_Retain:
2871 llvm_unreachable("bottom-up pointer in retain state!");
2872 }
2873 }
2874
2875 // Check for possible direct uses.
2876 switch (Seq) {
2877 case S_Release:
2878 case S_MovableRelease:
2879 if (CanUse(Inst, Ptr, PA, Class)) {
2880 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002881 // If this is an invoke instruction, we're scanning it as part of
2882 // one of its successor blocks, since we can't insert code after it
2883 // in its own block, and we don't want to split critical edges.
2884 if (isa<InvokeInst>(Inst))
2885 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2886 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002887 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002888 S.SetSeq(S_Use);
2889 } else if (Seq == S_Release &&
2890 (Class == IC_User || Class == IC_CallOrUser)) {
2891 // Non-movable releases depend on any possible objc pointer use.
2892 S.SetSeq(S_Stop);
2893 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002894 // As above; handle invoke specially.
2895 if (isa<InvokeInst>(Inst))
2896 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2897 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002898 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002899 }
2900 break;
2901 case S_Stop:
2902 if (CanUse(Inst, Ptr, PA, Class))
2903 S.SetSeq(S_Use);
2904 break;
2905 case S_CanRelease:
2906 case S_Use:
2907 case S_None:
2908 break;
2909 case S_Retain:
2910 llvm_unreachable("bottom-up pointer in retain state!");
2911 }
2912 }
2913
2914 return NestingDetected;
2915}
2916
2917bool
John McCall9fbd3182011-06-15 23:37:01 +00002918ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2919 DenseMap<const BasicBlock *, BBState> &BBStates,
2920 MapVector<Value *, RRInfo> &Retains) {
2921 bool NestingDetected = false;
2922 BBState &MyStates = BBStates[BB];
2923
2924 // Merge the states from each successor to compute the initial state
2925 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002926 BBState::edge_iterator SI(MyStates.succ_begin()),
2927 SE(MyStates.succ_end());
2928 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002929 const BasicBlock *Succ = *SI;
2930 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2931 assert(I != BBStates.end());
2932 MyStates.InitFromSucc(I->second);
2933 ++SI;
2934 for (; SI != SE; ++SI) {
2935 Succ = *SI;
2936 I = BBStates.find(Succ);
2937 assert(I != BBStates.end());
2938 MyStates.MergeSucc(I->second);
2939 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002940 }
John McCall9fbd3182011-06-15 23:37:01 +00002941
2942 // Visit all the instructions, bottom-up.
2943 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2944 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002945
2946 // Invoke instructions are visited as part of their successors (below).
2947 if (isa<InvokeInst>(Inst))
2948 continue;
2949
Michael Gottesmancf140052013-01-13 07:00:51 +00002950 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2951
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002952 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2953 }
2954
Dan Gohman447989c2012-04-27 18:56:31 +00002955 // If there's a predecessor with an invoke, visit the invoke as if it were
2956 // part of this block, since we can't insert code after an invoke in its own
2957 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002958 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2959 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002960 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002961 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2962 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002963 }
John McCall9fbd3182011-06-15 23:37:01 +00002964
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002965 return NestingDetected;
2966}
John McCall9fbd3182011-06-15 23:37:01 +00002967
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002968bool
2969ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2970 DenseMap<Value *, RRInfo> &Releases,
2971 BBState &MyStates) {
2972 bool NestingDetected = false;
2973 InstructionClass Class = GetInstructionClass(Inst);
2974 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002975
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002976 switch (Class) {
2977 case IC_RetainBlock:
2978 // An objc_retainBlock call with just a use may need to be kept,
2979 // because it may be copying a block from the stack to the heap.
2980 if (!IsRetainBlockOptimizable(Inst))
2981 break;
2982 // FALLTHROUGH
2983 case IC_Retain:
2984 case IC_RetainRV: {
2985 Arg = GetObjCArg(Inst);
2986
2987 PtrState &S = MyStates.getPtrTopDownState(Arg);
2988
2989 // Don't do retain+release tracking for IC_RetainRV, because it's
2990 // better to let it remain as the first instruction after a call.
2991 if (Class != IC_RetainRV) {
2992 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002993 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002994 // hopefully eliminated the second retain, which may allow us to
2995 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002996 // Theoretically we could implement removal of nested retain+release
2997 // pairs by making PtrState hold a stack of states, but this is
2998 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002999 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00003000 NestingDetected = true;
3001
Dan Gohman50ade652012-04-25 00:50:46 +00003002 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003003 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00003004 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00003005 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00003006 }
John McCall9fbd3182011-06-15 23:37:01 +00003007
Dan Gohman230768b2012-09-04 23:16:20 +00003008 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00003009
3010 // A retain can be a potential use; procede to the generic checking
3011 // code below.
3012 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003013 }
3014 case IC_Release: {
3015 Arg = GetObjCArg(Inst);
3016
3017 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00003018 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003019
3020 switch (S.GetSeq()) {
3021 case S_Retain:
3022 case S_CanRelease:
3023 S.RRI.ReverseInsertPts.clear();
3024 // FALL THROUGH
3025 case S_Use:
3026 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3027 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3028 Releases[Inst] = S.RRI;
3029 S.ClearSequenceProgress();
3030 break;
3031 case S_None:
3032 break;
3033 case S_Stop:
3034 case S_Release:
3035 case S_MovableRelease:
3036 llvm_unreachable("top-down pointer in release state!");
3037 }
3038 break;
3039 }
3040 case IC_AutoreleasepoolPop:
3041 // Conservatively, clear MyStates for all known pointers.
3042 MyStates.clearTopDownPointers();
3043 return NestingDetected;
3044 case IC_AutoreleasepoolPush:
3045 case IC_None:
3046 // These are irrelevant.
3047 return NestingDetected;
3048 default:
3049 break;
3050 }
3051
3052 // Consider any other possible effects of this instruction on each
3053 // pointer being tracked.
3054 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3055 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3056 const Value *Ptr = MI->first;
3057 if (Ptr == Arg)
3058 continue; // Handled above.
3059 PtrState &S = MI->second;
3060 Sequence Seq = S.GetSeq();
3061
3062 // Check for possible releases.
3063 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003064 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003065 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003066 case S_Retain:
3067 S.SetSeq(S_CanRelease);
3068 assert(S.RRI.ReverseInsertPts.empty());
3069 S.RRI.ReverseInsertPts.insert(Inst);
3070
3071 // One call can't cause a transition from S_Retain to S_CanRelease
3072 // and S_CanRelease to S_Use. If we've made the first transition,
3073 // we're done.
3074 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003075 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003076 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003077 case S_None:
3078 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003079 case S_Stop:
3080 case S_Release:
3081 case S_MovableRelease:
3082 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003083 }
3084 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003085
3086 // Check for possible direct uses.
3087 switch (Seq) {
3088 case S_CanRelease:
3089 if (CanUse(Inst, Ptr, PA, Class))
3090 S.SetSeq(S_Use);
3091 break;
3092 case S_Retain:
3093 case S_Use:
3094 case S_None:
3095 break;
3096 case S_Stop:
3097 case S_Release:
3098 case S_MovableRelease:
3099 llvm_unreachable("top-down pointer in release state!");
3100 }
John McCall9fbd3182011-06-15 23:37:01 +00003101 }
3102
3103 return NestingDetected;
3104}
3105
3106bool
3107ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3108 DenseMap<const BasicBlock *, BBState> &BBStates,
3109 DenseMap<Value *, RRInfo> &Releases) {
3110 bool NestingDetected = false;
3111 BBState &MyStates = BBStates[BB];
3112
3113 // Merge the states from each predecessor to compute the initial state
3114 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003115 BBState::edge_iterator PI(MyStates.pred_begin()),
3116 PE(MyStates.pred_end());
3117 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003118 const BasicBlock *Pred = *PI;
3119 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3120 assert(I != BBStates.end());
3121 MyStates.InitFromPred(I->second);
3122 ++PI;
3123 for (; PI != PE; ++PI) {
3124 Pred = *PI;
3125 I = BBStates.find(Pred);
3126 assert(I != BBStates.end());
3127 MyStates.MergePred(I->second);
3128 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003129 }
John McCall9fbd3182011-06-15 23:37:01 +00003130
3131 // Visit all the instructions, top-down.
3132 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3133 Instruction *Inst = I;
Michael Gottesmancf140052013-01-13 07:00:51 +00003134
3135 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3136
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003137 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003138 }
3139
3140 CheckForCFGHazards(BB, BBStates, MyStates);
3141 return NestingDetected;
3142}
3143
Dan Gohman59a1c932011-12-12 19:42:25 +00003144static void
3145ComputePostOrders(Function &F,
3146 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003147 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3148 unsigned NoObjCARCExceptionsMDKind,
3149 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003150 /// Visited - The visited set, for doing DFS walks.
3151 SmallPtrSet<BasicBlock *, 16> Visited;
3152
3153 // Do DFS, computing the PostOrder.
3154 SmallPtrSet<BasicBlock *, 16> OnStack;
3155 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003156
3157 // Functions always have exactly one entry block, and we don't have
3158 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003159 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003160 BBState &MyStates = BBStates[EntryBB];
3161 MyStates.SetAsEntry();
3162 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3163 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003164 Visited.insert(EntryBB);
3165 OnStack.insert(EntryBB);
3166 do {
3167 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003168 BasicBlock *CurrBB = SuccStack.back().first;
3169 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3170 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003171
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003172 // If the terminator is an invoke marked with the
3173 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3174 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00003175 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3176 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3177 "terminator marked with "
3178 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3179 "edge.\n");
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003180 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00003181 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003182
3183 while (SuccStack.back().second != SE) {
3184 BasicBlock *SuccBB = *SuccStack.back().second++;
3185 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003186 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3187 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003188 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003189 BBState &SuccStates = BBStates[SuccBB];
3190 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003191 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003192 goto dfs_next_succ;
3193 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003194
3195 if (!OnStack.count(SuccBB)) {
3196 BBStates[CurrBB].addSucc(SuccBB);
3197 BBStates[SuccBB].addPred(CurrBB);
3198 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003199 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003200 OnStack.erase(CurrBB);
3201 PostOrder.push_back(CurrBB);
3202 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003203 } while (!SuccStack.empty());
3204
3205 Visited.clear();
3206
Dan Gohman59a1c932011-12-12 19:42:25 +00003207 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003208 // Functions may have many exits, and there also blocks which we treat
3209 // as exits due to ignored edges.
3210 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3211 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3212 BasicBlock *ExitBB = I;
3213 BBState &MyStates = BBStates[ExitBB];
3214 if (!MyStates.isExit())
3215 continue;
3216
Dan Gohman447989c2012-04-27 18:56:31 +00003217 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003218
3219 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003220 Visited.insert(ExitBB);
3221 while (!PredStack.empty()) {
3222 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003223 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3224 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003225 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003226 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003227 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003228 goto reverse_dfs_next_succ;
3229 }
3230 }
3231 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3232 }
3233 }
3234}
3235
John McCall9fbd3182011-06-15 23:37:01 +00003236// Visit - Visit the function both top-down and bottom-up.
3237bool
3238ObjCARCOpt::Visit(Function &F,
3239 DenseMap<const BasicBlock *, BBState> &BBStates,
3240 MapVector<Value *, RRInfo> &Retains,
3241 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003242
3243 // Use reverse-postorder traversals, because we magically know that loops
3244 // will be well behaved, i.e. they won't repeatedly call retain on a single
3245 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3246 // class here because we want the reverse-CFG postorder to consider each
3247 // function exit point, and we want to ignore selected cycle edges.
3248 SmallVector<BasicBlock *, 16> PostOrder;
3249 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003250 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3251 NoObjCARCExceptionsMDKind,
3252 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003253
3254 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003255 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003256 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003257 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3258 I != E; ++I)
3259 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003260
Dan Gohman59a1c932011-12-12 19:42:25 +00003261 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003262 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003263 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3264 PostOrder.rbegin(), E = PostOrder.rend();
3265 I != E; ++I)
3266 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003267
3268 return TopDownNestingDetected && BottomUpNestingDetected;
3269}
3270
3271/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3272void ObjCARCOpt::MoveCalls(Value *Arg,
3273 RRInfo &RetainsToMove,
3274 RRInfo &ReleasesToMove,
3275 MapVector<Value *, RRInfo> &Retains,
3276 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003277 SmallVectorImpl<Instruction *> &DeadInsts,
3278 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003279 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003280 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003281
3282 // Insert the new retain and release calls.
3283 for (SmallPtrSet<Instruction *, 2>::const_iterator
3284 PI = ReleasesToMove.ReverseInsertPts.begin(),
3285 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3286 Instruction *InsertPt = *PI;
3287 Value *MyArg = ArgTy == ParamTy ? Arg :
3288 new BitCastInst(Arg, ParamTy, "", InsertPt);
3289 CallInst *Call =
3290 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003291 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003292 MyArg, "", InsertPt);
3293 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003294 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003295 Call->setMetadata(CopyOnEscapeMDKind,
3296 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003297 else
John McCall9fbd3182011-06-15 23:37:01 +00003298 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003299
3300 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3301 << "\n"
3302 " At insertion point: " << *InsertPt
3303 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003304 }
3305 for (SmallPtrSet<Instruction *, 2>::const_iterator
3306 PI = RetainsToMove.ReverseInsertPts.begin(),
3307 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003308 Instruction *InsertPt = *PI;
3309 Value *MyArg = ArgTy == ParamTy ? Arg :
3310 new BitCastInst(Arg, ParamTy, "", InsertPt);
3311 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3312 "", InsertPt);
3313 // Attach a clang.imprecise_release metadata tag, if appropriate.
3314 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3315 Call->setMetadata(ImpreciseReleaseMDKind, M);
3316 Call->setDoesNotThrow();
3317 if (ReleasesToMove.IsTailCallRelease)
3318 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003319
3320 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3321 << "\n"
3322 " At insertion point: " << *InsertPt
3323 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003324 }
3325
3326 // Delete the original retain and release calls.
3327 for (SmallPtrSet<Instruction *, 2>::const_iterator
3328 AI = RetainsToMove.Calls.begin(),
3329 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3330 Instruction *OrigRetain = *AI;
3331 Retains.blot(OrigRetain);
3332 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003333 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3334 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003335 }
3336 for (SmallPtrSet<Instruction *, 2>::const_iterator
3337 AI = ReleasesToMove.Calls.begin(),
3338 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3339 Instruction *OrigRelease = *AI;
3340 Releases.erase(OrigRelease);
3341 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003342 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3343 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003344 }
3345}
3346
Dan Gohmand6bf2012012-04-13 18:57:48 +00003347/// PerformCodePlacement - Identify pairings between the retains and releases,
3348/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003349bool
3350ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3351 &BBStates,
3352 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003353 DenseMap<Value *, RRInfo> &Releases,
3354 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003355 bool AnyPairsCompletelyEliminated = false;
3356 RRInfo RetainsToMove;
3357 RRInfo ReleasesToMove;
3358 SmallVector<Instruction *, 4> NewRetains;
3359 SmallVector<Instruction *, 4> NewReleases;
3360 SmallVector<Instruction *, 8> DeadInsts;
3361
Dan Gohmand6bf2012012-04-13 18:57:48 +00003362 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003363 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003364 E = Retains.end(); I != E; ++I) {
3365 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003366 if (!V) continue; // blotted
3367
3368 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003369
3370 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3371 << "\n");
3372
John McCall9fbd3182011-06-15 23:37:01 +00003373 Value *Arg = GetObjCArg(Retain);
3374
Dan Gohman79522dc2012-01-13 00:39:07 +00003375 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003376 // not being managed by ObjC reference counting, so we can delete pairs
3377 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003378 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003379
Dan Gohman1b31ea82011-08-22 17:29:11 +00003380 // A constant pointer can't be pointing to an object on the heap. It may
3381 // be reference-counted, but it won't be deleted.
3382 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3383 if (const GlobalVariable *GV =
3384 dyn_cast<GlobalVariable>(
3385 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3386 if (GV->isConstant())
3387 KnownSafe = true;
3388
John McCall9fbd3182011-06-15 23:37:01 +00003389 // If a pair happens in a region where it is known that the reference count
3390 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003391 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003392
3393 // Connect the dots between the top-down-collected RetainsToMove and
3394 // bottom-up-collected ReleasesToMove to form sets of related calls.
3395 // This is an iterative process so that we connect multiple releases
3396 // to multiple retains if needed.
3397 unsigned OldDelta = 0;
3398 unsigned NewDelta = 0;
3399 unsigned OldCount = 0;
3400 unsigned NewCount = 0;
3401 bool FirstRelease = true;
3402 bool FirstRetain = true;
3403 NewRetains.push_back(Retain);
3404 for (;;) {
3405 for (SmallVectorImpl<Instruction *>::const_iterator
3406 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3407 Instruction *NewRetain = *NI;
3408 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3409 assert(It != Retains.end());
3410 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003411 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003412 for (SmallPtrSet<Instruction *, 2>::const_iterator
3413 LI = NewRetainRRI.Calls.begin(),
3414 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3415 Instruction *NewRetainRelease = *LI;
3416 DenseMap<Value *, RRInfo>::const_iterator Jt =
3417 Releases.find(NewRetainRelease);
3418 if (Jt == Releases.end())
3419 goto next_retain;
3420 const RRInfo &NewRetainReleaseRRI = Jt->second;
3421 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3422 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3423 OldDelta -=
3424 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3425
3426 // Merge the ReleaseMetadata and IsTailCallRelease values.
3427 if (FirstRelease) {
3428 ReleasesToMove.ReleaseMetadata =
3429 NewRetainReleaseRRI.ReleaseMetadata;
3430 ReleasesToMove.IsTailCallRelease =
3431 NewRetainReleaseRRI.IsTailCallRelease;
3432 FirstRelease = false;
3433 } else {
3434 if (ReleasesToMove.ReleaseMetadata !=
3435 NewRetainReleaseRRI.ReleaseMetadata)
3436 ReleasesToMove.ReleaseMetadata = 0;
3437 if (ReleasesToMove.IsTailCallRelease !=
3438 NewRetainReleaseRRI.IsTailCallRelease)
3439 ReleasesToMove.IsTailCallRelease = false;
3440 }
3441
3442 // Collect the optimal insertion points.
3443 if (!KnownSafe)
3444 for (SmallPtrSet<Instruction *, 2>::const_iterator
3445 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3446 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3447 RI != RE; ++RI) {
3448 Instruction *RIP = *RI;
3449 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3450 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3451 }
3452 NewReleases.push_back(NewRetainRelease);
3453 }
3454 }
3455 }
3456 NewRetains.clear();
3457 if (NewReleases.empty()) break;
3458
3459 // Back the other way.
3460 for (SmallVectorImpl<Instruction *>::const_iterator
3461 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3462 Instruction *NewRelease = *NI;
3463 DenseMap<Value *, RRInfo>::const_iterator It =
3464 Releases.find(NewRelease);
3465 assert(It != Releases.end());
3466 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003467 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003468 for (SmallPtrSet<Instruction *, 2>::const_iterator
3469 LI = NewReleaseRRI.Calls.begin(),
3470 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3471 Instruction *NewReleaseRetain = *LI;
3472 MapVector<Value *, RRInfo>::const_iterator Jt =
3473 Retains.find(NewReleaseRetain);
3474 if (Jt == Retains.end())
3475 goto next_retain;
3476 const RRInfo &NewReleaseRetainRRI = Jt->second;
3477 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3478 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3479 unsigned PathCount =
3480 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3481 OldDelta += PathCount;
3482 OldCount += PathCount;
3483
3484 // Merge the IsRetainBlock values.
3485 if (FirstRetain) {
3486 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3487 FirstRetain = false;
3488 } else if (ReleasesToMove.IsRetainBlock !=
3489 NewReleaseRetainRRI.IsRetainBlock)
3490 // It's not possible to merge the sequences if one uses
3491 // objc_retain and the other uses objc_retainBlock.
3492 goto next_retain;
3493
3494 // Collect the optimal insertion points.
3495 if (!KnownSafe)
3496 for (SmallPtrSet<Instruction *, 2>::const_iterator
3497 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3498 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3499 RI != RE; ++RI) {
3500 Instruction *RIP = *RI;
3501 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3502 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3503 NewDelta += PathCount;
3504 NewCount += PathCount;
3505 }
3506 }
3507 NewRetains.push_back(NewReleaseRetain);
3508 }
3509 }
3510 }
3511 NewReleases.clear();
3512 if (NewRetains.empty()) break;
3513 }
3514
Dan Gohmane6d5e882011-08-19 00:26:36 +00003515 // If the pointer is known incremented or nested, we can safely delete the
3516 // pair regardless of what's between them.
3517 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003518 RetainsToMove.ReverseInsertPts.clear();
3519 ReleasesToMove.ReverseInsertPts.clear();
3520 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003521 } else {
3522 // Determine whether the new insertion points we computed preserve the
3523 // balance of retain and release calls through the program.
3524 // TODO: If the fully aggressive solution isn't valid, try to find a
3525 // less aggressive solution which is.
3526 if (NewDelta != 0)
3527 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003528 }
3529
3530 // Determine whether the original call points are balanced in the retain and
3531 // release calls through the program. If not, conservatively don't touch
3532 // them.
3533 // TODO: It's theoretically possible to do code motion in this case, as
3534 // long as the existing imbalances are maintained.
3535 if (OldDelta != 0)
3536 goto next_retain;
3537
John McCall9fbd3182011-06-15 23:37:01 +00003538 // Ok, everything checks out and we're all set. Let's move some code!
3539 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003540 assert(OldCount != 0 && "Unreachable code?");
3541 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003542 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003543 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3544 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003545
3546 next_retain:
3547 NewReleases.clear();
3548 NewRetains.clear();
3549 RetainsToMove.clear();
3550 ReleasesToMove.clear();
3551 }
3552
3553 // Now that we're done moving everything, we can delete the newly dead
3554 // instructions, as we no longer need them as insert points.
3555 while (!DeadInsts.empty())
3556 EraseInstruction(DeadInsts.pop_back_val());
3557
3558 return AnyPairsCompletelyEliminated;
3559}
3560
3561/// OptimizeWeakCalls - Weak pointer optimizations.
3562void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3563 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3564 // itself because it uses AliasAnalysis and we need to do provenance
3565 // queries instead.
3566 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3567 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003568
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003569 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003570 "\n");
3571
John McCall9fbd3182011-06-15 23:37:01 +00003572 InstructionClass Class = GetBasicInstructionClass(Inst);
3573 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3574 continue;
3575
3576 // Delete objc_loadWeak calls with no users.
3577 if (Class == IC_LoadWeak && Inst->use_empty()) {
3578 Inst->eraseFromParent();
3579 continue;
3580 }
3581
3582 // TODO: For now, just look for an earlier available version of this value
3583 // within the same block. Theoretically, we could do memdep-style non-local
3584 // analysis too, but that would want caching. A better approach would be to
3585 // use the technique that EarlyCSE uses.
3586 inst_iterator Current = llvm::prior(I);
3587 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3588 for (BasicBlock::iterator B = CurrentBB->begin(),
3589 J = Current.getInstructionIterator();
3590 J != B; --J) {
3591 Instruction *EarlierInst = &*llvm::prior(J);
3592 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3593 switch (EarlierClass) {
3594 case IC_LoadWeak:
3595 case IC_LoadWeakRetained: {
3596 // If this is loading from the same pointer, replace this load's value
3597 // with that one.
3598 CallInst *Call = cast<CallInst>(Inst);
3599 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3600 Value *Arg = Call->getArgOperand(0);
3601 Value *EarlierArg = EarlierCall->getArgOperand(0);
3602 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3603 case AliasAnalysis::MustAlias:
3604 Changed = true;
3605 // If the load has a builtin retain, insert a plain retain for it.
3606 if (Class == IC_LoadWeakRetained) {
3607 CallInst *CI =
3608 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3609 "", Call);
3610 CI->setTailCall();
3611 }
3612 // Zap the fully redundant load.
3613 Call->replaceAllUsesWith(EarlierCall);
3614 Call->eraseFromParent();
3615 goto clobbered;
3616 case AliasAnalysis::MayAlias:
3617 case AliasAnalysis::PartialAlias:
3618 goto clobbered;
3619 case AliasAnalysis::NoAlias:
3620 break;
3621 }
3622 break;
3623 }
3624 case IC_StoreWeak:
3625 case IC_InitWeak: {
3626 // If this is storing to the same pointer and has the same size etc.
3627 // replace this load's value with the stored value.
3628 CallInst *Call = cast<CallInst>(Inst);
3629 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3630 Value *Arg = Call->getArgOperand(0);
3631 Value *EarlierArg = EarlierCall->getArgOperand(0);
3632 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3633 case AliasAnalysis::MustAlias:
3634 Changed = true;
3635 // If the load has a builtin retain, insert a plain retain for it.
3636 if (Class == IC_LoadWeakRetained) {
3637 CallInst *CI =
3638 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3639 "", Call);
3640 CI->setTailCall();
3641 }
3642 // Zap the fully redundant load.
3643 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3644 Call->eraseFromParent();
3645 goto clobbered;
3646 case AliasAnalysis::MayAlias:
3647 case AliasAnalysis::PartialAlias:
3648 goto clobbered;
3649 case AliasAnalysis::NoAlias:
3650 break;
3651 }
3652 break;
3653 }
3654 case IC_MoveWeak:
3655 case IC_CopyWeak:
3656 // TOOD: Grab the copied value.
3657 goto clobbered;
3658 case IC_AutoreleasepoolPush:
3659 case IC_None:
3660 case IC_User:
3661 // Weak pointers are only modified through the weak entry points
3662 // (and arbitrary calls, which could call the weak entry points).
3663 break;
3664 default:
3665 // Anything else could modify the weak pointer.
3666 goto clobbered;
3667 }
3668 }
3669 clobbered:;
3670 }
3671
3672 // Then, for each destroyWeak with an alloca operand, check to see if
3673 // the alloca and all its users can be zapped.
3674 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3675 Instruction *Inst = &*I++;
3676 InstructionClass Class = GetBasicInstructionClass(Inst);
3677 if (Class != IC_DestroyWeak)
3678 continue;
3679
3680 CallInst *Call = cast<CallInst>(Inst);
3681 Value *Arg = Call->getArgOperand(0);
3682 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3683 for (Value::use_iterator UI = Alloca->use_begin(),
3684 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003685 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003686 switch (GetBasicInstructionClass(UserInst)) {
3687 case IC_InitWeak:
3688 case IC_StoreWeak:
3689 case IC_DestroyWeak:
3690 continue;
3691 default:
3692 goto done;
3693 }
3694 }
3695 Changed = true;
3696 for (Value::use_iterator UI = Alloca->use_begin(),
3697 UE = Alloca->use_end(); UI != UE; ) {
3698 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003699 switch (GetBasicInstructionClass(UserInst)) {
3700 case IC_InitWeak:
3701 case IC_StoreWeak:
3702 // These functions return their second argument.
3703 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3704 break;
3705 case IC_DestroyWeak:
3706 // No return value.
3707 break;
3708 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003709 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003710 }
John McCall9fbd3182011-06-15 23:37:01 +00003711 UserInst->eraseFromParent();
3712 }
3713 Alloca->eraseFromParent();
3714 done:;
3715 }
3716 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003717
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003718 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003719
John McCall9fbd3182011-06-15 23:37:01 +00003720}
3721
3722/// OptimizeSequences - Identify program paths which execute sequences of
3723/// retains and releases which can be eliminated.
3724bool ObjCARCOpt::OptimizeSequences(Function &F) {
3725 /// Releases, Retains - These are used to store the results of the main flow
3726 /// analysis. These use Value* as the key instead of Instruction* so that the
3727 /// map stays valid when we get around to rewriting code and calls get
3728 /// replaced by arguments.
3729 DenseMap<Value *, RRInfo> Releases;
3730 MapVector<Value *, RRInfo> Retains;
3731
3732 /// BBStates, This is used during the traversal of the function to track the
3733 /// states for each identified object at each block.
3734 DenseMap<const BasicBlock *, BBState> BBStates;
3735
3736 // Analyze the CFG of the function, and all instructions.
3737 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3738
3739 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003740 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3741 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003742}
3743
3744/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003745/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003746/// %call = call i8* @something(...)
3747/// %2 = call i8* @objc_retain(i8* %call)
3748/// %3 = call i8* @objc_autorelease(i8* %2)
3749/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003750/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003751/// And delete the retain and autorelease.
3752///
3753/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003754/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003755/// %3 = call i8* @objc_autorelease(i8* %2)
3756/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003757/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003758/// convert the autorelease to autoreleaseRV.
3759void ObjCARCOpt::OptimizeReturns(Function &F) {
3760 if (!F.getReturnType()->isPointerTy())
3761 return;
3762
3763 SmallPtrSet<Instruction *, 4> DependingInstructions;
3764 SmallPtrSet<const BasicBlock *, 4> Visited;
3765 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3766 BasicBlock *BB = FI;
3767 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003768
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003769 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003770
John McCall9fbd3182011-06-15 23:37:01 +00003771 if (!Ret) continue;
3772
3773 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3774 FindDependencies(NeedsPositiveRetainCount, Arg,
3775 BB, Ret, DependingInstructions, Visited, PA);
3776 if (DependingInstructions.size() != 1)
3777 goto next_block;
3778
3779 {
3780 CallInst *Autorelease =
3781 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3782 if (!Autorelease)
3783 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003784 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003785 if (!IsAutorelease(AutoreleaseClass))
3786 goto next_block;
3787 if (GetObjCArg(Autorelease) != Arg)
3788 goto next_block;
3789
3790 DependingInstructions.clear();
3791 Visited.clear();
3792
3793 // Check that there is nothing that can affect the reference
3794 // count between the autorelease and the retain.
3795 FindDependencies(CanChangeRetainCount, Arg,
3796 BB, Autorelease, DependingInstructions, Visited, PA);
3797 if (DependingInstructions.size() != 1)
3798 goto next_block;
3799
3800 {
3801 CallInst *Retain =
3802 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3803
3804 // Check that we found a retain with the same argument.
3805 if (!Retain ||
3806 !IsRetain(GetBasicInstructionClass(Retain)) ||
3807 GetObjCArg(Retain) != Arg)
3808 goto next_block;
3809
3810 DependingInstructions.clear();
3811 Visited.clear();
3812
3813 // Convert the autorelease to an autoreleaseRV, since it's
3814 // returning the value.
3815 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003816 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3817 "=> autoreleaseRV since it's returning a value.\n"
3818 " In: " << *Autorelease
3819 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003820 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003821 DEBUG(dbgs() << " Out: " << *Autorelease
3822 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003823 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003824 AutoreleaseClass = IC_AutoreleaseRV;
3825 }
3826
3827 // Check that there is nothing that can affect the reference
3828 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003829 // Note that Retain need not be in BB.
3830 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003831 DependingInstructions, Visited, PA);
3832 if (DependingInstructions.size() != 1)
3833 goto next_block;
3834
3835 {
3836 CallInst *Call =
3837 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3838
3839 // Check that the pointer is the return value of the call.
3840 if (!Call || Arg != Call)
3841 goto next_block;
3842
3843 // Check that the call is a regular call.
3844 InstructionClass Class = GetBasicInstructionClass(Call);
3845 if (Class != IC_CallOrUser && Class != IC_Call)
3846 goto next_block;
3847
3848 // If so, we can zap the retain and autorelease.
3849 Changed = true;
3850 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003851 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3852 << "\n Erasing: "
3853 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003854 EraseInstruction(Retain);
3855 EraseInstruction(Autorelease);
3856 }
3857 }
3858 }
3859
3860 next_block:
3861 DependingInstructions.clear();
3862 Visited.clear();
3863 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003864
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003865 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003866
John McCall9fbd3182011-06-15 23:37:01 +00003867}
3868
3869bool ObjCARCOpt::doInitialization(Module &M) {
3870 if (!EnableARCOpts)
3871 return false;
3872
Dan Gohmand6bf2012012-04-13 18:57:48 +00003873 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003874 Run = ModuleHasARC(M);
3875 if (!Run)
3876 return false;
3877
John McCall9fbd3182011-06-15 23:37:01 +00003878 // Identify the imprecise release metadata kind.
3879 ImpreciseReleaseMDKind =
3880 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003881 CopyOnEscapeMDKind =
3882 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003883 NoObjCARCExceptionsMDKind =
3884 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003885
John McCall9fbd3182011-06-15 23:37:01 +00003886 // Intuitively, objc_retain and others are nocapture, however in practice
3887 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003888 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003889
3890 // These are initialized lazily.
3891 RetainRVCallee = 0;
3892 AutoreleaseRVCallee = 0;
3893 ReleaseCallee = 0;
3894 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003895 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003896 AutoreleaseCallee = 0;
3897
3898 return false;
3899}
3900
3901bool ObjCARCOpt::runOnFunction(Function &F) {
3902 if (!EnableARCOpts)
3903 return false;
3904
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003905 // If nothing in the Module uses ARC, don't do anything.
3906 if (!Run)
3907 return false;
3908
John McCall9fbd3182011-06-15 23:37:01 +00003909 Changed = false;
3910
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003911 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3912
John McCall9fbd3182011-06-15 23:37:01 +00003913 PA.setAA(&getAnalysis<AliasAnalysis>());
3914
3915 // This pass performs several distinct transformations. As a compile-time aid
3916 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3917 // library functions aren't declared.
3918
3919 // Preliminary optimizations. This also computs UsedInThisFunction.
3920 OptimizeIndividualCalls(F);
3921
3922 // Optimizations for weak pointers.
3923 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3924 (1 << IC_LoadWeakRetained) |
3925 (1 << IC_StoreWeak) |
3926 (1 << IC_InitWeak) |
3927 (1 << IC_CopyWeak) |
3928 (1 << IC_MoveWeak) |
3929 (1 << IC_DestroyWeak)))
3930 OptimizeWeakCalls(F);
3931
3932 // Optimizations for retain+release pairs.
3933 if (UsedInThisFunction & ((1 << IC_Retain) |
3934 (1 << IC_RetainRV) |
3935 (1 << IC_RetainBlock)))
3936 if (UsedInThisFunction & (1 << IC_Release))
3937 // Run OptimizeSequences until it either stops making changes or
3938 // no retain+release pair nesting is detected.
3939 while (OptimizeSequences(F)) {}
3940
3941 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003942 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3943 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003944 OptimizeReturns(F);
3945
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003946 DEBUG(dbgs() << "\n");
3947
John McCall9fbd3182011-06-15 23:37:01 +00003948 return Changed;
3949}
3950
3951void ObjCARCOpt::releaseMemory() {
3952 PA.clear();
3953}
3954
3955//===----------------------------------------------------------------------===//
3956// ARC contraction.
3957//===----------------------------------------------------------------------===//
3958
3959// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3960// dominated by single calls.
3961
John McCall9fbd3182011-06-15 23:37:01 +00003962#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003963#include "llvm/IR/InlineAsm.h"
3964#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003965
3966STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3967
3968namespace {
3969 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3970 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3971 class ObjCARCContract : public FunctionPass {
3972 bool Changed;
3973 AliasAnalysis *AA;
3974 DominatorTree *DT;
3975 ProvenanceAnalysis PA;
3976
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003977 /// Run - A flag indicating whether this optimization pass should run.
3978 bool Run;
3979
John McCall9fbd3182011-06-15 23:37:01 +00003980 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3981 /// functions, for use in creating calls to them. These are initialized
3982 /// lazily to avoid cluttering up the Module with unused declarations.
3983 Constant *StoreStrongCallee,
3984 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3985
3986 /// RetainRVMarker - The inline asm string to insert between calls and
3987 /// RetainRV calls to make the optimization work on targets which need it.
3988 const MDString *RetainRVMarker;
3989
Dan Gohman0cdece42012-01-19 19:14:36 +00003990 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3991 /// at the end of walking the function we have found no alloca
3992 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003993 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003994
John McCall9fbd3182011-06-15 23:37:01 +00003995 Constant *getStoreStrongCallee(Module *M);
3996 Constant *getRetainAutoreleaseCallee(Module *M);
3997 Constant *getRetainAutoreleaseRVCallee(Module *M);
3998
3999 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4000 InstructionClass Class,
4001 SmallPtrSet<Instruction *, 4>
4002 &DependingInstructions,
4003 SmallPtrSet<const BasicBlock *, 4>
4004 &Visited);
4005
4006 void ContractRelease(Instruction *Release,
4007 inst_iterator &Iter);
4008
4009 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4010 virtual bool doInitialization(Module &M);
4011 virtual bool runOnFunction(Function &F);
4012
4013 public:
4014 static char ID;
4015 ObjCARCContract() : FunctionPass(ID) {
4016 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4017 }
4018 };
4019}
4020
4021char ObjCARCContract::ID = 0;
4022INITIALIZE_PASS_BEGIN(ObjCARCContract,
4023 "objc-arc-contract", "ObjC ARC contraction", false, false)
4024INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4025INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4026INITIALIZE_PASS_END(ObjCARCContract,
4027 "objc-arc-contract", "ObjC ARC contraction", false, false)
4028
4029Pass *llvm::createObjCARCContractPass() {
4030 return new ObjCARCContract();
4031}
4032
4033void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4034 AU.addRequired<AliasAnalysis>();
4035 AU.addRequired<DominatorTree>();
4036 AU.setPreservesCFG();
4037}
4038
4039Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4040 if (!StoreStrongCallee) {
4041 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004042 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4043 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004044 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004045
Bill Wendling034b94b2012-12-19 07:18:57 +00004046 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004047 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004048 Attribute::get(C, Attribute::NoUnwind))
4049 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004050
4051 StoreStrongCallee =
4052 M->getOrInsertFunction(
4053 "objc_storeStrong",
4054 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004055 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004056 }
4057 return StoreStrongCallee;
4058}
4059
4060Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4061 if (!RetainAutoreleaseCallee) {
4062 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004063 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004064 Type *Params[] = { I8X };
4065 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004066 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004067 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004068 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004069 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004070 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004071 }
4072 return RetainAutoreleaseCallee;
4073}
4074
4075Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4076 if (!RetainAutoreleaseRVCallee) {
4077 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004078 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004079 Type *Params[] = { I8X };
4080 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004081 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004082 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004083 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004084 RetainAutoreleaseRVCallee =
4085 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004086 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004087 }
4088 return RetainAutoreleaseRVCallee;
4089}
4090
Dan Gohman447989c2012-04-27 18:56:31 +00004091/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004092bool
4093ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4094 InstructionClass Class,
4095 SmallPtrSet<Instruction *, 4>
4096 &DependingInstructions,
4097 SmallPtrSet<const BasicBlock *, 4>
4098 &Visited) {
4099 const Value *Arg = GetObjCArg(Autorelease);
4100
4101 // Check that there are no instructions between the retain and the autorelease
4102 // (such as an autorelease_pop) which may change the count.
4103 CallInst *Retain = 0;
4104 if (Class == IC_AutoreleaseRV)
4105 FindDependencies(RetainAutoreleaseRVDep, Arg,
4106 Autorelease->getParent(), Autorelease,
4107 DependingInstructions, Visited, PA);
4108 else
4109 FindDependencies(RetainAutoreleaseDep, Arg,
4110 Autorelease->getParent(), Autorelease,
4111 DependingInstructions, Visited, PA);
4112
4113 Visited.clear();
4114 if (DependingInstructions.size() != 1) {
4115 DependingInstructions.clear();
4116 return false;
4117 }
4118
4119 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4120 DependingInstructions.clear();
4121
4122 if (!Retain ||
4123 GetBasicInstructionClass(Retain) != IC_Retain ||
4124 GetObjCArg(Retain) != Arg)
4125 return false;
4126
4127 Changed = true;
4128 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004129
Michael Gottesman916d52a2013-01-07 00:31:26 +00004130 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4131 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4132 " Old Retain: "
4133 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004134
John McCall9fbd3182011-06-15 23:37:01 +00004135 if (Class == IC_AutoreleaseRV)
4136 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4137 else
4138 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004139
Michael Gottesman916d52a2013-01-07 00:31:26 +00004140 DEBUG(dbgs() << " New Retain: "
4141 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004142
John McCall9fbd3182011-06-15 23:37:01 +00004143 EraseInstruction(Autorelease);
4144 return true;
4145}
4146
4147/// ContractRelease - Attempt to merge an objc_release with a store, load, and
4148/// objc_retain to form an objc_storeStrong. This can be a little tricky because
4149/// the instructions don't always appear in order, and there may be unrelated
4150/// intervening instructions.
4151void ObjCARCContract::ContractRelease(Instruction *Release,
4152 inst_iterator &Iter) {
4153 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004154 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004155
4156 // For now, require everything to be in one basic block.
4157 BasicBlock *BB = Release->getParent();
4158 if (Load->getParent() != BB) return;
4159
Dan Gohman4670dac2012-05-08 23:34:08 +00004160 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004161 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004162 ++I;
4163 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004164 StoreInst *Store = 0;
4165 bool SawRelease = false;
4166 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004167 if (I == End)
4168 return;
4169
Dan Gohman4670dac2012-05-08 23:34:08 +00004170 Instruction *Inst = I;
4171 if (Inst == Release) {
4172 SawRelease = true;
4173 continue;
4174 }
4175
4176 InstructionClass Class = GetBasicInstructionClass(Inst);
4177
4178 // Unrelated retains are harmless.
4179 if (IsRetain(Class))
4180 continue;
4181
4182 if (Store) {
4183 // The store is the point where we're going to put the objc_storeStrong,
4184 // so make sure there are no uses after it.
4185 if (CanUse(Inst, Load, PA, Class))
4186 return;
4187 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4188 // We are moving the load down to the store, so check for anything
4189 // else which writes to the memory between the load and the store.
4190 Store = dyn_cast<StoreInst>(Inst);
4191 if (!Store || !Store->isSimple()) return;
4192 if (Store->getPointerOperand() != Loc.Ptr) return;
4193 }
4194 }
John McCall9fbd3182011-06-15 23:37:01 +00004195
4196 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4197
4198 // Walk up to find the retain.
4199 I = Store;
4200 BasicBlock::iterator Begin = BB->begin();
4201 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4202 --I;
4203 Instruction *Retain = I;
4204 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4205 if (GetObjCArg(Retain) != New) return;
4206
4207 Changed = true;
4208 ++NumStoreStrongs;
4209
4210 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004211 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4212 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004213
4214 Value *Args[] = { Load->getPointerOperand(), New };
4215 if (Args[0]->getType() != I8XX)
4216 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4217 if (Args[1]->getType() != I8X)
4218 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4219 CallInst *StoreStrong =
4220 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004221 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004222 StoreStrong->setDoesNotThrow();
4223 StoreStrong->setDebugLoc(Store->getDebugLoc());
4224
Dan Gohman0cdece42012-01-19 19:14:36 +00004225 // We can't set the tail flag yet, because we haven't yet determined
4226 // whether there are any escaping allocas. Remember this call, so that
4227 // we can set the tail flag once we know it's safe.
4228 StoreStrongCalls.insert(StoreStrong);
4229
John McCall9fbd3182011-06-15 23:37:01 +00004230 if (&*Iter == Store) ++Iter;
4231 Store->eraseFromParent();
4232 Release->eraseFromParent();
4233 EraseInstruction(Retain);
4234 if (Load->use_empty())
4235 Load->eraseFromParent();
4236}
4237
4238bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004239 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004240 Run = ModuleHasARC(M);
4241 if (!Run)
4242 return false;
4243
John McCall9fbd3182011-06-15 23:37:01 +00004244 // These are initialized lazily.
4245 StoreStrongCallee = 0;
4246 RetainAutoreleaseCallee = 0;
4247 RetainAutoreleaseRVCallee = 0;
4248
4249 // Initialize RetainRVMarker.
4250 RetainRVMarker = 0;
4251 if (NamedMDNode *NMD =
4252 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4253 if (NMD->getNumOperands() == 1) {
4254 const MDNode *N = NMD->getOperand(0);
4255 if (N->getNumOperands() == 1)
4256 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4257 RetainRVMarker = S;
4258 }
4259
4260 return false;
4261}
4262
4263bool ObjCARCContract::runOnFunction(Function &F) {
4264 if (!EnableARCOpts)
4265 return false;
4266
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004267 // If nothing in the Module uses ARC, don't do anything.
4268 if (!Run)
4269 return false;
4270
John McCall9fbd3182011-06-15 23:37:01 +00004271 Changed = false;
4272 AA = &getAnalysis<AliasAnalysis>();
4273 DT = &getAnalysis<DominatorTree>();
4274
4275 PA.setAA(&getAnalysis<AliasAnalysis>());
4276
Dan Gohman0cdece42012-01-19 19:14:36 +00004277 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4278 // keyword. Be conservative if the function has variadic arguments.
4279 // It seems that functions which "return twice" are also unsafe for the
4280 // "tail" argument, because they are setjmp, which could need to
4281 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004282 bool TailOkForStoreStrongs = !F.isVarArg() &&
4283 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004284
John McCall9fbd3182011-06-15 23:37:01 +00004285 // For ObjC library calls which return their argument, replace uses of the
4286 // argument with uses of the call return value, if it dominates the use. This
4287 // reduces register pressure.
4288 SmallPtrSet<Instruction *, 4> DependingInstructions;
4289 SmallPtrSet<const BasicBlock *, 4> Visited;
4290 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4291 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004292
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004293 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004294
John McCall9fbd3182011-06-15 23:37:01 +00004295 // Only these library routines return their argument. In particular,
4296 // objc_retainBlock does not necessarily return its argument.
4297 InstructionClass Class = GetBasicInstructionClass(Inst);
4298 switch (Class) {
4299 case IC_Retain:
4300 case IC_FusedRetainAutorelease:
4301 case IC_FusedRetainAutoreleaseRV:
4302 break;
4303 case IC_Autorelease:
4304 case IC_AutoreleaseRV:
4305 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4306 continue;
4307 break;
4308 case IC_RetainRV: {
4309 // If we're compiling for a target which needs a special inline-asm
4310 // marker to do the retainAutoreleasedReturnValue optimization,
4311 // insert it now.
4312 if (!RetainRVMarker)
4313 break;
4314 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004315 BasicBlock *InstParent = Inst->getParent();
4316
4317 // Step up to see if the call immediately precedes the RetainRV call.
4318 // If it's an invoke, we have to cross a block boundary. And we have
4319 // to carefully dodge no-op instructions.
4320 do {
4321 if (&*BBI == InstParent->begin()) {
4322 BasicBlock *Pred = InstParent->getSinglePredecessor();
4323 if (!Pred)
4324 goto decline_rv_optimization;
4325 BBI = Pred->getTerminator();
4326 break;
4327 }
4328 --BBI;
4329 } while (isNoopInstruction(BBI));
4330
John McCall9fbd3182011-06-15 23:37:01 +00004331 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004332 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004333 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004334 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004335 InlineAsm *IA =
4336 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4337 /*isVarArg=*/false),
4338 RetainRVMarker->getString(),
4339 /*Constraints=*/"", /*hasSideEffects=*/true);
4340 CallInst::Create(IA, "", Inst);
4341 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004342 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004343 break;
4344 }
4345 case IC_InitWeak: {
4346 // objc_initWeak(p, null) => *p = null
4347 CallInst *CI = cast<CallInst>(Inst);
4348 if (isNullOrUndef(CI->getArgOperand(1))) {
4349 Value *Null =
4350 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4351 Changed = true;
4352 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004353
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004354 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4355 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004356
John McCall9fbd3182011-06-15 23:37:01 +00004357 CI->replaceAllUsesWith(Null);
4358 CI->eraseFromParent();
4359 }
4360 continue;
4361 }
4362 case IC_Release:
4363 ContractRelease(Inst, I);
4364 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004365 case IC_User:
4366 // Be conservative if the function has any alloca instructions.
4367 // Technically we only care about escaping alloca instructions,
4368 // but this is sufficient to handle some interesting cases.
4369 if (isa<AllocaInst>(Inst))
4370 TailOkForStoreStrongs = false;
4371 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004372 default:
4373 continue;
4374 }
4375
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004376 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004377
John McCall9fbd3182011-06-15 23:37:01 +00004378 // Don't use GetObjCArg because we don't want to look through bitcasts
4379 // and such; to do the replacement, the argument must have type i8*.
4380 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4381 for (;;) {
4382 // If we're compiling bugpointed code, don't get in trouble.
4383 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4384 break;
4385 // Look through the uses of the pointer.
4386 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4387 UI != UE; ) {
4388 Use &U = UI.getUse();
4389 unsigned OperandNo = UI.getOperandNo();
4390 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004391
4392 // If the call's return value dominates a use of the call's argument
4393 // value, rewrite the use to use the return value. We check for
4394 // reachability here because an unreachable call is considered to
4395 // trivially dominate itself, which would lead us to rewriting its
4396 // argument in terms of its return value, which would lead to
4397 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004398 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004399 Changed = true;
4400 Instruction *Replacement = Inst;
4401 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004402 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004403 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004404 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4405 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004406 if (Replacement->getType() != UseTy)
4407 Replacement = new BitCastInst(Replacement, UseTy, "",
4408 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004409 // While we're here, rewrite all edges for this PHI, rather
4410 // than just one use at a time, to minimize the number of
4411 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004412 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004413 if (PHI->getIncomingBlock(i) == BB) {
4414 // Keep the UI iterator valid.
4415 if (&PHI->getOperandUse(
4416 PHINode::getOperandNumForIncomingValue(i)) ==
4417 &UI.getUse())
4418 ++UI;
4419 PHI->setIncomingValue(i, Replacement);
4420 }
4421 } else {
4422 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004423 Replacement = new BitCastInst(Replacement, UseTy, "",
4424 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004425 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004426 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004427 }
John McCall9fbd3182011-06-15 23:37:01 +00004428 }
4429
Dan Gohman447989c2012-04-27 18:56:31 +00004430 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004431 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4432 Arg = BI->getOperand(0);
4433 else if (isa<GEPOperator>(Arg) &&
4434 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4435 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4436 else if (isa<GlobalAlias>(Arg) &&
4437 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4438 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4439 else
4440 break;
4441 }
4442 }
4443
Dan Gohman0cdece42012-01-19 19:14:36 +00004444 // If this function has no escaping allocas or suspicious vararg usage,
4445 // objc_storeStrong calls can be marked with the "tail" keyword.
4446 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004447 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004448 E = StoreStrongCalls.end(); I != E; ++I)
4449 (*I)->setTailCall();
4450 StoreStrongCalls.clear();
4451
John McCall9fbd3182011-06-15 23:37:01 +00004452 return Changed;
4453}