blob: 1aa41fc02b77b120a5d677031484b095732e3aa8 [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) {
622 // Walk the def-use chains.
623 SmallVector<const Value *, 4> Worklist;
624 Worklist.push_back(BlockPtr);
625 do {
626 const Value *V = Worklist.pop_back_val();
627 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
628 UI != UE; ++UI) {
629 const User *UUser = *UI;
630 // Special - Use by a call (callee or argument) is not considered
631 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000632 switch (GetBasicInstructionClass(UUser)) {
633 case IC_StoreWeak:
634 case IC_InitWeak:
635 case IC_StoreStrong:
636 case IC_Autorelease:
637 case IC_AutoreleaseRV:
638 // These special functions make copies of their pointer arguments.
639 return true;
640 case IC_User:
641 case IC_None:
642 // Use by an instruction which copies the value is an escape if the
643 // result is an escape.
644 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
645 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
646 Worklist.push_back(UUser);
647 continue;
648 }
649 // Use by a load is not an escape.
650 if (isa<LoadInst>(UUser))
651 continue;
652 // Use by a store is not an escape if the use is the address.
653 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
654 if (V != SI->getValueOperand())
655 continue;
656 break;
657 default:
658 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000659 continue;
660 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000661 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000662 return true;
663 }
664 } while (!Worklist.empty());
665
666 // No escapes found.
667 return false;
668}
669
John McCall9fbd3182011-06-15 23:37:01 +0000670//===----------------------------------------------------------------------===//
671// ARC AliasAnalysis.
672//===----------------------------------------------------------------------===//
673
John McCall9fbd3182011-06-15 23:37:01 +0000674#include "llvm/Analysis/AliasAnalysis.h"
675#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000676#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000677
678namespace {
679 /// ObjCARCAliasAnalysis - This is a simple alias analysis
680 /// implementation that uses knowledge of ARC constructs to answer queries.
681 ///
682 /// TODO: This class could be generalized to know about other ObjC-specific
683 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
684 /// even though their offsets are dynamic.
685 class ObjCARCAliasAnalysis : public ImmutablePass,
686 public AliasAnalysis {
687 public:
688 static char ID; // Class identification, replacement for typeinfo
689 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
690 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
691 }
692
693 private:
694 virtual void initializePass() {
695 InitializeAliasAnalysis(this);
696 }
697
698 /// getAdjustedAnalysisPointer - This method is used when a pass implements
699 /// an analysis interface through multiple inheritance. If needed, it
700 /// should override this to adjust the this pointer as needed for the
701 /// specified pass info.
702 virtual void *getAdjustedAnalysisPointer(const void *PI) {
703 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000704 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000705 return this;
706 }
707
708 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
709 virtual AliasResult alias(const Location &LocA, const Location &LocB);
710 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
711 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
712 virtual ModRefBehavior getModRefBehavior(const Function *F);
713 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
714 const Location &Loc);
715 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
716 ImmutableCallSite CS2);
717 };
718} // End of anonymous namespace
719
720// Register this pass...
721char ObjCARCAliasAnalysis::ID = 0;
722INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
723 "ObjC-ARC-Based Alias Analysis", false, true, false)
724
725ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
726 return new ObjCARCAliasAnalysis();
727}
728
729void
730ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
731 AU.setPreservesAll();
732 AliasAnalysis::getAnalysisUsage(AU);
733}
734
735AliasAnalysis::AliasResult
736ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
737 if (!EnableARCOpts)
738 return AliasAnalysis::alias(LocA, LocB);
739
740 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
741 // precise alias query.
742 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
743 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
744 AliasResult Result =
745 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
746 Location(SB, LocB.Size, LocB.TBAATag));
747 if (Result != MayAlias)
748 return Result;
749
750 // If that failed, climb to the underlying object, including climbing through
751 // ObjC-specific no-ops, and try making an imprecise alias query.
752 const Value *UA = GetUnderlyingObjCPtr(SA);
753 const Value *UB = GetUnderlyingObjCPtr(SB);
754 if (UA != SA || UB != SB) {
755 Result = AliasAnalysis::alias(Location(UA), Location(UB));
756 // We can't use MustAlias or PartialAlias results here because
757 // GetUnderlyingObjCPtr may return an offsetted pointer value.
758 if (Result == NoAlias)
759 return NoAlias;
760 }
761
762 // If that failed, fail. We don't need to chain here, since that's covered
763 // by the earlier precise query.
764 return MayAlias;
765}
766
767bool
768ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
769 bool OrLocal) {
770 if (!EnableARCOpts)
771 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
772
773 // First, strip off no-ops, including ObjC-specific no-ops, and try making
774 // a precise alias query.
775 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
776 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
777 OrLocal))
778 return true;
779
780 // If that failed, climb to the underlying object, including climbing through
781 // ObjC-specific no-ops, and try making an imprecise alias query.
782 const Value *U = GetUnderlyingObjCPtr(S);
783 if (U != S)
784 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
785
786 // If that failed, fail. We don't need to chain here, since that's covered
787 // by the earlier precise query.
788 return false;
789}
790
791AliasAnalysis::ModRefBehavior
792ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
793 // We have nothing to do. Just chain to the next AliasAnalysis.
794 return AliasAnalysis::getModRefBehavior(CS);
795}
796
797AliasAnalysis::ModRefBehavior
798ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
799 if (!EnableARCOpts)
800 return AliasAnalysis::getModRefBehavior(F);
801
802 switch (GetFunctionClass(F)) {
803 case IC_NoopCast:
804 return DoesNotAccessMemory;
805 default:
806 break;
807 }
808
809 return AliasAnalysis::getModRefBehavior(F);
810}
811
812AliasAnalysis::ModRefResult
813ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
814 if (!EnableARCOpts)
815 return AliasAnalysis::getModRefInfo(CS, Loc);
816
817 switch (GetBasicInstructionClass(CS.getInstruction())) {
818 case IC_Retain:
819 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000820 case IC_Autorelease:
821 case IC_AutoreleaseRV:
822 case IC_NoopCast:
823 case IC_AutoreleasepoolPush:
824 case IC_FusedRetainAutorelease:
825 case IC_FusedRetainAutoreleaseRV:
826 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000827 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000828 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000829 return NoModRef;
830 default:
831 break;
832 }
833
834 return AliasAnalysis::getModRefInfo(CS, Loc);
835}
836
837AliasAnalysis::ModRefResult
838ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
839 ImmutableCallSite CS2) {
840 // TODO: Theoretically we could check for dependencies between objc_* calls
841 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
842 return AliasAnalysis::getModRefInfo(CS1, CS2);
843}
844
845//===----------------------------------------------------------------------===//
846// ARC expansion.
847//===----------------------------------------------------------------------===//
848
849#include "llvm/Support/InstIterator.h"
850#include "llvm/Transforms/Scalar.h"
851
852namespace {
853 /// ObjCARCExpand - Early ARC transformations.
854 class ObjCARCExpand : public FunctionPass {
855 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000856 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000857 virtual bool runOnFunction(Function &F);
858
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000859 /// Run - A flag indicating whether this optimization pass should run.
860 bool Run;
861
John McCall9fbd3182011-06-15 23:37:01 +0000862 public:
863 static char ID;
864 ObjCARCExpand() : FunctionPass(ID) {
865 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
866 }
867 };
868}
869
870char ObjCARCExpand::ID = 0;
871INITIALIZE_PASS(ObjCARCExpand,
872 "objc-arc-expand", "ObjC ARC expansion", false, false)
873
874Pass *llvm::createObjCARCExpandPass() {
875 return new ObjCARCExpand();
876}
877
878void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
879 AU.setPreservesCFG();
880}
881
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000882bool ObjCARCExpand::doInitialization(Module &M) {
883 Run = ModuleHasARC(M);
884 return false;
885}
886
John McCall9fbd3182011-06-15 23:37:01 +0000887bool ObjCARCExpand::runOnFunction(Function &F) {
888 if (!EnableARCOpts)
889 return false;
890
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000891 // If nothing in the Module uses ARC, don't do anything.
892 if (!Run)
893 return false;
894
John McCall9fbd3182011-06-15 23:37:01 +0000895 bool Changed = false;
896
897 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
898 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000899
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000900 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000901
John McCall9fbd3182011-06-15 23:37:01 +0000902 switch (GetBasicInstructionClass(Inst)) {
903 case IC_Retain:
904 case IC_RetainRV:
905 case IC_Autorelease:
906 case IC_AutoreleaseRV:
907 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000908 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000909 // These calls return their argument verbatim, as a low-level
910 // optimization. However, this makes high-level optimizations
911 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000912 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000913 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000914 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
915 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
916 " New = " << *Value << "\n");
917 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000918 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000919 }
John McCall9fbd3182011-06-15 23:37:01 +0000920 default:
921 break;
922 }
923 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000924
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000925 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000926
John McCall9fbd3182011-06-15 23:37:01 +0000927 return Changed;
928}
929
930//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000931// ARC autorelease pool elimination.
932//===----------------------------------------------------------------------===//
933
Dan Gohman0daef3d2012-05-08 23:39:44 +0000934#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000935#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000936
Dan Gohman2f6263c2012-01-17 20:52:24 +0000937namespace {
938 /// ObjCARCAPElim - Autorelease pool elimination.
939 class ObjCARCAPElim : public ModulePass {
940 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
941 virtual bool runOnModule(Module &M);
942
Dan Gohman447989c2012-04-27 18:56:31 +0000943 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
944 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000945
946 public:
947 static char ID;
948 ObjCARCAPElim() : ModulePass(ID) {
949 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
950 }
951 };
952}
953
954char ObjCARCAPElim::ID = 0;
955INITIALIZE_PASS(ObjCARCAPElim,
956 "objc-arc-apelim",
957 "ObjC ARC autorelease pool elimination",
958 false, false)
959
960Pass *llvm::createObjCARCAPElimPass() {
961 return new ObjCARCAPElim();
962}
963
964void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
965 AU.setPreservesCFG();
966}
967
968/// MayAutorelease - Interprocedurally determine if calls made by the
969/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000970bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
971 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000972 if (Callee->isDeclaration() || Callee->mayBeOverridden())
973 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000974 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000975 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000976 const BasicBlock *BB = I;
977 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
978 J != F; ++J)
979 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000980 // This recursion depth limit is arbitrary. It's just great
981 // enough to cover known interesting testcases.
982 if (Depth < 3 &&
983 !JCS.onlyReadsMemory() &&
984 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000985 return true;
986 }
987 return false;
988 }
989
990 return true;
991}
992
993bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
994 bool Changed = false;
995
996 Instruction *Push = 0;
997 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
998 Instruction *Inst = I++;
999 switch (GetBasicInstructionClass(Inst)) {
1000 case IC_AutoreleasepoolPush:
1001 Push = Inst;
1002 break;
1003 case IC_AutoreleasepoolPop:
1004 // If this pop matches a push and nothing in between can autorelease,
1005 // zap the pair.
1006 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1007 Changed = true;
Michael Gottesman5c0ae472013-01-04 21:29:57 +00001008 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001009 << " Pop: " << *Inst << "\n"
1010 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001011 Inst->eraseFromParent();
1012 Push->eraseFromParent();
1013 }
1014 Push = 0;
1015 break;
1016 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001017 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001018 Push = 0;
1019 break;
1020 default:
1021 break;
1022 }
1023 }
1024
1025 return Changed;
1026}
1027
1028bool ObjCARCAPElim::runOnModule(Module &M) {
1029 if (!EnableARCOpts)
1030 return false;
1031
1032 // If nothing in the Module uses ARC, don't do anything.
1033 if (!ModuleHasARC(M))
1034 return false;
1035
Dan Gohman1dae3e92012-01-18 21:19:38 +00001036 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001037 // identifying the global constructors. In theory, unnecessary autorelease
1038 // pools could occur anywhere, but in practice it's pretty rare. Global
1039 // ctors are a place where autorelease pools get inserted automatically,
1040 // so it's pretty common for them to be unnecessary, and it's pretty
1041 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001042 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1043 if (!GV)
1044 return false;
1045
1046 assert(GV->hasDefinitiveInitializer() &&
1047 "llvm.global_ctors is uncooperative!");
1048
Dan Gohman2f6263c2012-01-17 20:52:24 +00001049 bool Changed = false;
1050
Dan Gohman1dae3e92012-01-18 21:19:38 +00001051 // Dig the constructor functions out of GV's initializer.
1052 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1053 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1054 OI != OE; ++OI) {
1055 Value *Op = *OI;
1056 // llvm.global_ctors is an array of pairs where the second members
1057 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001058 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1059 // If the user used a constructor function with the wrong signature and
1060 // it got bitcasted or whatever, look the other way.
1061 if (!F)
1062 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001063 // Only look at function definitions.
1064 if (F->isDeclaration())
1065 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001066 // Only look at functions with one basic block.
1067 if (llvm::next(F->begin()) != F->end())
1068 continue;
1069 // Ok, a single-block constructor function definition. Try to optimize it.
1070 Changed |= OptimizeBB(F->begin());
1071 }
1072
1073 return Changed;
1074}
1075
1076//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001077// ARC optimization.
1078//===----------------------------------------------------------------------===//
1079
1080// TODO: On code like this:
1081//
1082// objc_retain(%x)
1083// stuff_that_cannot_release()
1084// objc_autorelease(%x)
1085// stuff_that_cannot_release()
1086// objc_retain(%x)
1087// stuff_that_cannot_release()
1088// objc_autorelease(%x)
1089//
1090// The second retain and autorelease can be deleted.
1091
1092// TODO: It should be possible to delete
1093// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1094// pairs if nothing is actually autoreleased between them. Also, autorelease
1095// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1096// after inlining) can be turned into plain release calls.
1097
1098// TODO: Critical-edge splitting. If the optimial insertion point is
1099// a critical edge, the current algorithm has to fail, because it doesn't
1100// know how to split edges. It should be possible to make the optimizer
1101// think in terms of edges, rather than blocks, and then split critical
1102// edges on demand.
1103
1104// TODO: OptimizeSequences could generalized to be Interprocedural.
1105
1106// TODO: Recognize that a bunch of other objc runtime calls have
1107// non-escaping arguments and non-releasing arguments, and may be
1108// non-autoreleasing.
1109
1110// TODO: Sink autorelease calls as far as possible. Unfortunately we
1111// usually can't sink them past other calls, which would be the main
1112// case where it would be useful.
1113
Dan Gohmane6d5e882011-08-19 00:26:36 +00001114// TODO: The pointer returned from objc_loadWeakRetained is retained.
1115
1116// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001117
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001118#include "llvm/ADT/SmallPtrSet.h"
1119#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001120#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001121#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001122
1123STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1124STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1125STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1126STATISTIC(NumRets, "Number of return value forwarding "
1127 "retain+autoreleaes eliminated");
1128STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1129STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1130
1131namespace {
1132 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1133 /// uses many of the same techniques, except it uses special ObjC-specific
1134 /// reasoning about pointer relationships.
1135 class ProvenanceAnalysis {
1136 AliasAnalysis *AA;
1137
1138 typedef std::pair<const Value *, const Value *> ValuePairTy;
1139 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1140 CachedResultsTy CachedResults;
1141
1142 bool relatedCheck(const Value *A, const Value *B);
1143 bool relatedSelect(const SelectInst *A, const Value *B);
1144 bool relatedPHI(const PHINode *A, const Value *B);
1145
Craig Topperc2945e42012-09-18 02:01:41 +00001146 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1147 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001148
1149 public:
1150 ProvenanceAnalysis() {}
1151
1152 void setAA(AliasAnalysis *aa) { AA = aa; }
1153
1154 AliasAnalysis *getAA() const { return AA; }
1155
1156 bool related(const Value *A, const Value *B);
1157
1158 void clear() {
1159 CachedResults.clear();
1160 }
1161 };
1162}
1163
1164bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1165 // If the values are Selects with the same condition, we can do a more precise
1166 // check: just check for relations between the values on corresponding arms.
1167 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001168 if (A->getCondition() == SB->getCondition())
1169 return related(A->getTrueValue(), SB->getTrueValue()) ||
1170 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001171
1172 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001173 return related(A->getTrueValue(), B) ||
1174 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001175}
1176
1177bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1178 // If the values are PHIs in the same block, we can do a more precise as well
1179 // as efficient check: just check for relations between the values on
1180 // corresponding edges.
1181 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1182 if (PNB->getParent() == A->getParent()) {
1183 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1184 if (related(A->getIncomingValue(i),
1185 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1186 return true;
1187 return false;
1188 }
1189
1190 // Check each unique source of the PHI node against B.
1191 SmallPtrSet<const Value *, 4> UniqueSrc;
1192 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1193 const Value *PV1 = A->getIncomingValue(i);
1194 if (UniqueSrc.insert(PV1) && related(PV1, B))
1195 return true;
1196 }
1197
1198 // All of the arms checked out.
1199 return false;
1200}
1201
1202/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1203/// provenance, is ever stored within the function (not counting callees).
1204static bool isStoredObjCPointer(const Value *P) {
1205 SmallPtrSet<const Value *, 8> Visited;
1206 SmallVector<const Value *, 8> Worklist;
1207 Worklist.push_back(P);
1208 Visited.insert(P);
1209 do {
1210 P = Worklist.pop_back_val();
1211 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1212 UI != UE; ++UI) {
1213 const User *Ur = *UI;
1214 if (isa<StoreInst>(Ur)) {
1215 if (UI.getOperandNo() == 0)
1216 // The pointer is stored.
1217 return true;
1218 // The pointed is stored through.
1219 continue;
1220 }
1221 if (isa<CallInst>(Ur))
1222 // The pointer is passed as an argument, ignore this.
1223 continue;
1224 if (isa<PtrToIntInst>(P))
1225 // Assume the worst.
1226 return true;
1227 if (Visited.insert(Ur))
1228 Worklist.push_back(Ur);
1229 }
1230 } while (!Worklist.empty());
1231
1232 // Everything checked out.
1233 return false;
1234}
1235
1236bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1237 // Skip past provenance pass-throughs.
1238 A = GetUnderlyingObjCPtr(A);
1239 B = GetUnderlyingObjCPtr(B);
1240
1241 // Quick check.
1242 if (A == B)
1243 return true;
1244
1245 // Ask regular AliasAnalysis, for a first approximation.
1246 switch (AA->alias(A, B)) {
1247 case AliasAnalysis::NoAlias:
1248 return false;
1249 case AliasAnalysis::MustAlias:
1250 case AliasAnalysis::PartialAlias:
1251 return true;
1252 case AliasAnalysis::MayAlias:
1253 break;
1254 }
1255
1256 bool AIsIdentified = IsObjCIdentifiedObject(A);
1257 bool BIsIdentified = IsObjCIdentifiedObject(B);
1258
1259 // An ObjC-Identified object can't alias a load if it is never locally stored.
1260 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001261 // Check for an obvious escape.
1262 if (isa<LoadInst>(B))
1263 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001264 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001265 // Check for an obvious escape.
1266 if (isa<LoadInst>(A))
1267 return isStoredObjCPointer(B);
1268 // Both pointers are identified and escapes aren't an evident problem.
1269 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001270 }
Dan Gohman230768b2012-09-04 23:16:20 +00001271 } else if (BIsIdentified) {
1272 // Check for an obvious escape.
1273 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001274 return isStoredObjCPointer(B);
1275 }
1276
1277 // Special handling for PHI and Select.
1278 if (const PHINode *PN = dyn_cast<PHINode>(A))
1279 return relatedPHI(PN, B);
1280 if (const PHINode *PN = dyn_cast<PHINode>(B))
1281 return relatedPHI(PN, A);
1282 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1283 return relatedSelect(S, B);
1284 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1285 return relatedSelect(S, A);
1286
1287 // Conservative.
1288 return true;
1289}
1290
1291bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1292 // Begin by inserting a conservative value into the map. If the insertion
1293 // fails, we have the answer already. If it succeeds, leave it there until we
1294 // compute the real answer to guard against recursive queries.
1295 if (A > B) std::swap(A, B);
1296 std::pair<CachedResultsTy::iterator, bool> Pair =
1297 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1298 if (!Pair.second)
1299 return Pair.first->second;
1300
1301 bool Result = relatedCheck(A, B);
1302 CachedResults[ValuePairTy(A, B)] = Result;
1303 return Result;
1304}
1305
1306namespace {
1307 // Sequence - A sequence of states that a pointer may go through in which an
1308 // objc_retain and objc_release are actually needed.
1309 enum Sequence {
1310 S_None,
1311 S_Retain, ///< objc_retain(x)
1312 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1313 S_Use, ///< any use of x
1314 S_Stop, ///< like S_Release, but code motion is stopped
1315 S_Release, ///< objc_release(x)
1316 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1317 };
1318}
1319
1320static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1321 // The easy cases.
1322 if (A == B)
1323 return A;
1324 if (A == S_None || B == S_None)
1325 return S_None;
1326
John McCall9fbd3182011-06-15 23:37:01 +00001327 if (A > B) std::swap(A, B);
1328 if (TopDown) {
1329 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001330 if ((A == S_Retain || A == S_CanRelease) &&
1331 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001332 return B;
1333 } else {
1334 // Choose the side which is further along in the sequence.
1335 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001336 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001337 return A;
1338 // If both sides are releases, choose the more conservative one.
1339 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1340 return A;
1341 if (A == S_Release && B == S_MovableRelease)
1342 return A;
1343 }
1344
1345 return S_None;
1346}
1347
1348namespace {
1349 /// RRInfo - Unidirectional information about either a
1350 /// retain-decrement-use-release sequence or release-use-decrement-retain
1351 /// reverese sequence.
1352 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001353 /// KnownSafe - After an objc_retain, the reference count of the referenced
1354 /// object is known to be positive. Similarly, before an objc_release, the
1355 /// reference count of the referenced object is known to be positive. If
1356 /// there are retain-release pairs in code regions where the retain count
1357 /// is known to be positive, they can be eliminated, regardless of any side
1358 /// effects between them.
1359 ///
1360 /// Also, a retain+release pair nested within another retain+release
1361 /// pair all on the known same pointer value can be eliminated, regardless
1362 /// of any intervening side effects.
1363 ///
1364 /// KnownSafe is true when either of these conditions is satisfied.
1365 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001366
1367 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1368 /// opposed to objc_retain calls).
1369 bool IsRetainBlock;
1370
1371 /// IsTailCallRelease - True of the objc_release calls are all marked
1372 /// with the "tail" keyword.
1373 bool IsTailCallRelease;
1374
1375 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1376 /// a clang.imprecise_release tag, this is the metadata tag.
1377 MDNode *ReleaseMetadata;
1378
1379 /// Calls - For a top-down sequence, the set of objc_retains or
1380 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1381 SmallPtrSet<Instruction *, 2> Calls;
1382
1383 /// ReverseInsertPts - The set of optimal insert positions for
1384 /// moving calls in the opposite sequence.
1385 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1386
1387 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001388 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001389 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001390 ReleaseMetadata(0) {}
1391
1392 void clear();
1393 };
1394}
1395
1396void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001397 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001398 IsRetainBlock = false;
1399 IsTailCallRelease = false;
1400 ReleaseMetadata = 0;
1401 Calls.clear();
1402 ReverseInsertPts.clear();
1403}
1404
1405namespace {
1406 /// PtrState - This class summarizes several per-pointer runtime properties
1407 /// which are propogated through the flow graph.
1408 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001409 /// KnownPositiveRefCount - True if the reference count is known to
1410 /// be incremented.
1411 bool KnownPositiveRefCount;
1412
1413 /// Partial - True of we've seen an opportunity for partial RR elimination,
1414 /// such as pushing calls into a CFG triangle or into one side of a
1415 /// CFG diamond.
1416 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001417
1418 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001419 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001420
1421 public:
1422 /// RRI - Unidirectional information about the current sequence.
1423 /// TODO: Encapsulate this better.
1424 RRInfo RRI;
1425
Dan Gohman230768b2012-09-04 23:16:20 +00001426 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001427 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001428
Dan Gohman50ade652012-04-25 00:50:46 +00001429 void SetKnownPositiveRefCount() {
1430 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001431 }
1432
Dan Gohman50ade652012-04-25 00:50:46 +00001433 void ClearRefCount() {
1434 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001435 }
1436
John McCall9fbd3182011-06-15 23:37:01 +00001437 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001438 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001439 }
1440
1441 void SetSeq(Sequence NewSeq) {
1442 Seq = NewSeq;
1443 }
1444
John McCall9fbd3182011-06-15 23:37:01 +00001445 Sequence GetSeq() const {
1446 return Seq;
1447 }
1448
1449 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001450 ResetSequenceProgress(S_None);
1451 }
1452
1453 void ResetSequenceProgress(Sequence NewSeq) {
1454 Seq = NewSeq;
1455 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001456 RRI.clear();
1457 }
1458
1459 void Merge(const PtrState &Other, bool TopDown);
1460 };
1461}
1462
1463void
1464PtrState::Merge(const PtrState &Other, bool TopDown) {
1465 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001466 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001467
1468 // We can't merge a plain objc_retain with an objc_retainBlock.
1469 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1470 Seq = S_None;
1471
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001472 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001473 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001474 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001475 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001476 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001477 // If we're doing a merge on a path that's previously seen a partial
1478 // merge, conservatively drop the sequence, to avoid doing partial
1479 // RR elimination. If the branch predicates for the two merge differ,
1480 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001481 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001482 } else {
1483 // Conservatively merge the ReleaseMetadata information.
1484 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1485 RRI.ReleaseMetadata = 0;
1486
Dan Gohmane6d5e882011-08-19 00:26:36 +00001487 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001488 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1489 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001490 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001491
1492 // Merge the insert point sets. If there are any differences,
1493 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001494 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001495 for (SmallPtrSet<Instruction *, 2>::const_iterator
1496 I = Other.RRI.ReverseInsertPts.begin(),
1497 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001498 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001499 }
1500}
1501
1502namespace {
1503 /// BBState - Per-BasicBlock state.
1504 class BBState {
1505 /// TopDownPathCount - The number of unique control paths from the entry
1506 /// which can reach this block.
1507 unsigned TopDownPathCount;
1508
1509 /// BottomUpPathCount - The number of unique control paths to exits
1510 /// from this block.
1511 unsigned BottomUpPathCount;
1512
1513 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1514 typedef MapVector<const Value *, PtrState> MapTy;
1515
1516 /// PerPtrTopDown - The top-down traversal uses this to record information
1517 /// known about a pointer at the bottom of each block.
1518 MapTy PerPtrTopDown;
1519
1520 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1521 /// known about a pointer at the top of each block.
1522 MapTy PerPtrBottomUp;
1523
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001524 /// Preds, Succs - Effective successors and predecessors of the current
1525 /// block (this ignores ignorable edges and ignored backedges).
1526 SmallVector<BasicBlock *, 2> Preds;
1527 SmallVector<BasicBlock *, 2> Succs;
1528
John McCall9fbd3182011-06-15 23:37:01 +00001529 public:
1530 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1531
1532 typedef MapTy::iterator ptr_iterator;
1533 typedef MapTy::const_iterator ptr_const_iterator;
1534
1535 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1536 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1537 ptr_const_iterator top_down_ptr_begin() const {
1538 return PerPtrTopDown.begin();
1539 }
1540 ptr_const_iterator top_down_ptr_end() const {
1541 return PerPtrTopDown.end();
1542 }
1543
1544 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1545 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1546 ptr_const_iterator bottom_up_ptr_begin() const {
1547 return PerPtrBottomUp.begin();
1548 }
1549 ptr_const_iterator bottom_up_ptr_end() const {
1550 return PerPtrBottomUp.end();
1551 }
1552
1553 /// SetAsEntry - Mark this block as being an entry block, which has one
1554 /// path from the entry by definition.
1555 void SetAsEntry() { TopDownPathCount = 1; }
1556
1557 /// SetAsExit - Mark this block as being an exit block, which has one
1558 /// path to an exit by definition.
1559 void SetAsExit() { BottomUpPathCount = 1; }
1560
1561 PtrState &getPtrTopDownState(const Value *Arg) {
1562 return PerPtrTopDown[Arg];
1563 }
1564
1565 PtrState &getPtrBottomUpState(const Value *Arg) {
1566 return PerPtrBottomUp[Arg];
1567 }
1568
1569 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001570 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001571 }
1572
1573 void clearTopDownPointers() {
1574 PerPtrTopDown.clear();
1575 }
1576
1577 void InitFromPred(const BBState &Other);
1578 void InitFromSucc(const BBState &Other);
1579 void MergePred(const BBState &Other);
1580 void MergeSucc(const BBState &Other);
1581
1582 /// GetAllPathCount - Return the number of possible unique paths from an
1583 /// entry to an exit which pass through this block. This is only valid
1584 /// after both the top-down and bottom-up traversals are complete.
1585 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001586 assert(TopDownPathCount != 0);
1587 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001588 return TopDownPathCount * BottomUpPathCount;
1589 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001590
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001591 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001592 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001593 edge_iterator pred_begin() { return Preds.begin(); }
1594 edge_iterator pred_end() { return Preds.end(); }
1595 edge_iterator succ_begin() { return Succs.begin(); }
1596 edge_iterator succ_end() { return Succs.end(); }
1597
1598 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1599 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1600
1601 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001602 };
1603}
1604
1605void BBState::InitFromPred(const BBState &Other) {
1606 PerPtrTopDown = Other.PerPtrTopDown;
1607 TopDownPathCount = Other.TopDownPathCount;
1608}
1609
1610void BBState::InitFromSucc(const BBState &Other) {
1611 PerPtrBottomUp = Other.PerPtrBottomUp;
1612 BottomUpPathCount = Other.BottomUpPathCount;
1613}
1614
1615/// MergePred - The top-down traversal uses this to merge information about
1616/// predecessors to form the initial state for a new block.
1617void BBState::MergePred(const BBState &Other) {
1618 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1619 // loop backedge. Loop backedges are special.
1620 TopDownPathCount += Other.TopDownPathCount;
1621
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001622 // Check for overflow. If we have overflow, fall back to conservative behavior.
1623 if (TopDownPathCount < Other.TopDownPathCount) {
1624 clearTopDownPointers();
1625 return;
1626 }
1627
John McCall9fbd3182011-06-15 23:37:01 +00001628 // For each entry in the other set, if our set has an entry with the same key,
1629 // merge the entries. Otherwise, copy the entry and merge it with an empty
1630 // entry.
1631 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1632 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1633 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1634 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1635 /*TopDown=*/true);
1636 }
1637
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001638 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001639 // same key, force it to merge with an empty entry.
1640 for (ptr_iterator MI = top_down_ptr_begin(),
1641 ME = top_down_ptr_end(); MI != ME; ++MI)
1642 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1643 MI->second.Merge(PtrState(), /*TopDown=*/true);
1644}
1645
1646/// MergeSucc - The bottom-up traversal uses this to merge information about
1647/// successors to form the initial state for a new block.
1648void BBState::MergeSucc(const BBState &Other) {
1649 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1650 // loop backedge. Loop backedges are special.
1651 BottomUpPathCount += Other.BottomUpPathCount;
1652
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001653 // Check for overflow. If we have overflow, fall back to conservative behavior.
1654 if (BottomUpPathCount < Other.BottomUpPathCount) {
1655 clearBottomUpPointers();
1656 return;
1657 }
1658
John McCall9fbd3182011-06-15 23:37:01 +00001659 // For each entry in the other set, if our set has an entry with the
1660 // same key, merge the entries. Otherwise, copy the entry and merge
1661 // it with an empty entry.
1662 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1663 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1664 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1665 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1666 /*TopDown=*/false);
1667 }
1668
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001669 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001670 // with the same key, force it to merge with an empty entry.
1671 for (ptr_iterator MI = bottom_up_ptr_begin(),
1672 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1673 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1674 MI->second.Merge(PtrState(), /*TopDown=*/false);
1675}
1676
1677namespace {
1678 /// ObjCARCOpt - The main ARC optimization pass.
1679 class ObjCARCOpt : public FunctionPass {
1680 bool Changed;
1681 ProvenanceAnalysis PA;
1682
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001683 /// Run - A flag indicating whether this optimization pass should run.
1684 bool Run;
1685
John McCall9fbd3182011-06-15 23:37:01 +00001686 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1687 /// functions, for use in creating calls to them. These are initialized
1688 /// lazily to avoid cluttering up the Module with unused declarations.
1689 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001690 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001691
1692 /// UsedInThisFunciton - Flags which determine whether each of the
1693 /// interesting runtine functions is in fact used in the current function.
1694 unsigned UsedInThisFunction;
1695
1696 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1697 /// metadata.
1698 unsigned ImpreciseReleaseMDKind;
1699
Dan Gohman62e5b402011-12-12 18:20:00 +00001700 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001701 /// metadata.
1702 unsigned CopyOnEscapeMDKind;
1703
Dan Gohmandbe266b2012-02-17 18:59:53 +00001704 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1705 /// clang.arc.no_objc_arc_exceptions metadata.
1706 unsigned NoObjCARCExceptionsMDKind;
1707
John McCall9fbd3182011-06-15 23:37:01 +00001708 Constant *getRetainRVCallee(Module *M);
1709 Constant *getAutoreleaseRVCallee(Module *M);
1710 Constant *getReleaseCallee(Module *M);
1711 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001712 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001713 Constant *getAutoreleaseCallee(Module *M);
1714
Dan Gohman79522dc2012-01-13 00:39:07 +00001715 bool IsRetainBlockOptimizable(const Instruction *Inst);
1716
John McCall9fbd3182011-06-15 23:37:01 +00001717 void OptimizeRetainCall(Function &F, Instruction *Retain);
1718 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001719 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1720 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001721 void OptimizeIndividualCalls(Function &F);
1722
1723 void CheckForCFGHazards(const BasicBlock *BB,
1724 DenseMap<const BasicBlock *, BBState> &BBStates,
1725 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001726 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001727 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001728 MapVector<Value *, RRInfo> &Retains,
1729 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001730 bool VisitBottomUp(BasicBlock *BB,
1731 DenseMap<const BasicBlock *, BBState> &BBStates,
1732 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001733 bool VisitInstructionTopDown(Instruction *Inst,
1734 DenseMap<Value *, RRInfo> &Releases,
1735 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001736 bool VisitTopDown(BasicBlock *BB,
1737 DenseMap<const BasicBlock *, BBState> &BBStates,
1738 DenseMap<Value *, RRInfo> &Releases);
1739 bool Visit(Function &F,
1740 DenseMap<const BasicBlock *, BBState> &BBStates,
1741 MapVector<Value *, RRInfo> &Retains,
1742 DenseMap<Value *, RRInfo> &Releases);
1743
1744 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1745 MapVector<Value *, RRInfo> &Retains,
1746 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001747 SmallVectorImpl<Instruction *> &DeadInsts,
1748 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001749
1750 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1751 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001752 DenseMap<Value *, RRInfo> &Releases,
1753 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001754
1755 void OptimizeWeakCalls(Function &F);
1756
1757 bool OptimizeSequences(Function &F);
1758
1759 void OptimizeReturns(Function &F);
1760
1761 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1762 virtual bool doInitialization(Module &M);
1763 virtual bool runOnFunction(Function &F);
1764 virtual void releaseMemory();
1765
1766 public:
1767 static char ID;
1768 ObjCARCOpt() : FunctionPass(ID) {
1769 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1770 }
1771 };
1772}
1773
1774char ObjCARCOpt::ID = 0;
1775INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1776 "objc-arc", "ObjC ARC optimization", false, false)
1777INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1778INITIALIZE_PASS_END(ObjCARCOpt,
1779 "objc-arc", "ObjC ARC optimization", false, false)
1780
1781Pass *llvm::createObjCARCOptPass() {
1782 return new ObjCARCOpt();
1783}
1784
1785void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1786 AU.addRequired<ObjCARCAliasAnalysis>();
1787 AU.addRequired<AliasAnalysis>();
1788 // ARC optimization doesn't currently split critical edges.
1789 AU.setPreservesCFG();
1790}
1791
Dan Gohman79522dc2012-01-13 00:39:07 +00001792bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1793 // Without the magic metadata tag, we have to assume this might be an
1794 // objc_retainBlock call inserted to convert a block pointer to an id,
1795 // in which case it really is needed.
1796 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1797 return false;
1798
1799 // If the pointer "escapes" (not including being used in a call),
1800 // the copy may be needed.
1801 if (DoesObjCBlockEscape(Inst))
1802 return false;
1803
1804 // Otherwise, it's not needed.
1805 return true;
1806}
1807
John McCall9fbd3182011-06-15 23:37:01 +00001808Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1809 if (!RetainRVCallee) {
1810 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001811 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001812 Type *Params[] = { I8X };
1813 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001814 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001815 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001816 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001817 RetainRVCallee =
1818 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001819 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001820 }
1821 return RetainRVCallee;
1822}
1823
1824Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1825 if (!AutoreleaseRVCallee) {
1826 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001827 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001828 Type *Params[] = { I8X };
1829 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001830 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001831 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001832 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001833 AutoreleaseRVCallee =
1834 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001835 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001836 }
1837 return AutoreleaseRVCallee;
1838}
1839
1840Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1841 if (!ReleaseCallee) {
1842 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001843 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001844 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001845 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001846 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001847 ReleaseCallee =
1848 M->getOrInsertFunction(
1849 "objc_release",
1850 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001851 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001852 }
1853 return ReleaseCallee;
1854}
1855
1856Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1857 if (!RetainCallee) {
1858 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001859 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001860 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001861 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001862 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001863 RetainCallee =
1864 M->getOrInsertFunction(
1865 "objc_retain",
1866 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001867 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001868 }
1869 return RetainCallee;
1870}
1871
Dan Gohman44280692011-07-22 22:29:21 +00001872Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1873 if (!RetainBlockCallee) {
1874 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001875 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001876 // objc_retainBlock is not nounwind because it calls user copy constructors
1877 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001878 RetainBlockCallee =
1879 M->getOrInsertFunction(
1880 "objc_retainBlock",
1881 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001882 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001883 }
1884 return RetainBlockCallee;
1885}
1886
John McCall9fbd3182011-06-15 23:37:01 +00001887Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1888 if (!AutoreleaseCallee) {
1889 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001890 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001891 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001892 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001893 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001894 AutoreleaseCallee =
1895 M->getOrInsertFunction(
1896 "objc_autorelease",
1897 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001898 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001899 }
1900 return AutoreleaseCallee;
1901}
1902
Dan Gohman230768b2012-09-04 23:16:20 +00001903/// IsPotentialUse - Test whether the given value is possible a
1904/// reference-counted pointer, including tests which utilize AliasAnalysis.
1905static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1906 // First make the rudimentary check.
1907 if (!IsPotentialUse(Op))
1908 return false;
1909
1910 // Objects in constant memory are not reference-counted.
1911 if (AA.pointsToConstantMemory(Op))
1912 return false;
1913
1914 // Pointers in constant memory are not pointing to reference-counted objects.
1915 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1916 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1917 return false;
1918
1919 // Otherwise assume the worst.
1920 return true;
1921}
1922
John McCall9fbd3182011-06-15 23:37:01 +00001923/// CanAlterRefCount - Test whether the given instruction can result in a
1924/// reference count modification (positive or negative) for the pointer's
1925/// object.
1926static bool
1927CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1928 ProvenanceAnalysis &PA, InstructionClass Class) {
1929 switch (Class) {
1930 case IC_Autorelease:
1931 case IC_AutoreleaseRV:
1932 case IC_User:
1933 // These operations never directly modify a reference count.
1934 return false;
1935 default: break;
1936 }
1937
1938 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1939 assert(CS && "Only calls can alter reference counts!");
1940
1941 // See if AliasAnalysis can help us with the call.
1942 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1943 if (AliasAnalysis::onlyReadsMemory(MRB))
1944 return false;
1945 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1946 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1947 I != E; ++I) {
1948 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001949 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001950 return true;
1951 }
1952 return false;
1953 }
1954
1955 // Assume the worst.
1956 return true;
1957}
1958
1959/// CanUse - Test whether the given instruction can "use" the given pointer's
1960/// object in a way that requires the reference count to be positive.
1961static bool
1962CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1963 InstructionClass Class) {
1964 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1965 if (Class == IC_Call)
1966 return false;
1967
1968 // Consider various instructions which may have pointer arguments which are
1969 // not "uses".
1970 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1971 // Comparing a pointer with null, or any other constant, isn't really a use,
1972 // because we don't care what the pointer points to, or about the values
1973 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001974 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001975 return false;
1976 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1977 // For calls, just check the arguments (and not the callee operand).
1978 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1979 OE = CS.arg_end(); OI != OE; ++OI) {
1980 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001981 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001982 return true;
1983 }
1984 return false;
1985 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1986 // Special-case stores, because we don't care about the stored value, just
1987 // the store address.
1988 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1989 // If we can't tell what the underlying object was, assume there is a
1990 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001991 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001992 }
1993
1994 // Check each operand for a match.
1995 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1996 OI != OE; ++OI) {
1997 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001998 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001999 return true;
2000 }
2001 return false;
2002}
2003
2004/// CanInterruptRV - Test whether the given instruction can autorelease
2005/// any pointer or cause an autoreleasepool pop.
2006static bool
2007CanInterruptRV(InstructionClass Class) {
2008 switch (Class) {
2009 case IC_AutoreleasepoolPop:
2010 case IC_CallOrUser:
2011 case IC_Call:
2012 case IC_Autorelease:
2013 case IC_AutoreleaseRV:
2014 case IC_FusedRetainAutorelease:
2015 case IC_FusedRetainAutoreleaseRV:
2016 return true;
2017 default:
2018 return false;
2019 }
2020}
2021
2022namespace {
2023 /// DependenceKind - There are several kinds of dependence-like concepts in
2024 /// use here.
2025 enum DependenceKind {
2026 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002027 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002028 CanChangeRetainCount,
2029 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2030 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2031 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2032 };
2033}
2034
2035/// Depends - Test if there can be dependencies on Inst through Arg. This
2036/// function only tests dependencies relevant for removing pairs of calls.
2037static bool
2038Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2039 ProvenanceAnalysis &PA) {
2040 // If we've reached the definition of Arg, stop.
2041 if (Inst == Arg)
2042 return true;
2043
2044 switch (Flavor) {
2045 case NeedsPositiveRetainCount: {
2046 InstructionClass Class = GetInstructionClass(Inst);
2047 switch (Class) {
2048 case IC_AutoreleasepoolPop:
2049 case IC_AutoreleasepoolPush:
2050 case IC_None:
2051 return false;
2052 default:
2053 return CanUse(Inst, Arg, PA, Class);
2054 }
2055 }
2056
Dan Gohman511568d2012-04-13 00:59:57 +00002057 case AutoreleasePoolBoundary: {
2058 InstructionClass Class = GetInstructionClass(Inst);
2059 switch (Class) {
2060 case IC_AutoreleasepoolPop:
2061 case IC_AutoreleasepoolPush:
2062 // These mark the end and begin of an autorelease pool scope.
2063 return true;
2064 default:
2065 // Nothing else does this.
2066 return false;
2067 }
2068 }
2069
John McCall9fbd3182011-06-15 23:37:01 +00002070 case CanChangeRetainCount: {
2071 InstructionClass Class = GetInstructionClass(Inst);
2072 switch (Class) {
2073 case IC_AutoreleasepoolPop:
2074 // Conservatively assume this can decrement any count.
2075 return true;
2076 case IC_AutoreleasepoolPush:
2077 case IC_None:
2078 return false;
2079 default:
2080 return CanAlterRefCount(Inst, Arg, PA, Class);
2081 }
2082 }
2083
2084 case RetainAutoreleaseDep:
2085 switch (GetBasicInstructionClass(Inst)) {
2086 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002087 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002088 // Don't merge an objc_autorelease with an objc_retain inside a different
2089 // autoreleasepool scope.
2090 return true;
2091 case IC_Retain:
2092 case IC_RetainRV:
2093 // Check for a retain of the same pointer for merging.
2094 return GetObjCArg(Inst) == Arg;
2095 default:
2096 // Nothing else matters for objc_retainAutorelease formation.
2097 return false;
2098 }
John McCall9fbd3182011-06-15 23:37:01 +00002099
2100 case RetainAutoreleaseRVDep: {
2101 InstructionClass Class = GetBasicInstructionClass(Inst);
2102 switch (Class) {
2103 case IC_Retain:
2104 case IC_RetainRV:
2105 // Check for a retain of the same pointer for merging.
2106 return GetObjCArg(Inst) == Arg;
2107 default:
2108 // Anything that can autorelease interrupts
2109 // retainAutoreleaseReturnValue formation.
2110 return CanInterruptRV(Class);
2111 }
John McCall9fbd3182011-06-15 23:37:01 +00002112 }
2113
2114 case RetainRVDep:
2115 return CanInterruptRV(GetBasicInstructionClass(Inst));
2116 }
2117
2118 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002119}
2120
2121/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2122/// find local and non-local dependencies on Arg.
2123/// TODO: Cache results?
2124static void
2125FindDependencies(DependenceKind Flavor,
2126 const Value *Arg,
2127 BasicBlock *StartBB, Instruction *StartInst,
2128 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2129 SmallPtrSet<const BasicBlock *, 4> &Visited,
2130 ProvenanceAnalysis &PA) {
2131 BasicBlock::iterator StartPos = StartInst;
2132
2133 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2134 Worklist.push_back(std::make_pair(StartBB, StartPos));
2135 do {
2136 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2137 Worklist.pop_back_val();
2138 BasicBlock *LocalStartBB = Pair.first;
2139 BasicBlock::iterator LocalStartPos = Pair.second;
2140 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2141 for (;;) {
2142 if (LocalStartPos == StartBBBegin) {
2143 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2144 if (PI == PE)
2145 // If we've reached the function entry, produce a null dependence.
2146 DependingInstructions.insert(0);
2147 else
2148 // Add the predecessors to the worklist.
2149 do {
2150 BasicBlock *PredBB = *PI;
2151 if (Visited.insert(PredBB))
2152 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2153 } while (++PI != PE);
2154 break;
2155 }
2156
2157 Instruction *Inst = --LocalStartPos;
2158 if (Depends(Flavor, Inst, Arg, PA)) {
2159 DependingInstructions.insert(Inst);
2160 break;
2161 }
2162 }
2163 } while (!Worklist.empty());
2164
2165 // Determine whether the original StartBB post-dominates all of the blocks we
2166 // visited. If not, insert a sentinal indicating that most optimizations are
2167 // not safe.
2168 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2169 E = Visited.end(); I != E; ++I) {
2170 const BasicBlock *BB = *I;
2171 if (BB == StartBB)
2172 continue;
2173 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2174 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2175 const BasicBlock *Succ = *SI;
2176 if (Succ != StartBB && !Visited.count(Succ)) {
2177 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2178 return;
2179 }
2180 }
2181 }
2182}
2183
2184static bool isNullOrUndef(const Value *V) {
2185 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2186}
2187
2188static bool isNoopInstruction(const Instruction *I) {
2189 return isa<BitCastInst>(I) ||
2190 (isa<GetElementPtrInst>(I) &&
2191 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2192}
2193
2194/// OptimizeRetainCall - Turn objc_retain into
2195/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2196void
2197ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002198 ImmutableCallSite CS(GetObjCArg(Retain));
2199 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002200 if (!Call) return;
2201 if (Call->getParent() != Retain->getParent()) return;
2202
2203 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002204 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002205 ++I;
2206 while (isNoopInstruction(I)) ++I;
2207 if (&*I != Retain)
2208 return;
2209
2210 // Turn it to an objc_retainAutoreleasedReturnValue..
2211 Changed = true;
2212 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002213
Michael Gottesman715f6a62013-01-04 21:30:38 +00002214 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002215 "objc_retain => objc_retainAutoreleasedReturnValue"
2216 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002217 " Old: "
2218 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002219
John McCall9fbd3182011-06-15 23:37:01 +00002220 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002221
2222 DEBUG(dbgs() << " New: "
2223 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002224}
2225
2226/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002227/// objc_retain if the operand is not a return value. Or, if it can be paired
2228/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002229bool
2230ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002231 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002232 const Value *Arg = GetObjCArg(RetainRV);
2233 ImmutableCallSite CS(Arg);
2234 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002235 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002236 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002237 ++I;
2238 while (isNoopInstruction(I)) ++I;
2239 if (&*I == RetainRV)
2240 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002241 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002242 BasicBlock *RetainRVParent = RetainRV->getParent();
2243 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002244 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002245 while (isNoopInstruction(I)) ++I;
2246 if (&*I == RetainRV)
2247 return false;
2248 }
John McCall9fbd3182011-06-15 23:37:01 +00002249 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002250 }
John McCall9fbd3182011-06-15 23:37:01 +00002251
2252 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2253 // pointer. In this case, we can delete the pair.
2254 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2255 if (I != Begin) {
2256 do --I; while (I != Begin && isNoopInstruction(I));
2257 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2258 GetObjCArg(I) == Arg) {
2259 Changed = true;
2260 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002261
Michael Gottesman87a0f022013-01-05 17:55:35 +00002262 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2263 << " Erasing " << *RetainRV
2264 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002265
John McCall9fbd3182011-06-15 23:37:01 +00002266 EraseInstruction(I);
2267 EraseInstruction(RetainRV);
2268 return true;
2269 }
2270 }
2271
2272 // Turn it to a plain objc_retain.
2273 Changed = true;
2274 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002275
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002276 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2277 "objc_retainAutoreleasedReturnValue => "
2278 "objc_retain since the operand is not a return value.\n"
2279 " Old: "
2280 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002281
John McCall9fbd3182011-06-15 23:37:01 +00002282 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002283
2284 DEBUG(dbgs() << " New: "
2285 << *RetainRV << "\n");
2286
John McCall9fbd3182011-06-15 23:37:01 +00002287 return false;
2288}
2289
2290/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2291/// objc_autorelease if the result is not used as a return value.
2292void
Michael Gottesman0e385452013-01-12 01:25:19 +00002293ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2294 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002295 // Check for a return of the pointer value.
2296 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002297 SmallVector<const Value *, 2> Users;
2298 Users.push_back(Ptr);
2299 do {
2300 Ptr = Users.pop_back_val();
2301 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2302 UI != UE; ++UI) {
2303 const User *I = *UI;
2304 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2305 return;
2306 if (isa<BitCastInst>(I))
2307 Users.push_back(I);
2308 }
2309 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002310
2311 Changed = true;
2312 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002313
2314 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2315 "objc_autoreleaseReturnValue => "
2316 "objc_autorelease since its operand is not used as a return "
2317 "value.\n"
2318 " Old: "
2319 << *AutoreleaseRV << "\n");
2320
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002321 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2322 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002323 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002324 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002325 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002326
Michael Gottesman48239c72013-01-06 21:07:11 +00002327 DEBUG(dbgs() << " New: "
2328 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002329
John McCall9fbd3182011-06-15 23:37:01 +00002330}
2331
2332/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2333/// simplifications without doing any additional analysis.
2334void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2335 // Reset all the flags in preparation for recomputing them.
2336 UsedInThisFunction = 0;
2337
2338 // Visit all objc_* calls in F.
2339 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2340 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002341
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002342 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002343 *Inst << "\n");
2344
John McCall9fbd3182011-06-15 23:37:01 +00002345 InstructionClass Class = GetBasicInstructionClass(Inst);
2346
2347 switch (Class) {
2348 default: break;
2349
2350 // Delete no-op casts. These function calls have special semantics, but
2351 // the semantics are entirely implemented via lowering in the front-end,
2352 // so by the time they reach the optimizer, they are just no-op calls
2353 // which return their argument.
2354 //
2355 // There are gray areas here, as the ability to cast reference-counted
2356 // pointers to raw void* and back allows code to break ARC assumptions,
2357 // however these are currently considered to be unimportant.
2358 case IC_NoopCast:
2359 Changed = true;
2360 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002361 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2362 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002363 EraseInstruction(Inst);
2364 continue;
2365
2366 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2367 case IC_StoreWeak:
2368 case IC_LoadWeak:
2369 case IC_LoadWeakRetained:
2370 case IC_InitWeak:
2371 case IC_DestroyWeak: {
2372 CallInst *CI = cast<CallInst>(Inst);
2373 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002374 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002375 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002376 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2377 Constant::getNullValue(Ty),
2378 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002379 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002380 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2381 "pointer-to-weak-pointer is undefined behavior.\n"
2382 " Old = " << *CI <<
2383 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002384 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002385 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002386 CI->eraseFromParent();
2387 continue;
2388 }
2389 break;
2390 }
2391 case IC_CopyWeak:
2392 case IC_MoveWeak: {
2393 CallInst *CI = cast<CallInst>(Inst);
2394 if (isNullOrUndef(CI->getArgOperand(0)) ||
2395 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002396 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002397 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002398 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2399 Constant::getNullValue(Ty),
2400 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002401
2402 llvm::Value *NewValue = UndefValue::get(CI->getType());
2403 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2404 "pointer-to-weak-pointer is undefined behavior.\n"
2405 " Old = " << *CI <<
2406 "\n New = " <<
2407 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002408
Michael Gottesmane5494922013-01-06 21:54:30 +00002409 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002410 CI->eraseFromParent();
2411 continue;
2412 }
2413 break;
2414 }
2415 case IC_Retain:
2416 OptimizeRetainCall(F, Inst);
2417 break;
2418 case IC_RetainRV:
2419 if (OptimizeRetainRVCall(F, Inst))
2420 continue;
2421 break;
2422 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002423 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002424 break;
2425 }
2426
2427 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2428 if (IsAutorelease(Class) && Inst->use_empty()) {
2429 CallInst *Call = cast<CallInst>(Inst);
2430 const Value *Arg = Call->getArgOperand(0);
2431 Arg = FindSingleUseIdentifiedObject(Arg);
2432 if (Arg) {
2433 Changed = true;
2434 ++NumAutoreleases;
2435
2436 // Create the declaration lazily.
2437 LLVMContext &C = Inst->getContext();
2438 CallInst *NewCall =
2439 CallInst::Create(getReleaseCallee(F.getParent()),
2440 Call->getArgOperand(0), "", Call);
2441 NewCall->setMetadata(ImpreciseReleaseMDKind,
2442 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002443
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002444 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2445 "objc_autorelease(x) with objc_release(x) since x is "
2446 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002447 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002448 "\n New: " <<
2449 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002450
John McCall9fbd3182011-06-15 23:37:01 +00002451 EraseInstruction(Call);
2452 Inst = NewCall;
2453 Class = IC_Release;
2454 }
2455 }
2456
2457 // For functions which can never be passed stack arguments, add
2458 // a tail keyword.
2459 if (IsAlwaysTail(Class)) {
2460 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002461 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2462 " to function since it can never be passed stack args: " << *Inst <<
2463 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002464 cast<CallInst>(Inst)->setTailCall();
2465 }
2466
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002467 // Ensure that functions that can never have a "tail" keyword due to the
2468 // semantics of ARC truly do not do so.
2469 if (IsNeverTail(Class)) {
2470 Changed = true;
2471 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2472 " from function: " << *Inst <<
2473 "\n");
2474 cast<CallInst>(Inst)->setTailCall(false);
2475 }
2476
John McCall9fbd3182011-06-15 23:37:01 +00002477 // Set nounwind as needed.
2478 if (IsNoThrow(Class)) {
2479 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002480 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2481 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002482 cast<CallInst>(Inst)->setDoesNotThrow();
2483 }
2484
2485 if (!IsNoopOnNull(Class)) {
2486 UsedInThisFunction |= 1 << Class;
2487 continue;
2488 }
2489
2490 const Value *Arg = GetObjCArg(Inst);
2491
2492 // ARC calls with null are no-ops. Delete them.
2493 if (isNullOrUndef(Arg)) {
2494 Changed = true;
2495 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002496 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2497 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002498 EraseInstruction(Inst);
2499 continue;
2500 }
2501
2502 // Keep track of which of retain, release, autorelease, and retain_block
2503 // are actually present in this function.
2504 UsedInThisFunction |= 1 << Class;
2505
2506 // If Arg is a PHI, and one or more incoming values to the
2507 // PHI are null, and the call is control-equivalent to the PHI, and there
2508 // are no relevant side effects between the PHI and the call, the call
2509 // could be pushed up to just those paths with non-null incoming values.
2510 // For now, don't bother splitting critical edges for this.
2511 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2512 Worklist.push_back(std::make_pair(Inst, Arg));
2513 do {
2514 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2515 Inst = Pair.first;
2516 Arg = Pair.second;
2517
2518 const PHINode *PN = dyn_cast<PHINode>(Arg);
2519 if (!PN) continue;
2520
2521 // Determine if the PHI has any null operands, or any incoming
2522 // critical edges.
2523 bool HasNull = false;
2524 bool HasCriticalEdges = false;
2525 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2526 Value *Incoming =
2527 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2528 if (isNullOrUndef(Incoming))
2529 HasNull = true;
2530 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2531 .getNumSuccessors() != 1) {
2532 HasCriticalEdges = true;
2533 break;
2534 }
2535 }
2536 // If we have null operands and no critical edges, optimize.
2537 if (!HasCriticalEdges && HasNull) {
2538 SmallPtrSet<Instruction *, 4> DependingInstructions;
2539 SmallPtrSet<const BasicBlock *, 4> Visited;
2540
2541 // Check that there is nothing that cares about the reference
2542 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002543 switch (Class) {
2544 case IC_Retain:
2545 case IC_RetainBlock:
2546 // These can always be moved up.
2547 break;
2548 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002549 // These can't be moved across things that care about the retain
2550 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002551 FindDependencies(NeedsPositiveRetainCount, Arg,
2552 Inst->getParent(), Inst,
2553 DependingInstructions, Visited, PA);
2554 break;
2555 case IC_Autorelease:
2556 // These can't be moved across autorelease pool scope boundaries.
2557 FindDependencies(AutoreleasePoolBoundary, Arg,
2558 Inst->getParent(), Inst,
2559 DependingInstructions, Visited, PA);
2560 break;
2561 case IC_RetainRV:
2562 case IC_AutoreleaseRV:
2563 // Don't move these; the RV optimization depends on the autoreleaseRV
2564 // being tail called, and the retainRV being immediately after a call
2565 // (which might still happen if we get lucky with codegen layout, but
2566 // it's not worth taking the chance).
2567 continue;
2568 default:
2569 llvm_unreachable("Invalid dependence flavor");
2570 }
2571
John McCall9fbd3182011-06-15 23:37:01 +00002572 if (DependingInstructions.size() == 1 &&
2573 *DependingInstructions.begin() == PN) {
2574 Changed = true;
2575 ++NumPartialNoops;
2576 // Clone the call into each predecessor that has a non-null value.
2577 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002578 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002579 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2580 Value *Incoming =
2581 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2582 if (!isNullOrUndef(Incoming)) {
2583 CallInst *Clone = cast<CallInst>(CInst->clone());
2584 Value *Op = PN->getIncomingValue(i);
2585 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2586 if (Op->getType() != ParamTy)
2587 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2588 Clone->setArgOperand(0, Op);
2589 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002590
2591 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2592 << *CInst << "\n"
2593 " And inserting "
2594 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002595 Worklist.push_back(std::make_pair(Clone, Incoming));
2596 }
2597 }
2598 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002599 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002600 EraseInstruction(CInst);
2601 continue;
2602 }
2603 }
2604 } while (!Worklist.empty());
2605 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002606 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002607}
2608
2609/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2610/// control flow, or other CFG structures where moving code across the edge
2611/// would result in it being executed more.
2612void
2613ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2614 DenseMap<const BasicBlock *, BBState> &BBStates,
2615 BBState &MyStates) const {
2616 // If any top-down local-use or possible-dec has a succ which is earlier in
2617 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002618 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002619 E = MyStates.top_down_ptr_end(); I != E; ++I)
2620 switch (I->second.GetSeq()) {
2621 default: break;
2622 case S_Use: {
2623 const Value *Arg = I->first;
2624 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2625 bool SomeSuccHasSame = false;
2626 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002627 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002628 succ_const_iterator SI(TI), SE(TI, false);
2629
2630 // If the terminator is an invoke marked with the
2631 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2632 // ignored, for ARC purposes.
2633 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2634 --SE;
2635
2636 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002637 Sequence SuccSSeq = S_None;
2638 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002639 // If VisitBottomUp has pointer information for this successor, take
2640 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002641 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2642 BBStates.find(*SI);
2643 assert(BBI != BBStates.end());
2644 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2645 SuccSSeq = SuccS.GetSeq();
2646 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002647 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002648 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002649 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002650 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002651 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002652 break;
2653 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002654 continue;
2655 }
John McCall9fbd3182011-06-15 23:37:01 +00002656 case S_Use:
2657 SomeSuccHasSame = true;
2658 break;
2659 case S_Stop:
2660 case S_Release:
2661 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002662 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002663 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002664 break;
2665 case S_Retain:
2666 llvm_unreachable("bottom-up pointer in retain state!");
2667 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002668 }
John McCall9fbd3182011-06-15 23:37:01 +00002669 // If the state at the other end of any of the successor edges
2670 // matches the current state, require all edges to match. This
2671 // guards against loops in the middle of a sequence.
2672 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002673 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002674 break;
John McCall9fbd3182011-06-15 23:37:01 +00002675 }
2676 case S_CanRelease: {
2677 const Value *Arg = I->first;
2678 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2679 bool SomeSuccHasSame = false;
2680 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002681 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002682 succ_const_iterator SI(TI), SE(TI, false);
2683
2684 // If the terminator is an invoke marked with the
2685 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2686 // ignored, for ARC purposes.
2687 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2688 --SE;
2689
2690 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002691 Sequence SuccSSeq = S_None;
2692 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002693 // If VisitBottomUp has pointer information for this successor, take
2694 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002695 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2696 BBStates.find(*SI);
2697 assert(BBI != BBStates.end());
2698 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2699 SuccSSeq = SuccS.GetSeq();
2700 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002701 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002702 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002703 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002704 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002705 break;
2706 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002707 continue;
2708 }
John McCall9fbd3182011-06-15 23:37:01 +00002709 case S_CanRelease:
2710 SomeSuccHasSame = true;
2711 break;
2712 case S_Stop:
2713 case S_Release:
2714 case S_MovableRelease:
2715 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002716 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002717 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002718 break;
2719 case S_Retain:
2720 llvm_unreachable("bottom-up pointer in retain state!");
2721 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002722 }
John McCall9fbd3182011-06-15 23:37:01 +00002723 // If the state at the other end of any of the successor edges
2724 // matches the current state, require all edges to match. This
2725 // guards against loops in the middle of a sequence.
2726 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002727 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002728 break;
John McCall9fbd3182011-06-15 23:37:01 +00002729 }
2730 }
2731}
2732
2733bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002734ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002735 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002736 MapVector<Value *, RRInfo> &Retains,
2737 BBState &MyStates) {
2738 bool NestingDetected = false;
2739 InstructionClass Class = GetInstructionClass(Inst);
2740 const Value *Arg = 0;
2741
2742 switch (Class) {
2743 case IC_Release: {
2744 Arg = GetObjCArg(Inst);
2745
2746 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2747
2748 // If we see two releases in a row on the same pointer. If so, make
2749 // a note, and we'll cicle back to revisit it after we've
2750 // hopefully eliminated the second release, which may allow us to
2751 // eliminate the first release too.
2752 // Theoretically we could implement removal of nested retain+release
2753 // pairs by making PtrState hold a stack of states, but this is
2754 // simple and avoids adding overhead for the non-nested case.
2755 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2756 NestingDetected = true;
2757
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002758 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002759 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002760 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002761 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002762 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2763 S.RRI.Calls.insert(Inst);
2764
Dan Gohman230768b2012-09-04 23:16:20 +00002765 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002766 break;
2767 }
2768 case IC_RetainBlock:
2769 // An objc_retainBlock call with just a use may need to be kept,
2770 // because it may be copying a block from the stack to the heap.
2771 if (!IsRetainBlockOptimizable(Inst))
2772 break;
2773 // FALLTHROUGH
2774 case IC_Retain:
2775 case IC_RetainRV: {
2776 Arg = GetObjCArg(Inst);
2777
2778 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002779 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002780
2781 switch (S.GetSeq()) {
2782 case S_Stop:
2783 case S_Release:
2784 case S_MovableRelease:
2785 case S_Use:
2786 S.RRI.ReverseInsertPts.clear();
2787 // FALL THROUGH
2788 case S_CanRelease:
2789 // Don't do retain+release tracking for IC_RetainRV, because it's
2790 // better to let it remain as the first instruction after a call.
2791 if (Class != IC_RetainRV) {
2792 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2793 Retains[Inst] = S.RRI;
2794 }
2795 S.ClearSequenceProgress();
2796 break;
2797 case S_None:
2798 break;
2799 case S_Retain:
2800 llvm_unreachable("bottom-up pointer in retain state!");
2801 }
2802 return NestingDetected;
2803 }
2804 case IC_AutoreleasepoolPop:
2805 // Conservatively, clear MyStates for all known pointers.
2806 MyStates.clearBottomUpPointers();
2807 return NestingDetected;
2808 case IC_AutoreleasepoolPush:
2809 case IC_None:
2810 // These are irrelevant.
2811 return NestingDetected;
2812 default:
2813 break;
2814 }
2815
2816 // Consider any other possible effects of this instruction on each
2817 // pointer being tracked.
2818 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2819 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2820 const Value *Ptr = MI->first;
2821 if (Ptr == Arg)
2822 continue; // Handled above.
2823 PtrState &S = MI->second;
2824 Sequence Seq = S.GetSeq();
2825
2826 // Check for possible releases.
2827 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002828 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002829 switch (Seq) {
2830 case S_Use:
2831 S.SetSeq(S_CanRelease);
2832 continue;
2833 case S_CanRelease:
2834 case S_Release:
2835 case S_MovableRelease:
2836 case S_Stop:
2837 case S_None:
2838 break;
2839 case S_Retain:
2840 llvm_unreachable("bottom-up pointer in retain state!");
2841 }
2842 }
2843
2844 // Check for possible direct uses.
2845 switch (Seq) {
2846 case S_Release:
2847 case S_MovableRelease:
2848 if (CanUse(Inst, Ptr, PA, Class)) {
2849 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002850 // If this is an invoke instruction, we're scanning it as part of
2851 // one of its successor blocks, since we can't insert code after it
2852 // in its own block, and we don't want to split critical edges.
2853 if (isa<InvokeInst>(Inst))
2854 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2855 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002856 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002857 S.SetSeq(S_Use);
2858 } else if (Seq == S_Release &&
2859 (Class == IC_User || Class == IC_CallOrUser)) {
2860 // Non-movable releases depend on any possible objc pointer use.
2861 S.SetSeq(S_Stop);
2862 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002863 // As above; handle invoke specially.
2864 if (isa<InvokeInst>(Inst))
2865 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2866 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002867 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002868 }
2869 break;
2870 case S_Stop:
2871 if (CanUse(Inst, Ptr, PA, Class))
2872 S.SetSeq(S_Use);
2873 break;
2874 case S_CanRelease:
2875 case S_Use:
2876 case S_None:
2877 break;
2878 case S_Retain:
2879 llvm_unreachable("bottom-up pointer in retain state!");
2880 }
2881 }
2882
2883 return NestingDetected;
2884}
2885
2886bool
John McCall9fbd3182011-06-15 23:37:01 +00002887ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2888 DenseMap<const BasicBlock *, BBState> &BBStates,
2889 MapVector<Value *, RRInfo> &Retains) {
2890 bool NestingDetected = false;
2891 BBState &MyStates = BBStates[BB];
2892
2893 // Merge the states from each successor to compute the initial state
2894 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002895 BBState::edge_iterator SI(MyStates.succ_begin()),
2896 SE(MyStates.succ_end());
2897 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002898 const BasicBlock *Succ = *SI;
2899 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2900 assert(I != BBStates.end());
2901 MyStates.InitFromSucc(I->second);
2902 ++SI;
2903 for (; SI != SE; ++SI) {
2904 Succ = *SI;
2905 I = BBStates.find(Succ);
2906 assert(I != BBStates.end());
2907 MyStates.MergeSucc(I->second);
2908 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002909 }
John McCall9fbd3182011-06-15 23:37:01 +00002910
2911 // Visit all the instructions, bottom-up.
2912 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2913 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002914
2915 // Invoke instructions are visited as part of their successors (below).
2916 if (isa<InvokeInst>(Inst))
2917 continue;
2918
2919 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2920 }
2921
Dan Gohman447989c2012-04-27 18:56:31 +00002922 // If there's a predecessor with an invoke, visit the invoke as if it were
2923 // part of this block, since we can't insert code after an invoke in its own
2924 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002925 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2926 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002927 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002928 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2929 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002930 }
John McCall9fbd3182011-06-15 23:37:01 +00002931
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002932 return NestingDetected;
2933}
John McCall9fbd3182011-06-15 23:37:01 +00002934
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002935bool
2936ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2937 DenseMap<Value *, RRInfo> &Releases,
2938 BBState &MyStates) {
2939 bool NestingDetected = false;
2940 InstructionClass Class = GetInstructionClass(Inst);
2941 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002942
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002943 switch (Class) {
2944 case IC_RetainBlock:
2945 // An objc_retainBlock call with just a use may need to be kept,
2946 // because it may be copying a block from the stack to the heap.
2947 if (!IsRetainBlockOptimizable(Inst))
2948 break;
2949 // FALLTHROUGH
2950 case IC_Retain:
2951 case IC_RetainRV: {
2952 Arg = GetObjCArg(Inst);
2953
2954 PtrState &S = MyStates.getPtrTopDownState(Arg);
2955
2956 // Don't do retain+release tracking for IC_RetainRV, because it's
2957 // better to let it remain as the first instruction after a call.
2958 if (Class != IC_RetainRV) {
2959 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002960 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002961 // hopefully eliminated the second retain, which may allow us to
2962 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002963 // Theoretically we could implement removal of nested retain+release
2964 // pairs by making PtrState hold a stack of states, but this is
2965 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002966 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002967 NestingDetected = true;
2968
Dan Gohman50ade652012-04-25 00:50:46 +00002969 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002970 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002971 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002972 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002973 }
John McCall9fbd3182011-06-15 23:37:01 +00002974
Dan Gohman230768b2012-09-04 23:16:20 +00002975 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002976
2977 // A retain can be a potential use; procede to the generic checking
2978 // code below.
2979 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002980 }
2981 case IC_Release: {
2982 Arg = GetObjCArg(Inst);
2983
2984 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00002985 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002986
2987 switch (S.GetSeq()) {
2988 case S_Retain:
2989 case S_CanRelease:
2990 S.RRI.ReverseInsertPts.clear();
2991 // FALL THROUGH
2992 case S_Use:
2993 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2994 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2995 Releases[Inst] = S.RRI;
2996 S.ClearSequenceProgress();
2997 break;
2998 case S_None:
2999 break;
3000 case S_Stop:
3001 case S_Release:
3002 case S_MovableRelease:
3003 llvm_unreachable("top-down pointer in release state!");
3004 }
3005 break;
3006 }
3007 case IC_AutoreleasepoolPop:
3008 // Conservatively, clear MyStates for all known pointers.
3009 MyStates.clearTopDownPointers();
3010 return NestingDetected;
3011 case IC_AutoreleasepoolPush:
3012 case IC_None:
3013 // These are irrelevant.
3014 return NestingDetected;
3015 default:
3016 break;
3017 }
3018
3019 // Consider any other possible effects of this instruction on each
3020 // pointer being tracked.
3021 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3022 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3023 const Value *Ptr = MI->first;
3024 if (Ptr == Arg)
3025 continue; // Handled above.
3026 PtrState &S = MI->second;
3027 Sequence Seq = S.GetSeq();
3028
3029 // Check for possible releases.
3030 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003031 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003032 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003033 case S_Retain:
3034 S.SetSeq(S_CanRelease);
3035 assert(S.RRI.ReverseInsertPts.empty());
3036 S.RRI.ReverseInsertPts.insert(Inst);
3037
3038 // One call can't cause a transition from S_Retain to S_CanRelease
3039 // and S_CanRelease to S_Use. If we've made the first transition,
3040 // we're done.
3041 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003042 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003043 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003044 case S_None:
3045 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003046 case S_Stop:
3047 case S_Release:
3048 case S_MovableRelease:
3049 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003050 }
3051 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003052
3053 // Check for possible direct uses.
3054 switch (Seq) {
3055 case S_CanRelease:
3056 if (CanUse(Inst, Ptr, PA, Class))
3057 S.SetSeq(S_Use);
3058 break;
3059 case S_Retain:
3060 case S_Use:
3061 case S_None:
3062 break;
3063 case S_Stop:
3064 case S_Release:
3065 case S_MovableRelease:
3066 llvm_unreachable("top-down pointer in release state!");
3067 }
John McCall9fbd3182011-06-15 23:37:01 +00003068 }
3069
3070 return NestingDetected;
3071}
3072
3073bool
3074ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3075 DenseMap<const BasicBlock *, BBState> &BBStates,
3076 DenseMap<Value *, RRInfo> &Releases) {
3077 bool NestingDetected = false;
3078 BBState &MyStates = BBStates[BB];
3079
3080 // Merge the states from each predecessor to compute the initial state
3081 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003082 BBState::edge_iterator PI(MyStates.pred_begin()),
3083 PE(MyStates.pred_end());
3084 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003085 const BasicBlock *Pred = *PI;
3086 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3087 assert(I != BBStates.end());
3088 MyStates.InitFromPred(I->second);
3089 ++PI;
3090 for (; PI != PE; ++PI) {
3091 Pred = *PI;
3092 I = BBStates.find(Pred);
3093 assert(I != BBStates.end());
3094 MyStates.MergePred(I->second);
3095 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003096 }
John McCall9fbd3182011-06-15 23:37:01 +00003097
3098 // Visit all the instructions, top-down.
3099 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3100 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003101 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003102 }
3103
3104 CheckForCFGHazards(BB, BBStates, MyStates);
3105 return NestingDetected;
3106}
3107
Dan Gohman59a1c932011-12-12 19:42:25 +00003108static void
3109ComputePostOrders(Function &F,
3110 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003111 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3112 unsigned NoObjCARCExceptionsMDKind,
3113 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003114 /// Visited - The visited set, for doing DFS walks.
3115 SmallPtrSet<BasicBlock *, 16> Visited;
3116
3117 // Do DFS, computing the PostOrder.
3118 SmallPtrSet<BasicBlock *, 16> OnStack;
3119 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003120
3121 // Functions always have exactly one entry block, and we don't have
3122 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003123 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003124 BBState &MyStates = BBStates[EntryBB];
3125 MyStates.SetAsEntry();
3126 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3127 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003128 Visited.insert(EntryBB);
3129 OnStack.insert(EntryBB);
3130 do {
3131 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003132 BasicBlock *CurrBB = SuccStack.back().first;
3133 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3134 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003135
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003136 // If the terminator is an invoke marked with the
3137 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3138 // ignored, for ARC purposes.
3139 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3140 --SE;
3141
3142 while (SuccStack.back().second != SE) {
3143 BasicBlock *SuccBB = *SuccStack.back().second++;
3144 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003145 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3146 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003147 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003148 BBState &SuccStates = BBStates[SuccBB];
3149 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003150 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003151 goto dfs_next_succ;
3152 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003153
3154 if (!OnStack.count(SuccBB)) {
3155 BBStates[CurrBB].addSucc(SuccBB);
3156 BBStates[SuccBB].addPred(CurrBB);
3157 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003158 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003159 OnStack.erase(CurrBB);
3160 PostOrder.push_back(CurrBB);
3161 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003162 } while (!SuccStack.empty());
3163
3164 Visited.clear();
3165
Dan Gohman59a1c932011-12-12 19:42:25 +00003166 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003167 // Functions may have many exits, and there also blocks which we treat
3168 // as exits due to ignored edges.
3169 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3170 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3171 BasicBlock *ExitBB = I;
3172 BBState &MyStates = BBStates[ExitBB];
3173 if (!MyStates.isExit())
3174 continue;
3175
Dan Gohman447989c2012-04-27 18:56:31 +00003176 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003177
3178 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003179 Visited.insert(ExitBB);
3180 while (!PredStack.empty()) {
3181 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003182 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3183 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003184 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003185 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003186 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003187 goto reverse_dfs_next_succ;
3188 }
3189 }
3190 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3191 }
3192 }
3193}
3194
John McCall9fbd3182011-06-15 23:37:01 +00003195// Visit - Visit the function both top-down and bottom-up.
3196bool
3197ObjCARCOpt::Visit(Function &F,
3198 DenseMap<const BasicBlock *, BBState> &BBStates,
3199 MapVector<Value *, RRInfo> &Retains,
3200 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003201
3202 // Use reverse-postorder traversals, because we magically know that loops
3203 // will be well behaved, i.e. they won't repeatedly call retain on a single
3204 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3205 // class here because we want the reverse-CFG postorder to consider each
3206 // function exit point, and we want to ignore selected cycle edges.
3207 SmallVector<BasicBlock *, 16> PostOrder;
3208 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003209 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3210 NoObjCARCExceptionsMDKind,
3211 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003212
3213 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003214 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003215 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003216 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3217 I != E; ++I)
3218 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003219
Dan Gohman59a1c932011-12-12 19:42:25 +00003220 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003221 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003222 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3223 PostOrder.rbegin(), E = PostOrder.rend();
3224 I != E; ++I)
3225 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003226
3227 return TopDownNestingDetected && BottomUpNestingDetected;
3228}
3229
3230/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3231void ObjCARCOpt::MoveCalls(Value *Arg,
3232 RRInfo &RetainsToMove,
3233 RRInfo &ReleasesToMove,
3234 MapVector<Value *, RRInfo> &Retains,
3235 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003236 SmallVectorImpl<Instruction *> &DeadInsts,
3237 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003238 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003239 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003240
3241 // Insert the new retain and release calls.
3242 for (SmallPtrSet<Instruction *, 2>::const_iterator
3243 PI = ReleasesToMove.ReverseInsertPts.begin(),
3244 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3245 Instruction *InsertPt = *PI;
3246 Value *MyArg = ArgTy == ParamTy ? Arg :
3247 new BitCastInst(Arg, ParamTy, "", InsertPt);
3248 CallInst *Call =
3249 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003250 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003251 MyArg, "", InsertPt);
3252 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003253 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003254 Call->setMetadata(CopyOnEscapeMDKind,
3255 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003256 else
John McCall9fbd3182011-06-15 23:37:01 +00003257 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003258
3259 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3260 << "\n"
3261 " At insertion point: " << *InsertPt
3262 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003263 }
3264 for (SmallPtrSet<Instruction *, 2>::const_iterator
3265 PI = RetainsToMove.ReverseInsertPts.begin(),
3266 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003267 Instruction *InsertPt = *PI;
3268 Value *MyArg = ArgTy == ParamTy ? Arg :
3269 new BitCastInst(Arg, ParamTy, "", InsertPt);
3270 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3271 "", InsertPt);
3272 // Attach a clang.imprecise_release metadata tag, if appropriate.
3273 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3274 Call->setMetadata(ImpreciseReleaseMDKind, M);
3275 Call->setDoesNotThrow();
3276 if (ReleasesToMove.IsTailCallRelease)
3277 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003278
3279 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3280 << "\n"
3281 " At insertion point: " << *InsertPt
3282 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003283 }
3284
3285 // Delete the original retain and release calls.
3286 for (SmallPtrSet<Instruction *, 2>::const_iterator
3287 AI = RetainsToMove.Calls.begin(),
3288 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3289 Instruction *OrigRetain = *AI;
3290 Retains.blot(OrigRetain);
3291 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003292 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3293 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003294 }
3295 for (SmallPtrSet<Instruction *, 2>::const_iterator
3296 AI = ReleasesToMove.Calls.begin(),
3297 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3298 Instruction *OrigRelease = *AI;
3299 Releases.erase(OrigRelease);
3300 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003301 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3302 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003303 }
3304}
3305
Dan Gohmand6bf2012012-04-13 18:57:48 +00003306/// PerformCodePlacement - Identify pairings between the retains and releases,
3307/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003308bool
3309ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3310 &BBStates,
3311 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003312 DenseMap<Value *, RRInfo> &Releases,
3313 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003314 bool AnyPairsCompletelyEliminated = false;
3315 RRInfo RetainsToMove;
3316 RRInfo ReleasesToMove;
3317 SmallVector<Instruction *, 4> NewRetains;
3318 SmallVector<Instruction *, 4> NewReleases;
3319 SmallVector<Instruction *, 8> DeadInsts;
3320
Dan Gohmand6bf2012012-04-13 18:57:48 +00003321 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003322 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003323 E = Retains.end(); I != E; ++I) {
3324 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003325 if (!V) continue; // blotted
3326
3327 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003328
3329 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3330 << "\n");
3331
John McCall9fbd3182011-06-15 23:37:01 +00003332 Value *Arg = GetObjCArg(Retain);
3333
Dan Gohman79522dc2012-01-13 00:39:07 +00003334 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003335 // not being managed by ObjC reference counting, so we can delete pairs
3336 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003337 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003338
Dan Gohman1b31ea82011-08-22 17:29:11 +00003339 // A constant pointer can't be pointing to an object on the heap. It may
3340 // be reference-counted, but it won't be deleted.
3341 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3342 if (const GlobalVariable *GV =
3343 dyn_cast<GlobalVariable>(
3344 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3345 if (GV->isConstant())
3346 KnownSafe = true;
3347
John McCall9fbd3182011-06-15 23:37:01 +00003348 // If a pair happens in a region where it is known that the reference count
3349 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003350 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003351
3352 // Connect the dots between the top-down-collected RetainsToMove and
3353 // bottom-up-collected ReleasesToMove to form sets of related calls.
3354 // This is an iterative process so that we connect multiple releases
3355 // to multiple retains if needed.
3356 unsigned OldDelta = 0;
3357 unsigned NewDelta = 0;
3358 unsigned OldCount = 0;
3359 unsigned NewCount = 0;
3360 bool FirstRelease = true;
3361 bool FirstRetain = true;
3362 NewRetains.push_back(Retain);
3363 for (;;) {
3364 for (SmallVectorImpl<Instruction *>::const_iterator
3365 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3366 Instruction *NewRetain = *NI;
3367 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3368 assert(It != Retains.end());
3369 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003370 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003371 for (SmallPtrSet<Instruction *, 2>::const_iterator
3372 LI = NewRetainRRI.Calls.begin(),
3373 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3374 Instruction *NewRetainRelease = *LI;
3375 DenseMap<Value *, RRInfo>::const_iterator Jt =
3376 Releases.find(NewRetainRelease);
3377 if (Jt == Releases.end())
3378 goto next_retain;
3379 const RRInfo &NewRetainReleaseRRI = Jt->second;
3380 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3381 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3382 OldDelta -=
3383 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3384
3385 // Merge the ReleaseMetadata and IsTailCallRelease values.
3386 if (FirstRelease) {
3387 ReleasesToMove.ReleaseMetadata =
3388 NewRetainReleaseRRI.ReleaseMetadata;
3389 ReleasesToMove.IsTailCallRelease =
3390 NewRetainReleaseRRI.IsTailCallRelease;
3391 FirstRelease = false;
3392 } else {
3393 if (ReleasesToMove.ReleaseMetadata !=
3394 NewRetainReleaseRRI.ReleaseMetadata)
3395 ReleasesToMove.ReleaseMetadata = 0;
3396 if (ReleasesToMove.IsTailCallRelease !=
3397 NewRetainReleaseRRI.IsTailCallRelease)
3398 ReleasesToMove.IsTailCallRelease = false;
3399 }
3400
3401 // Collect the optimal insertion points.
3402 if (!KnownSafe)
3403 for (SmallPtrSet<Instruction *, 2>::const_iterator
3404 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3405 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3406 RI != RE; ++RI) {
3407 Instruction *RIP = *RI;
3408 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3409 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3410 }
3411 NewReleases.push_back(NewRetainRelease);
3412 }
3413 }
3414 }
3415 NewRetains.clear();
3416 if (NewReleases.empty()) break;
3417
3418 // Back the other way.
3419 for (SmallVectorImpl<Instruction *>::const_iterator
3420 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3421 Instruction *NewRelease = *NI;
3422 DenseMap<Value *, RRInfo>::const_iterator It =
3423 Releases.find(NewRelease);
3424 assert(It != Releases.end());
3425 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003426 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003427 for (SmallPtrSet<Instruction *, 2>::const_iterator
3428 LI = NewReleaseRRI.Calls.begin(),
3429 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3430 Instruction *NewReleaseRetain = *LI;
3431 MapVector<Value *, RRInfo>::const_iterator Jt =
3432 Retains.find(NewReleaseRetain);
3433 if (Jt == Retains.end())
3434 goto next_retain;
3435 const RRInfo &NewReleaseRetainRRI = Jt->second;
3436 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3437 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3438 unsigned PathCount =
3439 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3440 OldDelta += PathCount;
3441 OldCount += PathCount;
3442
3443 // Merge the IsRetainBlock values.
3444 if (FirstRetain) {
3445 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3446 FirstRetain = false;
3447 } else if (ReleasesToMove.IsRetainBlock !=
3448 NewReleaseRetainRRI.IsRetainBlock)
3449 // It's not possible to merge the sequences if one uses
3450 // objc_retain and the other uses objc_retainBlock.
3451 goto next_retain;
3452
3453 // Collect the optimal insertion points.
3454 if (!KnownSafe)
3455 for (SmallPtrSet<Instruction *, 2>::const_iterator
3456 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3457 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3458 RI != RE; ++RI) {
3459 Instruction *RIP = *RI;
3460 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3461 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3462 NewDelta += PathCount;
3463 NewCount += PathCount;
3464 }
3465 }
3466 NewRetains.push_back(NewReleaseRetain);
3467 }
3468 }
3469 }
3470 NewReleases.clear();
3471 if (NewRetains.empty()) break;
3472 }
3473
Dan Gohmane6d5e882011-08-19 00:26:36 +00003474 // If the pointer is known incremented or nested, we can safely delete the
3475 // pair regardless of what's between them.
3476 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003477 RetainsToMove.ReverseInsertPts.clear();
3478 ReleasesToMove.ReverseInsertPts.clear();
3479 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003480 } else {
3481 // Determine whether the new insertion points we computed preserve the
3482 // balance of retain and release calls through the program.
3483 // TODO: If the fully aggressive solution isn't valid, try to find a
3484 // less aggressive solution which is.
3485 if (NewDelta != 0)
3486 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003487 }
3488
3489 // Determine whether the original call points are balanced in the retain and
3490 // release calls through the program. If not, conservatively don't touch
3491 // them.
3492 // TODO: It's theoretically possible to do code motion in this case, as
3493 // long as the existing imbalances are maintained.
3494 if (OldDelta != 0)
3495 goto next_retain;
3496
John McCall9fbd3182011-06-15 23:37:01 +00003497 // Ok, everything checks out and we're all set. Let's move some code!
3498 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003499 assert(OldCount != 0 && "Unreachable code?");
3500 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003501 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003502 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3503 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003504
3505 next_retain:
3506 NewReleases.clear();
3507 NewRetains.clear();
3508 RetainsToMove.clear();
3509 ReleasesToMove.clear();
3510 }
3511
3512 // Now that we're done moving everything, we can delete the newly dead
3513 // instructions, as we no longer need them as insert points.
3514 while (!DeadInsts.empty())
3515 EraseInstruction(DeadInsts.pop_back_val());
3516
3517 return AnyPairsCompletelyEliminated;
3518}
3519
3520/// OptimizeWeakCalls - Weak pointer optimizations.
3521void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3522 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3523 // itself because it uses AliasAnalysis and we need to do provenance
3524 // queries instead.
3525 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3526 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003527
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003528 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003529 "\n");
3530
John McCall9fbd3182011-06-15 23:37:01 +00003531 InstructionClass Class = GetBasicInstructionClass(Inst);
3532 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3533 continue;
3534
3535 // Delete objc_loadWeak calls with no users.
3536 if (Class == IC_LoadWeak && Inst->use_empty()) {
3537 Inst->eraseFromParent();
3538 continue;
3539 }
3540
3541 // TODO: For now, just look for an earlier available version of this value
3542 // within the same block. Theoretically, we could do memdep-style non-local
3543 // analysis too, but that would want caching. A better approach would be to
3544 // use the technique that EarlyCSE uses.
3545 inst_iterator Current = llvm::prior(I);
3546 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3547 for (BasicBlock::iterator B = CurrentBB->begin(),
3548 J = Current.getInstructionIterator();
3549 J != B; --J) {
3550 Instruction *EarlierInst = &*llvm::prior(J);
3551 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3552 switch (EarlierClass) {
3553 case IC_LoadWeak:
3554 case IC_LoadWeakRetained: {
3555 // If this is loading from the same pointer, replace this load's value
3556 // with that one.
3557 CallInst *Call = cast<CallInst>(Inst);
3558 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3559 Value *Arg = Call->getArgOperand(0);
3560 Value *EarlierArg = EarlierCall->getArgOperand(0);
3561 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3562 case AliasAnalysis::MustAlias:
3563 Changed = true;
3564 // If the load has a builtin retain, insert a plain retain for it.
3565 if (Class == IC_LoadWeakRetained) {
3566 CallInst *CI =
3567 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3568 "", Call);
3569 CI->setTailCall();
3570 }
3571 // Zap the fully redundant load.
3572 Call->replaceAllUsesWith(EarlierCall);
3573 Call->eraseFromParent();
3574 goto clobbered;
3575 case AliasAnalysis::MayAlias:
3576 case AliasAnalysis::PartialAlias:
3577 goto clobbered;
3578 case AliasAnalysis::NoAlias:
3579 break;
3580 }
3581 break;
3582 }
3583 case IC_StoreWeak:
3584 case IC_InitWeak: {
3585 // If this is storing to the same pointer and has the same size etc.
3586 // replace this load's value with the stored value.
3587 CallInst *Call = cast<CallInst>(Inst);
3588 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3589 Value *Arg = Call->getArgOperand(0);
3590 Value *EarlierArg = EarlierCall->getArgOperand(0);
3591 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3592 case AliasAnalysis::MustAlias:
3593 Changed = true;
3594 // If the load has a builtin retain, insert a plain retain for it.
3595 if (Class == IC_LoadWeakRetained) {
3596 CallInst *CI =
3597 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3598 "", Call);
3599 CI->setTailCall();
3600 }
3601 // Zap the fully redundant load.
3602 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3603 Call->eraseFromParent();
3604 goto clobbered;
3605 case AliasAnalysis::MayAlias:
3606 case AliasAnalysis::PartialAlias:
3607 goto clobbered;
3608 case AliasAnalysis::NoAlias:
3609 break;
3610 }
3611 break;
3612 }
3613 case IC_MoveWeak:
3614 case IC_CopyWeak:
3615 // TOOD: Grab the copied value.
3616 goto clobbered;
3617 case IC_AutoreleasepoolPush:
3618 case IC_None:
3619 case IC_User:
3620 // Weak pointers are only modified through the weak entry points
3621 // (and arbitrary calls, which could call the weak entry points).
3622 break;
3623 default:
3624 // Anything else could modify the weak pointer.
3625 goto clobbered;
3626 }
3627 }
3628 clobbered:;
3629 }
3630
3631 // Then, for each destroyWeak with an alloca operand, check to see if
3632 // the alloca and all its users can be zapped.
3633 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3634 Instruction *Inst = &*I++;
3635 InstructionClass Class = GetBasicInstructionClass(Inst);
3636 if (Class != IC_DestroyWeak)
3637 continue;
3638
3639 CallInst *Call = cast<CallInst>(Inst);
3640 Value *Arg = Call->getArgOperand(0);
3641 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3642 for (Value::use_iterator UI = Alloca->use_begin(),
3643 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003644 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003645 switch (GetBasicInstructionClass(UserInst)) {
3646 case IC_InitWeak:
3647 case IC_StoreWeak:
3648 case IC_DestroyWeak:
3649 continue;
3650 default:
3651 goto done;
3652 }
3653 }
3654 Changed = true;
3655 for (Value::use_iterator UI = Alloca->use_begin(),
3656 UE = Alloca->use_end(); UI != UE; ) {
3657 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003658 switch (GetBasicInstructionClass(UserInst)) {
3659 case IC_InitWeak:
3660 case IC_StoreWeak:
3661 // These functions return their second argument.
3662 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3663 break;
3664 case IC_DestroyWeak:
3665 // No return value.
3666 break;
3667 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003668 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003669 }
John McCall9fbd3182011-06-15 23:37:01 +00003670 UserInst->eraseFromParent();
3671 }
3672 Alloca->eraseFromParent();
3673 done:;
3674 }
3675 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003676
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003677 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003678
John McCall9fbd3182011-06-15 23:37:01 +00003679}
3680
3681/// OptimizeSequences - Identify program paths which execute sequences of
3682/// retains and releases which can be eliminated.
3683bool ObjCARCOpt::OptimizeSequences(Function &F) {
3684 /// Releases, Retains - These are used to store the results of the main flow
3685 /// analysis. These use Value* as the key instead of Instruction* so that the
3686 /// map stays valid when we get around to rewriting code and calls get
3687 /// replaced by arguments.
3688 DenseMap<Value *, RRInfo> Releases;
3689 MapVector<Value *, RRInfo> Retains;
3690
3691 /// BBStates, This is used during the traversal of the function to track the
3692 /// states for each identified object at each block.
3693 DenseMap<const BasicBlock *, BBState> BBStates;
3694
3695 // Analyze the CFG of the function, and all instructions.
3696 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3697
3698 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003699 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3700 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003701}
3702
3703/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003704/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003705/// %call = call i8* @something(...)
3706/// %2 = call i8* @objc_retain(i8* %call)
3707/// %3 = call i8* @objc_autorelease(i8* %2)
3708/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003709/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003710/// And delete the retain and autorelease.
3711///
3712/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003713/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003714/// %3 = call i8* @objc_autorelease(i8* %2)
3715/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003716/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003717/// convert the autorelease to autoreleaseRV.
3718void ObjCARCOpt::OptimizeReturns(Function &F) {
3719 if (!F.getReturnType()->isPointerTy())
3720 return;
3721
3722 SmallPtrSet<Instruction *, 4> DependingInstructions;
3723 SmallPtrSet<const BasicBlock *, 4> Visited;
3724 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3725 BasicBlock *BB = FI;
3726 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003727
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003728 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003729
John McCall9fbd3182011-06-15 23:37:01 +00003730 if (!Ret) continue;
3731
3732 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3733 FindDependencies(NeedsPositiveRetainCount, Arg,
3734 BB, Ret, DependingInstructions, Visited, PA);
3735 if (DependingInstructions.size() != 1)
3736 goto next_block;
3737
3738 {
3739 CallInst *Autorelease =
3740 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3741 if (!Autorelease)
3742 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003743 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003744 if (!IsAutorelease(AutoreleaseClass))
3745 goto next_block;
3746 if (GetObjCArg(Autorelease) != Arg)
3747 goto next_block;
3748
3749 DependingInstructions.clear();
3750 Visited.clear();
3751
3752 // Check that there is nothing that can affect the reference
3753 // count between the autorelease and the retain.
3754 FindDependencies(CanChangeRetainCount, Arg,
3755 BB, Autorelease, DependingInstructions, Visited, PA);
3756 if (DependingInstructions.size() != 1)
3757 goto next_block;
3758
3759 {
3760 CallInst *Retain =
3761 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3762
3763 // Check that we found a retain with the same argument.
3764 if (!Retain ||
3765 !IsRetain(GetBasicInstructionClass(Retain)) ||
3766 GetObjCArg(Retain) != Arg)
3767 goto next_block;
3768
3769 DependingInstructions.clear();
3770 Visited.clear();
3771
3772 // Convert the autorelease to an autoreleaseRV, since it's
3773 // returning the value.
3774 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003775 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3776 "=> autoreleaseRV since it's returning a value.\n"
3777 " In: " << *Autorelease
3778 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003779 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003780 DEBUG(dbgs() << " Out: " << *Autorelease
3781 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003782 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003783 AutoreleaseClass = IC_AutoreleaseRV;
3784 }
3785
3786 // Check that there is nothing that can affect the reference
3787 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003788 // Note that Retain need not be in BB.
3789 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003790 DependingInstructions, Visited, PA);
3791 if (DependingInstructions.size() != 1)
3792 goto next_block;
3793
3794 {
3795 CallInst *Call =
3796 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3797
3798 // Check that the pointer is the return value of the call.
3799 if (!Call || Arg != Call)
3800 goto next_block;
3801
3802 // Check that the call is a regular call.
3803 InstructionClass Class = GetBasicInstructionClass(Call);
3804 if (Class != IC_CallOrUser && Class != IC_Call)
3805 goto next_block;
3806
3807 // If so, we can zap the retain and autorelease.
3808 Changed = true;
3809 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003810 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3811 << "\n Erasing: "
3812 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003813 EraseInstruction(Retain);
3814 EraseInstruction(Autorelease);
3815 }
3816 }
3817 }
3818
3819 next_block:
3820 DependingInstructions.clear();
3821 Visited.clear();
3822 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003823
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003824 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003825
John McCall9fbd3182011-06-15 23:37:01 +00003826}
3827
3828bool ObjCARCOpt::doInitialization(Module &M) {
3829 if (!EnableARCOpts)
3830 return false;
3831
Dan Gohmand6bf2012012-04-13 18:57:48 +00003832 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003833 Run = ModuleHasARC(M);
3834 if (!Run)
3835 return false;
3836
John McCall9fbd3182011-06-15 23:37:01 +00003837 // Identify the imprecise release metadata kind.
3838 ImpreciseReleaseMDKind =
3839 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003840 CopyOnEscapeMDKind =
3841 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003842 NoObjCARCExceptionsMDKind =
3843 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003844
John McCall9fbd3182011-06-15 23:37:01 +00003845 // Intuitively, objc_retain and others are nocapture, however in practice
3846 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003847 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003848
3849 // These are initialized lazily.
3850 RetainRVCallee = 0;
3851 AutoreleaseRVCallee = 0;
3852 ReleaseCallee = 0;
3853 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003854 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003855 AutoreleaseCallee = 0;
3856
3857 return false;
3858}
3859
3860bool ObjCARCOpt::runOnFunction(Function &F) {
3861 if (!EnableARCOpts)
3862 return false;
3863
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003864 // If nothing in the Module uses ARC, don't do anything.
3865 if (!Run)
3866 return false;
3867
John McCall9fbd3182011-06-15 23:37:01 +00003868 Changed = false;
3869
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003870 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3871
John McCall9fbd3182011-06-15 23:37:01 +00003872 PA.setAA(&getAnalysis<AliasAnalysis>());
3873
3874 // This pass performs several distinct transformations. As a compile-time aid
3875 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3876 // library functions aren't declared.
3877
3878 // Preliminary optimizations. This also computs UsedInThisFunction.
3879 OptimizeIndividualCalls(F);
3880
3881 // Optimizations for weak pointers.
3882 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3883 (1 << IC_LoadWeakRetained) |
3884 (1 << IC_StoreWeak) |
3885 (1 << IC_InitWeak) |
3886 (1 << IC_CopyWeak) |
3887 (1 << IC_MoveWeak) |
3888 (1 << IC_DestroyWeak)))
3889 OptimizeWeakCalls(F);
3890
3891 // Optimizations for retain+release pairs.
3892 if (UsedInThisFunction & ((1 << IC_Retain) |
3893 (1 << IC_RetainRV) |
3894 (1 << IC_RetainBlock)))
3895 if (UsedInThisFunction & (1 << IC_Release))
3896 // Run OptimizeSequences until it either stops making changes or
3897 // no retain+release pair nesting is detected.
3898 while (OptimizeSequences(F)) {}
3899
3900 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003901 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3902 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003903 OptimizeReturns(F);
3904
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003905 DEBUG(dbgs() << "\n");
3906
John McCall9fbd3182011-06-15 23:37:01 +00003907 return Changed;
3908}
3909
3910void ObjCARCOpt::releaseMemory() {
3911 PA.clear();
3912}
3913
3914//===----------------------------------------------------------------------===//
3915// ARC contraction.
3916//===----------------------------------------------------------------------===//
3917
3918// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3919// dominated by single calls.
3920
John McCall9fbd3182011-06-15 23:37:01 +00003921#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003922#include "llvm/IR/InlineAsm.h"
3923#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003924
3925STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3926
3927namespace {
3928 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3929 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3930 class ObjCARCContract : public FunctionPass {
3931 bool Changed;
3932 AliasAnalysis *AA;
3933 DominatorTree *DT;
3934 ProvenanceAnalysis PA;
3935
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003936 /// Run - A flag indicating whether this optimization pass should run.
3937 bool Run;
3938
John McCall9fbd3182011-06-15 23:37:01 +00003939 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3940 /// functions, for use in creating calls to them. These are initialized
3941 /// lazily to avoid cluttering up the Module with unused declarations.
3942 Constant *StoreStrongCallee,
3943 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3944
3945 /// RetainRVMarker - The inline asm string to insert between calls and
3946 /// RetainRV calls to make the optimization work on targets which need it.
3947 const MDString *RetainRVMarker;
3948
Dan Gohman0cdece42012-01-19 19:14:36 +00003949 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3950 /// at the end of walking the function we have found no alloca
3951 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003952 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003953
John McCall9fbd3182011-06-15 23:37:01 +00003954 Constant *getStoreStrongCallee(Module *M);
3955 Constant *getRetainAutoreleaseCallee(Module *M);
3956 Constant *getRetainAutoreleaseRVCallee(Module *M);
3957
3958 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3959 InstructionClass Class,
3960 SmallPtrSet<Instruction *, 4>
3961 &DependingInstructions,
3962 SmallPtrSet<const BasicBlock *, 4>
3963 &Visited);
3964
3965 void ContractRelease(Instruction *Release,
3966 inst_iterator &Iter);
3967
3968 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3969 virtual bool doInitialization(Module &M);
3970 virtual bool runOnFunction(Function &F);
3971
3972 public:
3973 static char ID;
3974 ObjCARCContract() : FunctionPass(ID) {
3975 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3976 }
3977 };
3978}
3979
3980char ObjCARCContract::ID = 0;
3981INITIALIZE_PASS_BEGIN(ObjCARCContract,
3982 "objc-arc-contract", "ObjC ARC contraction", false, false)
3983INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3984INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3985INITIALIZE_PASS_END(ObjCARCContract,
3986 "objc-arc-contract", "ObjC ARC contraction", false, false)
3987
3988Pass *llvm::createObjCARCContractPass() {
3989 return new ObjCARCContract();
3990}
3991
3992void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3993 AU.addRequired<AliasAnalysis>();
3994 AU.addRequired<DominatorTree>();
3995 AU.setPreservesCFG();
3996}
3997
3998Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3999 if (!StoreStrongCallee) {
4000 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004001 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4002 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004003 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004004
Bill Wendling034b94b2012-12-19 07:18:57 +00004005 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004006 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004007 Attribute::get(C, Attribute::NoUnwind))
4008 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004009
4010 StoreStrongCallee =
4011 M->getOrInsertFunction(
4012 "objc_storeStrong",
4013 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004014 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004015 }
4016 return StoreStrongCallee;
4017}
4018
4019Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4020 if (!RetainAutoreleaseCallee) {
4021 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004022 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004023 Type *Params[] = { I8X };
4024 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004025 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004026 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004027 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004028 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004029 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004030 }
4031 return RetainAutoreleaseCallee;
4032}
4033
4034Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4035 if (!RetainAutoreleaseRVCallee) {
4036 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004037 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004038 Type *Params[] = { I8X };
4039 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004040 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004041 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004042 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004043 RetainAutoreleaseRVCallee =
4044 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004045 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004046 }
4047 return RetainAutoreleaseRVCallee;
4048}
4049
Dan Gohman447989c2012-04-27 18:56:31 +00004050/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004051bool
4052ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4053 InstructionClass Class,
4054 SmallPtrSet<Instruction *, 4>
4055 &DependingInstructions,
4056 SmallPtrSet<const BasicBlock *, 4>
4057 &Visited) {
4058 const Value *Arg = GetObjCArg(Autorelease);
4059
4060 // Check that there are no instructions between the retain and the autorelease
4061 // (such as an autorelease_pop) which may change the count.
4062 CallInst *Retain = 0;
4063 if (Class == IC_AutoreleaseRV)
4064 FindDependencies(RetainAutoreleaseRVDep, Arg,
4065 Autorelease->getParent(), Autorelease,
4066 DependingInstructions, Visited, PA);
4067 else
4068 FindDependencies(RetainAutoreleaseDep, Arg,
4069 Autorelease->getParent(), Autorelease,
4070 DependingInstructions, Visited, PA);
4071
4072 Visited.clear();
4073 if (DependingInstructions.size() != 1) {
4074 DependingInstructions.clear();
4075 return false;
4076 }
4077
4078 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4079 DependingInstructions.clear();
4080
4081 if (!Retain ||
4082 GetBasicInstructionClass(Retain) != IC_Retain ||
4083 GetObjCArg(Retain) != Arg)
4084 return false;
4085
4086 Changed = true;
4087 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004088
Michael Gottesman916d52a2013-01-07 00:31:26 +00004089 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4090 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4091 " Old Retain: "
4092 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004093
John McCall9fbd3182011-06-15 23:37:01 +00004094 if (Class == IC_AutoreleaseRV)
4095 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4096 else
4097 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004098
Michael Gottesman916d52a2013-01-07 00:31:26 +00004099 DEBUG(dbgs() << " New Retain: "
4100 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004101
John McCall9fbd3182011-06-15 23:37:01 +00004102 EraseInstruction(Autorelease);
4103 return true;
4104}
4105
4106/// ContractRelease - Attempt to merge an objc_release with a store, load, and
4107/// objc_retain to form an objc_storeStrong. This can be a little tricky because
4108/// the instructions don't always appear in order, and there may be unrelated
4109/// intervening instructions.
4110void ObjCARCContract::ContractRelease(Instruction *Release,
4111 inst_iterator &Iter) {
4112 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004113 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004114
4115 // For now, require everything to be in one basic block.
4116 BasicBlock *BB = Release->getParent();
4117 if (Load->getParent() != BB) return;
4118
Dan Gohman4670dac2012-05-08 23:34:08 +00004119 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004120 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004121 ++I;
4122 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004123 StoreInst *Store = 0;
4124 bool SawRelease = false;
4125 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004126 if (I == End)
4127 return;
4128
Dan Gohman4670dac2012-05-08 23:34:08 +00004129 Instruction *Inst = I;
4130 if (Inst == Release) {
4131 SawRelease = true;
4132 continue;
4133 }
4134
4135 InstructionClass Class = GetBasicInstructionClass(Inst);
4136
4137 // Unrelated retains are harmless.
4138 if (IsRetain(Class))
4139 continue;
4140
4141 if (Store) {
4142 // The store is the point where we're going to put the objc_storeStrong,
4143 // so make sure there are no uses after it.
4144 if (CanUse(Inst, Load, PA, Class))
4145 return;
4146 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4147 // We are moving the load down to the store, so check for anything
4148 // else which writes to the memory between the load and the store.
4149 Store = dyn_cast<StoreInst>(Inst);
4150 if (!Store || !Store->isSimple()) return;
4151 if (Store->getPointerOperand() != Loc.Ptr) return;
4152 }
4153 }
John McCall9fbd3182011-06-15 23:37:01 +00004154
4155 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4156
4157 // Walk up to find the retain.
4158 I = Store;
4159 BasicBlock::iterator Begin = BB->begin();
4160 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4161 --I;
4162 Instruction *Retain = I;
4163 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4164 if (GetObjCArg(Retain) != New) return;
4165
4166 Changed = true;
4167 ++NumStoreStrongs;
4168
4169 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004170 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4171 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004172
4173 Value *Args[] = { Load->getPointerOperand(), New };
4174 if (Args[0]->getType() != I8XX)
4175 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4176 if (Args[1]->getType() != I8X)
4177 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4178 CallInst *StoreStrong =
4179 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004180 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004181 StoreStrong->setDoesNotThrow();
4182 StoreStrong->setDebugLoc(Store->getDebugLoc());
4183
Dan Gohman0cdece42012-01-19 19:14:36 +00004184 // We can't set the tail flag yet, because we haven't yet determined
4185 // whether there are any escaping allocas. Remember this call, so that
4186 // we can set the tail flag once we know it's safe.
4187 StoreStrongCalls.insert(StoreStrong);
4188
John McCall9fbd3182011-06-15 23:37:01 +00004189 if (&*Iter == Store) ++Iter;
4190 Store->eraseFromParent();
4191 Release->eraseFromParent();
4192 EraseInstruction(Retain);
4193 if (Load->use_empty())
4194 Load->eraseFromParent();
4195}
4196
4197bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004198 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004199 Run = ModuleHasARC(M);
4200 if (!Run)
4201 return false;
4202
John McCall9fbd3182011-06-15 23:37:01 +00004203 // These are initialized lazily.
4204 StoreStrongCallee = 0;
4205 RetainAutoreleaseCallee = 0;
4206 RetainAutoreleaseRVCallee = 0;
4207
4208 // Initialize RetainRVMarker.
4209 RetainRVMarker = 0;
4210 if (NamedMDNode *NMD =
4211 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4212 if (NMD->getNumOperands() == 1) {
4213 const MDNode *N = NMD->getOperand(0);
4214 if (N->getNumOperands() == 1)
4215 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4216 RetainRVMarker = S;
4217 }
4218
4219 return false;
4220}
4221
4222bool ObjCARCContract::runOnFunction(Function &F) {
4223 if (!EnableARCOpts)
4224 return false;
4225
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004226 // If nothing in the Module uses ARC, don't do anything.
4227 if (!Run)
4228 return false;
4229
John McCall9fbd3182011-06-15 23:37:01 +00004230 Changed = false;
4231 AA = &getAnalysis<AliasAnalysis>();
4232 DT = &getAnalysis<DominatorTree>();
4233
4234 PA.setAA(&getAnalysis<AliasAnalysis>());
4235
Dan Gohman0cdece42012-01-19 19:14:36 +00004236 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4237 // keyword. Be conservative if the function has variadic arguments.
4238 // It seems that functions which "return twice" are also unsafe for the
4239 // "tail" argument, because they are setjmp, which could need to
4240 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004241 bool TailOkForStoreStrongs = !F.isVarArg() &&
4242 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004243
John McCall9fbd3182011-06-15 23:37:01 +00004244 // For ObjC library calls which return their argument, replace uses of the
4245 // argument with uses of the call return value, if it dominates the use. This
4246 // reduces register pressure.
4247 SmallPtrSet<Instruction *, 4> DependingInstructions;
4248 SmallPtrSet<const BasicBlock *, 4> Visited;
4249 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4250 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004251
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004252 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004253
John McCall9fbd3182011-06-15 23:37:01 +00004254 // Only these library routines return their argument. In particular,
4255 // objc_retainBlock does not necessarily return its argument.
4256 InstructionClass Class = GetBasicInstructionClass(Inst);
4257 switch (Class) {
4258 case IC_Retain:
4259 case IC_FusedRetainAutorelease:
4260 case IC_FusedRetainAutoreleaseRV:
4261 break;
4262 case IC_Autorelease:
4263 case IC_AutoreleaseRV:
4264 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4265 continue;
4266 break;
4267 case IC_RetainRV: {
4268 // If we're compiling for a target which needs a special inline-asm
4269 // marker to do the retainAutoreleasedReturnValue optimization,
4270 // insert it now.
4271 if (!RetainRVMarker)
4272 break;
4273 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004274 BasicBlock *InstParent = Inst->getParent();
4275
4276 // Step up to see if the call immediately precedes the RetainRV call.
4277 // If it's an invoke, we have to cross a block boundary. And we have
4278 // to carefully dodge no-op instructions.
4279 do {
4280 if (&*BBI == InstParent->begin()) {
4281 BasicBlock *Pred = InstParent->getSinglePredecessor();
4282 if (!Pred)
4283 goto decline_rv_optimization;
4284 BBI = Pred->getTerminator();
4285 break;
4286 }
4287 --BBI;
4288 } while (isNoopInstruction(BBI));
4289
John McCall9fbd3182011-06-15 23:37:01 +00004290 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004291 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004292 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004293 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004294 InlineAsm *IA =
4295 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4296 /*isVarArg=*/false),
4297 RetainRVMarker->getString(),
4298 /*Constraints=*/"", /*hasSideEffects=*/true);
4299 CallInst::Create(IA, "", Inst);
4300 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004301 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004302 break;
4303 }
4304 case IC_InitWeak: {
4305 // objc_initWeak(p, null) => *p = null
4306 CallInst *CI = cast<CallInst>(Inst);
4307 if (isNullOrUndef(CI->getArgOperand(1))) {
4308 Value *Null =
4309 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4310 Changed = true;
4311 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004312
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004313 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4314 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004315
John McCall9fbd3182011-06-15 23:37:01 +00004316 CI->replaceAllUsesWith(Null);
4317 CI->eraseFromParent();
4318 }
4319 continue;
4320 }
4321 case IC_Release:
4322 ContractRelease(Inst, I);
4323 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004324 case IC_User:
4325 // Be conservative if the function has any alloca instructions.
4326 // Technically we only care about escaping alloca instructions,
4327 // but this is sufficient to handle some interesting cases.
4328 if (isa<AllocaInst>(Inst))
4329 TailOkForStoreStrongs = false;
4330 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004331 default:
4332 continue;
4333 }
4334
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004335 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004336
John McCall9fbd3182011-06-15 23:37:01 +00004337 // Don't use GetObjCArg because we don't want to look through bitcasts
4338 // and such; to do the replacement, the argument must have type i8*.
4339 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4340 for (;;) {
4341 // If we're compiling bugpointed code, don't get in trouble.
4342 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4343 break;
4344 // Look through the uses of the pointer.
4345 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4346 UI != UE; ) {
4347 Use &U = UI.getUse();
4348 unsigned OperandNo = UI.getOperandNo();
4349 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004350
4351 // If the call's return value dominates a use of the call's argument
4352 // value, rewrite the use to use the return value. We check for
4353 // reachability here because an unreachable call is considered to
4354 // trivially dominate itself, which would lead us to rewriting its
4355 // argument in terms of its return value, which would lead to
4356 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004357 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004358 Changed = true;
4359 Instruction *Replacement = Inst;
4360 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004361 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004362 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004363 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4364 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004365 if (Replacement->getType() != UseTy)
4366 Replacement = new BitCastInst(Replacement, UseTy, "",
4367 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004368 // While we're here, rewrite all edges for this PHI, rather
4369 // than just one use at a time, to minimize the number of
4370 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004371 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004372 if (PHI->getIncomingBlock(i) == BB) {
4373 // Keep the UI iterator valid.
4374 if (&PHI->getOperandUse(
4375 PHINode::getOperandNumForIncomingValue(i)) ==
4376 &UI.getUse())
4377 ++UI;
4378 PHI->setIncomingValue(i, Replacement);
4379 }
4380 } else {
4381 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004382 Replacement = new BitCastInst(Replacement, UseTy, "",
4383 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004384 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004385 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004386 }
John McCall9fbd3182011-06-15 23:37:01 +00004387 }
4388
Dan Gohman447989c2012-04-27 18:56:31 +00004389 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004390 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4391 Arg = BI->getOperand(0);
4392 else if (isa<GEPOperator>(Arg) &&
4393 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4394 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4395 else if (isa<GlobalAlias>(Arg) &&
4396 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4397 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4398 else
4399 break;
4400 }
4401 }
4402
Dan Gohman0cdece42012-01-19 19:14:36 +00004403 // If this function has no escaping allocas or suspicious vararg usage,
4404 // objc_storeStrong calls can be marked with the "tail" keyword.
4405 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004406 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004407 E = StoreStrongCalls.end(); I != E; ++I)
4408 (*I)->setTailCall();
4409 StoreStrongCalls.clear();
4410
John McCall9fbd3182011-06-15 23:37:01 +00004411 return Changed;
4412}