blob: dce8e8beb6b8f0d10a2fcc48917c695fb34e4d8d [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/Support/CommandLine.h"
John McCall9fbd3182011-06-15 23:37:01 +000033#include "llvm/ADT/DenseMap.h"
John McCall9fbd3182011-06-15 23:37:01 +000034using namespace llvm;
35
36// A handy option to enable/disable all optimizations in this file.
37static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
38
39//===----------------------------------------------------------------------===//
40// Misc. Utilities
41//===----------------------------------------------------------------------===//
42
43namespace {
44 /// MapVector - An associative container with fast insertion-order
45 /// (deterministic) iteration over its elements. Plus the special
46 /// blot operation.
47 template<class KeyT, class ValueT>
48 class MapVector {
49 /// Map - Map keys to indices in Vector.
50 typedef DenseMap<KeyT, size_t> MapTy;
51 MapTy Map;
52
53 /// Vector - Keys and values.
54 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
55 VectorTy Vector;
56
57 public:
58 typedef typename VectorTy::iterator iterator;
59 typedef typename VectorTy::const_iterator const_iterator;
60 iterator begin() { return Vector.begin(); }
61 iterator end() { return Vector.end(); }
62 const_iterator begin() const { return Vector.begin(); }
63 const_iterator end() const { return Vector.end(); }
64
65#ifdef XDEBUG
66 ~MapVector() {
67 assert(Vector.size() >= Map.size()); // May differ due to blotting.
68 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
69 I != E; ++I) {
70 assert(I->second < Vector.size());
71 assert(Vector[I->second].first == I->first);
72 }
73 for (typename VectorTy::const_iterator I = Vector.begin(),
74 E = Vector.end(); I != E; ++I)
75 assert(!I->first ||
76 (Map.count(I->first) &&
77 Map[I->first] == size_t(I - Vector.begin())));
78 }
79#endif
80
Dan Gohman22cc4cc2012-03-02 01:13:53 +000081 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000082 std::pair<typename MapTy::iterator, bool> Pair =
83 Map.insert(std::make_pair(Arg, size_t(0)));
84 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000085 size_t Num = Vector.size();
86 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000087 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000088 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000089 }
90 return Vector[Pair.first->second].second;
91 }
92
93 std::pair<iterator, bool>
94 insert(const std::pair<KeyT, ValueT> &InsertPair) {
95 std::pair<typename MapTy::iterator, bool> Pair =
96 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
97 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000098 size_t Num = Vector.size();
99 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000100 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000101 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000102 }
103 return std::make_pair(Vector.begin() + Pair.first->second, false);
104 }
105
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000106 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000107 typename MapTy::const_iterator It = Map.find(Key);
108 if (It == Map.end()) return Vector.end();
109 return Vector.begin() + It->second;
110 }
111
112 /// blot - This is similar to erase, but instead of removing the element
113 /// from the vector, it just zeros out the key in the vector. This leaves
114 /// iterators intact, but clients must be prepared for zeroed-out keys when
115 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000116 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000117 typename MapTy::iterator It = Map.find(Key);
118 if (It == Map.end()) return;
119 Vector[It->second].first = KeyT();
120 Map.erase(It);
121 }
122
123 void clear() {
124 Map.clear();
125 Vector.clear();
126 }
127 };
128}
129
130//===----------------------------------------------------------------------===//
131// ARC Utilities.
132//===----------------------------------------------------------------------===//
133
Dan Gohman0daef3d2012-05-08 23:39:44 +0000134#include "llvm/Intrinsics.h"
135#include "llvm/Module.h"
136#include "llvm/Analysis/ValueTracking.h"
137#include "llvm/Transforms/Utils/Local.h"
138#include "llvm/Support/CallSite.h"
139#include "llvm/ADT/StringSwitch.h"
140
John McCall9fbd3182011-06-15 23:37:01 +0000141namespace {
142 /// InstructionClass - A simple classification for instructions.
143 enum InstructionClass {
144 IC_Retain, ///< objc_retain
145 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
146 IC_RetainBlock, ///< objc_retainBlock
147 IC_Release, ///< objc_release
148 IC_Autorelease, ///< objc_autorelease
149 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
150 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
151 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
152 IC_NoopCast, ///< objc_retainedObject, etc.
153 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
154 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
155 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
156 IC_StoreWeak, ///< objc_storeWeak (primitive)
157 IC_InitWeak, ///< objc_initWeak (derived)
158 IC_LoadWeak, ///< objc_loadWeak (derived)
159 IC_MoveWeak, ///< objc_moveWeak (derived)
160 IC_CopyWeak, ///< objc_copyWeak (derived)
161 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000162 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
164 IC_Call, ///< could call objc_release
165 IC_User, ///< could "use" a pointer
166 IC_None ///< anything else
167 };
168}
169
170/// IsPotentialUse - Test whether the given value is possible a
171/// reference-counted pointer.
172static bool IsPotentialUse(const Value *Op) {
173 // Pointers to static or stack storage are not reference-counted pointers.
174 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
175 return false;
176 // Special arguments are not reference-counted.
177 if (const Argument *Arg = dyn_cast<Argument>(Op))
178 if (Arg->hasByValAttr() ||
179 Arg->hasNestAttr() ||
180 Arg->hasStructRetAttr())
181 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000182 // Only consider values with pointer types.
183 // It seemes intuitive to exclude function pointer types as well, since
184 // functions are never reference-counted, however clang occasionally
185 // bitcasts reference-counted pointers to function-pointer type
186 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000187 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000188 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000189 return false;
190 // Conservatively assume anything else is a potential use.
191 return true;
192}
193
194/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
195/// of construct CS is.
196static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
197 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
198 I != E; ++I)
199 if (IsPotentialUse(*I))
200 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
201
202 return CS.onlyReadsMemory() ? IC_None : IC_Call;
203}
204
205/// GetFunctionClass - Determine if F is one of the special known Functions.
206/// If it isn't, return IC_CallOrUser.
207static InstructionClass GetFunctionClass(const Function *F) {
208 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
209
210 // No arguments.
211 if (AI == AE)
212 return StringSwitch<InstructionClass>(F->getName())
213 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
214 .Default(IC_CallOrUser);
215
216 // One argument.
217 const Argument *A0 = AI++;
218 if (AI == AE)
219 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000220 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
221 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000222 // Argument is i8*.
223 if (ETy->isIntegerTy(8))
224 return StringSwitch<InstructionClass>(F->getName())
225 .Case("objc_retain", IC_Retain)
226 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
227 .Case("objc_retainBlock", IC_RetainBlock)
228 .Case("objc_release", IC_Release)
229 .Case("objc_autorelease", IC_Autorelease)
230 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
231 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
232 .Case("objc_retainedObject", IC_NoopCast)
233 .Case("objc_unretainedObject", IC_NoopCast)
234 .Case("objc_unretainedPointer", IC_NoopCast)
235 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
236 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
238 .Default(IC_CallOrUser);
239
240 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000241 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000242 if (Pte->getElementType()->isIntegerTy(8))
243 return StringSwitch<InstructionClass>(F->getName())
244 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
245 .Case("objc_loadWeak", IC_LoadWeak)
246 .Case("objc_destroyWeak", IC_DestroyWeak)
247 .Default(IC_CallOrUser);
248 }
249
250 // Two arguments, first is i8**.
251 const Argument *A1 = AI++;
252 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000253 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
254 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000255 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000256 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
257 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000258 // Second argument is i8*
259 if (ETy1->isIntegerTy(8))
260 return StringSwitch<InstructionClass>(F->getName())
261 .Case("objc_storeWeak", IC_StoreWeak)
262 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000263 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000264 .Default(IC_CallOrUser);
265 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000266 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000267 if (Pte1->getElementType()->isIntegerTy(8))
268 return StringSwitch<InstructionClass>(F->getName())
269 .Case("objc_moveWeak", IC_MoveWeak)
270 .Case("objc_copyWeak", IC_CopyWeak)
271 .Default(IC_CallOrUser);
272 }
273
274 // Anything else.
275 return IC_CallOrUser;
276}
277
278/// GetInstructionClass - Determine what kind of construct V is.
279static InstructionClass GetInstructionClass(const Value *V) {
280 if (const Instruction *I = dyn_cast<Instruction>(V)) {
281 // Any instruction other than bitcast and gep with a pointer operand have a
282 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
283 // to a subsequent use, rather than using it themselves, in this sense.
284 // As a short cut, several other opcodes are known to have no pointer
285 // operands of interest. And ret is never followed by a release, so it's
286 // not interesting to examine.
287 switch (I->getOpcode()) {
288 case Instruction::Call: {
289 const CallInst *CI = cast<CallInst>(I);
290 // Check for calls to special functions.
291 if (const Function *F = CI->getCalledFunction()) {
292 InstructionClass Class = GetFunctionClass(F);
293 if (Class != IC_CallOrUser)
294 return Class;
295
296 // None of the intrinsic functions do objc_release. For intrinsics, the
297 // only question is whether or not they may be users.
298 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000299 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
300 case Intrinsic::stacksave: case Intrinsic::stackrestore:
301 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000302 case Intrinsic::objectsize: case Intrinsic::prefetch:
303 case Intrinsic::stackprotector:
304 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
305 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
306 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
307 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
308 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
309 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000310 // Don't let dbg info affect our results.
311 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
312 // Short cut: Some intrinsics obviously don't use ObjC pointers.
313 return IC_None;
314 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000315 break;
John McCall9fbd3182011-06-15 23:37:01 +0000316 }
317 }
318 return GetCallSiteClass(CI);
319 }
320 case Instruction::Invoke:
321 return GetCallSiteClass(cast<InvokeInst>(I));
322 case Instruction::BitCast:
323 case Instruction::GetElementPtr:
324 case Instruction::Select: case Instruction::PHI:
325 case Instruction::Ret: case Instruction::Br:
326 case Instruction::Switch: case Instruction::IndirectBr:
327 case Instruction::Alloca: case Instruction::VAArg:
328 case Instruction::Add: case Instruction::FAdd:
329 case Instruction::Sub: case Instruction::FSub:
330 case Instruction::Mul: case Instruction::FMul:
331 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
332 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
333 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
334 case Instruction::And: case Instruction::Or: case Instruction::Xor:
335 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
336 case Instruction::IntToPtr: case Instruction::FCmp:
337 case Instruction::FPTrunc: case Instruction::FPExt:
338 case Instruction::FPToUI: case Instruction::FPToSI:
339 case Instruction::UIToFP: case Instruction::SIToFP:
340 case Instruction::InsertElement: case Instruction::ExtractElement:
341 case Instruction::ShuffleVector:
342 case Instruction::ExtractValue:
343 break;
344 case Instruction::ICmp:
345 // Comparing a pointer with null, or any other constant, isn't an
346 // interesting use, because we don't care what the pointer points to, or
347 // about the values of any other dynamic reference-counted pointers.
348 if (IsPotentialUse(I->getOperand(1)))
349 return IC_User;
350 break;
351 default:
352 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000353 // Note that this includes both operands of a Store: while the first
354 // operand isn't actually being dereferenced, it is being stored to
355 // memory where we can no longer track who might read it and dereference
356 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000357 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
358 OI != OE; ++OI)
359 if (IsPotentialUse(*OI))
360 return IC_User;
361 }
362 }
363
364 // Otherwise, it's totally inert for ARC purposes.
365 return IC_None;
366}
367
368/// GetBasicInstructionClass - Determine what kind of construct V is. This is
369/// similar to GetInstructionClass except that it only detects objc runtine
370/// calls. This allows it to be faster.
371static InstructionClass GetBasicInstructionClass(const Value *V) {
372 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
373 if (const Function *F = CI->getCalledFunction())
374 return GetFunctionClass(F);
375 // Otherwise, be conservative.
376 return IC_CallOrUser;
377 }
378
379 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000380 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000381}
382
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000383/// IsRetain - Test if the given class is objc_retain or
John McCall9fbd3182011-06-15 23:37:01 +0000384/// equivalent.
385static bool IsRetain(InstructionClass Class) {
386 return Class == IC_Retain ||
387 Class == IC_RetainRV;
388}
389
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000390/// IsAutorelease - Test if the given class is objc_autorelease or
John McCall9fbd3182011-06-15 23:37:01 +0000391/// equivalent.
392static bool IsAutorelease(InstructionClass Class) {
393 return Class == IC_Autorelease ||
394 Class == IC_AutoreleaseRV;
395}
396
397/// IsForwarding - Test if the given class represents instructions which return
398/// their argument verbatim.
399static bool IsForwarding(InstructionClass Class) {
400 // objc_retainBlock technically doesn't always return its argument
401 // verbatim, but it doesn't matter for our purposes here.
402 return Class == IC_Retain ||
403 Class == IC_RetainRV ||
404 Class == IC_Autorelease ||
405 Class == IC_AutoreleaseRV ||
406 Class == IC_RetainBlock ||
407 Class == IC_NoopCast;
408}
409
410/// IsNoopOnNull - Test if the given class represents instructions which do
411/// nothing if passed a null pointer.
412static bool IsNoopOnNull(InstructionClass Class) {
413 return Class == IC_Retain ||
414 Class == IC_RetainRV ||
415 Class == IC_Release ||
416 Class == IC_Autorelease ||
417 Class == IC_AutoreleaseRV ||
418 Class == IC_RetainBlock;
419}
420
421/// IsAlwaysTail - Test if the given class represents instructions which are
422/// always safe to mark with the "tail" keyword.
423static bool IsAlwaysTail(InstructionClass Class) {
424 // IC_RetainBlock may be given a stack argument.
425 return Class == IC_Retain ||
426 Class == IC_RetainRV ||
427 Class == IC_Autorelease ||
428 Class == IC_AutoreleaseRV;
429}
430
431/// IsNoThrow - Test if the given class represents instructions which are always
432/// safe to mark with the nounwind attribute..
433static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000434 // objc_retainBlock is not nounwind because it calls user copy constructors
435 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000436 return Class == IC_Retain ||
437 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000438 Class == IC_Release ||
439 Class == IC_Autorelease ||
440 Class == IC_AutoreleaseRV ||
441 Class == IC_AutoreleasepoolPush ||
442 Class == IC_AutoreleasepoolPop;
443}
444
Dan Gohman447989c2012-04-27 18:56:31 +0000445/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000446/// argument verbatim, so if it's such a call and the return value has users,
447/// replace them with the argument value.
448static void EraseInstruction(Instruction *CI) {
449 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
450
451 bool Unused = CI->use_empty();
452
453 if (!Unused) {
454 // Replace the return value with the argument.
455 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
456 "Can't delete non-forwarding instruction with users!");
457 CI->replaceAllUsesWith(OldArg);
458 }
459
460 CI->eraseFromParent();
461
462 if (Unused)
463 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
464}
465
466/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
467/// also knows how to look through objc_retain and objc_autorelease calls, which
468/// we know to return their argument verbatim.
469static const Value *GetUnderlyingObjCPtr(const Value *V) {
470 for (;;) {
471 V = GetUnderlyingObject(V);
472 if (!IsForwarding(GetBasicInstructionClass(V)))
473 break;
474 V = cast<CallInst>(V)->getArgOperand(0);
475 }
476
477 return V;
478}
479
480/// StripPointerCastsAndObjCCalls - This is a wrapper around
481/// Value::stripPointerCasts which also knows how to look through objc_retain
482/// and objc_autorelease calls, which we know to return their argument verbatim.
483static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
484 for (;;) {
485 V = V->stripPointerCasts();
486 if (!IsForwarding(GetBasicInstructionClass(V)))
487 break;
488 V = cast<CallInst>(V)->getArgOperand(0);
489 }
490 return V;
491}
492
493/// StripPointerCastsAndObjCCalls - This is a wrapper around
494/// Value::stripPointerCasts which also knows how to look through objc_retain
495/// and objc_autorelease calls, which we know to return their argument verbatim.
496static Value *StripPointerCastsAndObjCCalls(Value *V) {
497 for (;;) {
498 V = V->stripPointerCasts();
499 if (!IsForwarding(GetBasicInstructionClass(V)))
500 break;
501 V = cast<CallInst>(V)->getArgOperand(0);
502 }
503 return V;
504}
505
506/// GetObjCArg - Assuming the given instruction is one of the special calls such
507/// as objc_retain or objc_release, return the argument value, stripped of no-op
508/// casts and forwarding calls.
509static Value *GetObjCArg(Value *Inst) {
510 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
511}
512
513/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
514/// isObjCIdentifiedObject, except that it uses special knowledge of
515/// ObjC conventions...
516static bool IsObjCIdentifiedObject(const Value *V) {
517 // Assume that call results and arguments have their own "provenance".
518 // Constants (including GlobalVariables) and Allocas are never
519 // reference-counted.
520 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
521 isa<Argument>(V) || isa<Constant>(V) ||
522 isa<AllocaInst>(V))
523 return true;
524
525 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
526 const Value *Pointer =
527 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
528 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000529 // A constant pointer can't be pointing to an object on the heap. It may
530 // be reference-counted, but it won't be deleted.
531 if (GV->isConstant())
532 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000533 StringRef Name = GV->getName();
534 // These special variables are known to hold values which are not
535 // reference-counted pointers.
536 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
537 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
538 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
539 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
540 Name.startswith("\01l_objc_msgSend_fixup_"))
541 return true;
542 }
543 }
544
545 return false;
546}
547
548/// FindSingleUseIdentifiedObject - This is similar to
549/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
550/// with multiple uses.
551static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
552 if (Arg->hasOneUse()) {
553 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
554 return FindSingleUseIdentifiedObject(BC->getOperand(0));
555 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
556 if (GEP->hasAllZeroIndices())
557 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
558 if (IsForwarding(GetBasicInstructionClass(Arg)))
559 return FindSingleUseIdentifiedObject(
560 cast<CallInst>(Arg)->getArgOperand(0));
561 if (!IsObjCIdentifiedObject(Arg))
562 return 0;
563 return Arg;
564 }
565
Dan Gohman0daef3d2012-05-08 23:39:44 +0000566 // If we found an identifiable object but it has multiple uses, but they are
567 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000568 if (IsObjCIdentifiedObject(Arg)) {
569 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
570 UI != UE; ++UI) {
571 const User *U = *UI;
572 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
573 return 0;
574 }
575
576 return Arg;
577 }
578
579 return 0;
580}
581
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000582/// ModuleHasARC - Test if the given module looks interesting to run ARC
583/// optimization on.
584static bool ModuleHasARC(const Module &M) {
585 return
586 M.getNamedValue("objc_retain") ||
587 M.getNamedValue("objc_release") ||
588 M.getNamedValue("objc_autorelease") ||
589 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
590 M.getNamedValue("objc_retainBlock") ||
591 M.getNamedValue("objc_autoreleaseReturnValue") ||
592 M.getNamedValue("objc_autoreleasePoolPush") ||
593 M.getNamedValue("objc_loadWeakRetained") ||
594 M.getNamedValue("objc_loadWeak") ||
595 M.getNamedValue("objc_destroyWeak") ||
596 M.getNamedValue("objc_storeWeak") ||
597 M.getNamedValue("objc_initWeak") ||
598 M.getNamedValue("objc_moveWeak") ||
599 M.getNamedValue("objc_copyWeak") ||
600 M.getNamedValue("objc_retainedObject") ||
601 M.getNamedValue("objc_unretainedObject") ||
602 M.getNamedValue("objc_unretainedPointer");
603}
604
Dan Gohman79522dc2012-01-13 00:39:07 +0000605/// DoesObjCBlockEscape - Test whether the given pointer, which is an
606/// Objective C block pointer, does not "escape". This differs from regular
607/// escape analysis in that a use as an argument to a call is not considered
608/// an escape.
609static bool DoesObjCBlockEscape(const Value *BlockPtr) {
610 // Walk the def-use chains.
611 SmallVector<const Value *, 4> Worklist;
612 Worklist.push_back(BlockPtr);
613 do {
614 const Value *V = Worklist.pop_back_val();
615 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
616 UI != UE; ++UI) {
617 const User *UUser = *UI;
618 // Special - Use by a call (callee or argument) is not considered
619 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000620 switch (GetBasicInstructionClass(UUser)) {
621 case IC_StoreWeak:
622 case IC_InitWeak:
623 case IC_StoreStrong:
624 case IC_Autorelease:
625 case IC_AutoreleaseRV:
626 // These special functions make copies of their pointer arguments.
627 return true;
628 case IC_User:
629 case IC_None:
630 // Use by an instruction which copies the value is an escape if the
631 // result is an escape.
632 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
633 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
634 Worklist.push_back(UUser);
635 continue;
636 }
637 // Use by a load is not an escape.
638 if (isa<LoadInst>(UUser))
639 continue;
640 // Use by a store is not an escape if the use is the address.
641 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
642 if (V != SI->getValueOperand())
643 continue;
644 break;
645 default:
646 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000647 continue;
648 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000649 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000650 return true;
651 }
652 } while (!Worklist.empty());
653
654 // No escapes found.
655 return false;
656}
657
John McCall9fbd3182011-06-15 23:37:01 +0000658//===----------------------------------------------------------------------===//
659// ARC AliasAnalysis.
660//===----------------------------------------------------------------------===//
661
662#include "llvm/Pass.h"
663#include "llvm/Analysis/AliasAnalysis.h"
664#include "llvm/Analysis/Passes.h"
665
666namespace {
667 /// ObjCARCAliasAnalysis - This is a simple alias analysis
668 /// implementation that uses knowledge of ARC constructs to answer queries.
669 ///
670 /// TODO: This class could be generalized to know about other ObjC-specific
671 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
672 /// even though their offsets are dynamic.
673 class ObjCARCAliasAnalysis : public ImmutablePass,
674 public AliasAnalysis {
675 public:
676 static char ID; // Class identification, replacement for typeinfo
677 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
678 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
679 }
680
681 private:
682 virtual void initializePass() {
683 InitializeAliasAnalysis(this);
684 }
685
686 /// getAdjustedAnalysisPointer - This method is used when a pass implements
687 /// an analysis interface through multiple inheritance. If needed, it
688 /// should override this to adjust the this pointer as needed for the
689 /// specified pass info.
690 virtual void *getAdjustedAnalysisPointer(const void *PI) {
691 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000692 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000693 return this;
694 }
695
696 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
697 virtual AliasResult alias(const Location &LocA, const Location &LocB);
698 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
699 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
700 virtual ModRefBehavior getModRefBehavior(const Function *F);
701 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
702 const Location &Loc);
703 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
704 ImmutableCallSite CS2);
705 };
706} // End of anonymous namespace
707
708// Register this pass...
709char ObjCARCAliasAnalysis::ID = 0;
710INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
711 "ObjC-ARC-Based Alias Analysis", false, true, false)
712
713ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
714 return new ObjCARCAliasAnalysis();
715}
716
717void
718ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
719 AU.setPreservesAll();
720 AliasAnalysis::getAnalysisUsage(AU);
721}
722
723AliasAnalysis::AliasResult
724ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
725 if (!EnableARCOpts)
726 return AliasAnalysis::alias(LocA, LocB);
727
728 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
729 // precise alias query.
730 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
731 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
732 AliasResult Result =
733 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
734 Location(SB, LocB.Size, LocB.TBAATag));
735 if (Result != MayAlias)
736 return Result;
737
738 // If that failed, climb to the underlying object, including climbing through
739 // ObjC-specific no-ops, and try making an imprecise alias query.
740 const Value *UA = GetUnderlyingObjCPtr(SA);
741 const Value *UB = GetUnderlyingObjCPtr(SB);
742 if (UA != SA || UB != SB) {
743 Result = AliasAnalysis::alias(Location(UA), Location(UB));
744 // We can't use MustAlias or PartialAlias results here because
745 // GetUnderlyingObjCPtr may return an offsetted pointer value.
746 if (Result == NoAlias)
747 return NoAlias;
748 }
749
750 // If that failed, fail. We don't need to chain here, since that's covered
751 // by the earlier precise query.
752 return MayAlias;
753}
754
755bool
756ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
757 bool OrLocal) {
758 if (!EnableARCOpts)
759 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
760
761 // First, strip off no-ops, including ObjC-specific no-ops, and try making
762 // a precise alias query.
763 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
764 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
765 OrLocal))
766 return true;
767
768 // If that failed, climb to the underlying object, including climbing through
769 // ObjC-specific no-ops, and try making an imprecise alias query.
770 const Value *U = GetUnderlyingObjCPtr(S);
771 if (U != S)
772 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
773
774 // If that failed, fail. We don't need to chain here, since that's covered
775 // by the earlier precise query.
776 return false;
777}
778
779AliasAnalysis::ModRefBehavior
780ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
781 // We have nothing to do. Just chain to the next AliasAnalysis.
782 return AliasAnalysis::getModRefBehavior(CS);
783}
784
785AliasAnalysis::ModRefBehavior
786ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
787 if (!EnableARCOpts)
788 return AliasAnalysis::getModRefBehavior(F);
789
790 switch (GetFunctionClass(F)) {
791 case IC_NoopCast:
792 return DoesNotAccessMemory;
793 default:
794 break;
795 }
796
797 return AliasAnalysis::getModRefBehavior(F);
798}
799
800AliasAnalysis::ModRefResult
801ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
802 if (!EnableARCOpts)
803 return AliasAnalysis::getModRefInfo(CS, Loc);
804
805 switch (GetBasicInstructionClass(CS.getInstruction())) {
806 case IC_Retain:
807 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000808 case IC_Autorelease:
809 case IC_AutoreleaseRV:
810 case IC_NoopCast:
811 case IC_AutoreleasepoolPush:
812 case IC_FusedRetainAutorelease:
813 case IC_FusedRetainAutoreleaseRV:
814 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000815 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000816 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000817 return NoModRef;
818 default:
819 break;
820 }
821
822 return AliasAnalysis::getModRefInfo(CS, Loc);
823}
824
825AliasAnalysis::ModRefResult
826ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
827 ImmutableCallSite CS2) {
828 // TODO: Theoretically we could check for dependencies between objc_* calls
829 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
830 return AliasAnalysis::getModRefInfo(CS1, CS2);
831}
832
833//===----------------------------------------------------------------------===//
834// ARC expansion.
835//===----------------------------------------------------------------------===//
836
837#include "llvm/Support/InstIterator.h"
838#include "llvm/Transforms/Scalar.h"
839
840namespace {
841 /// ObjCARCExpand - Early ARC transformations.
842 class ObjCARCExpand : public FunctionPass {
843 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000844 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000845 virtual bool runOnFunction(Function &F);
846
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000847 /// Run - A flag indicating whether this optimization pass should run.
848 bool Run;
849
John McCall9fbd3182011-06-15 23:37:01 +0000850 public:
851 static char ID;
852 ObjCARCExpand() : FunctionPass(ID) {
853 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
854 }
855 };
856}
857
858char ObjCARCExpand::ID = 0;
859INITIALIZE_PASS(ObjCARCExpand,
860 "objc-arc-expand", "ObjC ARC expansion", false, false)
861
862Pass *llvm::createObjCARCExpandPass() {
863 return new ObjCARCExpand();
864}
865
866void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
867 AU.setPreservesCFG();
868}
869
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000870bool ObjCARCExpand::doInitialization(Module &M) {
871 Run = ModuleHasARC(M);
872 return false;
873}
874
John McCall9fbd3182011-06-15 23:37:01 +0000875bool ObjCARCExpand::runOnFunction(Function &F) {
876 if (!EnableARCOpts)
877 return false;
878
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000879 // If nothing in the Module uses ARC, don't do anything.
880 if (!Run)
881 return false;
882
John McCall9fbd3182011-06-15 23:37:01 +0000883 bool Changed = false;
884
885 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
886 Instruction *Inst = &*I;
887
888 switch (GetBasicInstructionClass(Inst)) {
889 case IC_Retain:
890 case IC_RetainRV:
891 case IC_Autorelease:
892 case IC_AutoreleaseRV:
893 case IC_FusedRetainAutorelease:
894 case IC_FusedRetainAutoreleaseRV:
895 // These calls return their argument verbatim, as a low-level
896 // optimization. However, this makes high-level optimizations
897 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000898 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000899 Changed = true;
900 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
901 break;
902 default:
903 break;
904 }
905 }
906
907 return Changed;
908}
909
910//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000911// ARC autorelease pool elimination.
912//===----------------------------------------------------------------------===//
913
Dan Gohman1dae3e92012-01-18 21:19:38 +0000914#include "llvm/Constants.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000915#include "llvm/ADT/STLExtras.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000916
Dan Gohman2f6263c2012-01-17 20:52:24 +0000917namespace {
918 /// ObjCARCAPElim - Autorelease pool elimination.
919 class ObjCARCAPElim : public ModulePass {
920 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
921 virtual bool runOnModule(Module &M);
922
Dan Gohman447989c2012-04-27 18:56:31 +0000923 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
924 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000925
926 public:
927 static char ID;
928 ObjCARCAPElim() : ModulePass(ID) {
929 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
930 }
931 };
932}
933
934char ObjCARCAPElim::ID = 0;
935INITIALIZE_PASS(ObjCARCAPElim,
936 "objc-arc-apelim",
937 "ObjC ARC autorelease pool elimination",
938 false, false)
939
940Pass *llvm::createObjCARCAPElimPass() {
941 return new ObjCARCAPElim();
942}
943
944void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
945 AU.setPreservesCFG();
946}
947
948/// MayAutorelease - Interprocedurally determine if calls made by the
949/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000950bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
951 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000952 if (Callee->isDeclaration() || Callee->mayBeOverridden())
953 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000954 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000955 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000956 const BasicBlock *BB = I;
957 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
958 J != F; ++J)
959 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000960 // This recursion depth limit is arbitrary. It's just great
961 // enough to cover known interesting testcases.
962 if (Depth < 3 &&
963 !JCS.onlyReadsMemory() &&
964 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000965 return true;
966 }
967 return false;
968 }
969
970 return true;
971}
972
973bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
974 bool Changed = false;
975
976 Instruction *Push = 0;
977 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
978 Instruction *Inst = I++;
979 switch (GetBasicInstructionClass(Inst)) {
980 case IC_AutoreleasepoolPush:
981 Push = Inst;
982 break;
983 case IC_AutoreleasepoolPop:
984 // If this pop matches a push and nothing in between can autorelease,
985 // zap the pair.
986 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
987 Changed = true;
988 Inst->eraseFromParent();
989 Push->eraseFromParent();
990 }
991 Push = 0;
992 break;
993 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +0000994 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000995 Push = 0;
996 break;
997 default:
998 break;
999 }
1000 }
1001
1002 return Changed;
1003}
1004
1005bool ObjCARCAPElim::runOnModule(Module &M) {
1006 if (!EnableARCOpts)
1007 return false;
1008
1009 // If nothing in the Module uses ARC, don't do anything.
1010 if (!ModuleHasARC(M))
1011 return false;
1012
Dan Gohman1dae3e92012-01-18 21:19:38 +00001013 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001014 // identifying the global constructors. In theory, unnecessary autorelease
1015 // pools could occur anywhere, but in practice it's pretty rare. Global
1016 // ctors are a place where autorelease pools get inserted automatically,
1017 // so it's pretty common for them to be unnecessary, and it's pretty
1018 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001019 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1020 if (!GV)
1021 return false;
1022
1023 assert(GV->hasDefinitiveInitializer() &&
1024 "llvm.global_ctors is uncooperative!");
1025
Dan Gohman2f6263c2012-01-17 20:52:24 +00001026 bool Changed = false;
1027
Dan Gohman1dae3e92012-01-18 21:19:38 +00001028 // Dig the constructor functions out of GV's initializer.
1029 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1030 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1031 OI != OE; ++OI) {
1032 Value *Op = *OI;
1033 // llvm.global_ctors is an array of pairs where the second members
1034 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001035 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1036 // If the user used a constructor function with the wrong signature and
1037 // it got bitcasted or whatever, look the other way.
1038 if (!F)
1039 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001040 // Only look at function definitions.
1041 if (F->isDeclaration())
1042 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001043 // Only look at functions with one basic block.
1044 if (llvm::next(F->begin()) != F->end())
1045 continue;
1046 // Ok, a single-block constructor function definition. Try to optimize it.
1047 Changed |= OptimizeBB(F->begin());
1048 }
1049
1050 return Changed;
1051}
1052
1053//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001054// ARC optimization.
1055//===----------------------------------------------------------------------===//
1056
1057// TODO: On code like this:
1058//
1059// objc_retain(%x)
1060// stuff_that_cannot_release()
1061// objc_autorelease(%x)
1062// stuff_that_cannot_release()
1063// objc_retain(%x)
1064// stuff_that_cannot_release()
1065// objc_autorelease(%x)
1066//
1067// The second retain and autorelease can be deleted.
1068
1069// TODO: It should be possible to delete
1070// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1071// pairs if nothing is actually autoreleased between them. Also, autorelease
1072// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1073// after inlining) can be turned into plain release calls.
1074
1075// TODO: Critical-edge splitting. If the optimial insertion point is
1076// a critical edge, the current algorithm has to fail, because it doesn't
1077// know how to split edges. It should be possible to make the optimizer
1078// think in terms of edges, rather than blocks, and then split critical
1079// edges on demand.
1080
1081// TODO: OptimizeSequences could generalized to be Interprocedural.
1082
1083// TODO: Recognize that a bunch of other objc runtime calls have
1084// non-escaping arguments and non-releasing arguments, and may be
1085// non-autoreleasing.
1086
1087// TODO: Sink autorelease calls as far as possible. Unfortunately we
1088// usually can't sink them past other calls, which would be the main
1089// case where it would be useful.
1090
Dan Gohmane6d5e882011-08-19 00:26:36 +00001091// TODO: The pointer returned from objc_loadWeakRetained is retained.
1092
1093// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001094
John McCall9fbd3182011-06-15 23:37:01 +00001095#include "llvm/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001096#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001097#include "llvm/ADT/Statistic.h"
Dan Gohman59a1c932011-12-12 19:42:25 +00001098#include "llvm/ADT/SmallPtrSet.h"
John McCall9fbd3182011-06-15 23:37:01 +00001099
1100STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1101STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1102STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1103STATISTIC(NumRets, "Number of return value forwarding "
1104 "retain+autoreleaes eliminated");
1105STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1106STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1107
1108namespace {
1109 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1110 /// uses many of the same techniques, except it uses special ObjC-specific
1111 /// reasoning about pointer relationships.
1112 class ProvenanceAnalysis {
1113 AliasAnalysis *AA;
1114
1115 typedef std::pair<const Value *, const Value *> ValuePairTy;
1116 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1117 CachedResultsTy CachedResults;
1118
1119 bool relatedCheck(const Value *A, const Value *B);
1120 bool relatedSelect(const SelectInst *A, const Value *B);
1121 bool relatedPHI(const PHINode *A, const Value *B);
1122
1123 // Do not implement.
1124 void operator=(const ProvenanceAnalysis &);
1125 ProvenanceAnalysis(const ProvenanceAnalysis &);
1126
1127 public:
1128 ProvenanceAnalysis() {}
1129
1130 void setAA(AliasAnalysis *aa) { AA = aa; }
1131
1132 AliasAnalysis *getAA() const { return AA; }
1133
1134 bool related(const Value *A, const Value *B);
1135
1136 void clear() {
1137 CachedResults.clear();
1138 }
1139 };
1140}
1141
1142bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1143 // If the values are Selects with the same condition, we can do a more precise
1144 // check: just check for relations between the values on corresponding arms.
1145 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001146 if (A->getCondition() == SB->getCondition())
1147 return related(A->getTrueValue(), SB->getTrueValue()) ||
1148 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001149
1150 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001151 return related(A->getTrueValue(), B) ||
1152 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001153}
1154
1155bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1156 // If the values are PHIs in the same block, we can do a more precise as well
1157 // as efficient check: just check for relations between the values on
1158 // corresponding edges.
1159 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1160 if (PNB->getParent() == A->getParent()) {
1161 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1162 if (related(A->getIncomingValue(i),
1163 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1164 return true;
1165 return false;
1166 }
1167
1168 // Check each unique source of the PHI node against B.
1169 SmallPtrSet<const Value *, 4> UniqueSrc;
1170 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1171 const Value *PV1 = A->getIncomingValue(i);
1172 if (UniqueSrc.insert(PV1) && related(PV1, B))
1173 return true;
1174 }
1175
1176 // All of the arms checked out.
1177 return false;
1178}
1179
1180/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1181/// provenance, is ever stored within the function (not counting callees).
1182static bool isStoredObjCPointer(const Value *P) {
1183 SmallPtrSet<const Value *, 8> Visited;
1184 SmallVector<const Value *, 8> Worklist;
1185 Worklist.push_back(P);
1186 Visited.insert(P);
1187 do {
1188 P = Worklist.pop_back_val();
1189 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1190 UI != UE; ++UI) {
1191 const User *Ur = *UI;
1192 if (isa<StoreInst>(Ur)) {
1193 if (UI.getOperandNo() == 0)
1194 // The pointer is stored.
1195 return true;
1196 // The pointed is stored through.
1197 continue;
1198 }
1199 if (isa<CallInst>(Ur))
1200 // The pointer is passed as an argument, ignore this.
1201 continue;
1202 if (isa<PtrToIntInst>(P))
1203 // Assume the worst.
1204 return true;
1205 if (Visited.insert(Ur))
1206 Worklist.push_back(Ur);
1207 }
1208 } while (!Worklist.empty());
1209
1210 // Everything checked out.
1211 return false;
1212}
1213
1214bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1215 // Skip past provenance pass-throughs.
1216 A = GetUnderlyingObjCPtr(A);
1217 B = GetUnderlyingObjCPtr(B);
1218
1219 // Quick check.
1220 if (A == B)
1221 return true;
1222
1223 // Ask regular AliasAnalysis, for a first approximation.
1224 switch (AA->alias(A, B)) {
1225 case AliasAnalysis::NoAlias:
1226 return false;
1227 case AliasAnalysis::MustAlias:
1228 case AliasAnalysis::PartialAlias:
1229 return true;
1230 case AliasAnalysis::MayAlias:
1231 break;
1232 }
1233
1234 bool AIsIdentified = IsObjCIdentifiedObject(A);
1235 bool BIsIdentified = IsObjCIdentifiedObject(B);
1236
1237 // An ObjC-Identified object can't alias a load if it is never locally stored.
1238 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001239 // Check for an obvious escape.
1240 if (isa<LoadInst>(B))
1241 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001242 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001243 // Check for an obvious escape.
1244 if (isa<LoadInst>(A))
1245 return isStoredObjCPointer(B);
1246 // Both pointers are identified and escapes aren't an evident problem.
1247 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001248 }
Dan Gohman230768b2012-09-04 23:16:20 +00001249 } else if (BIsIdentified) {
1250 // Check for an obvious escape.
1251 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001252 return isStoredObjCPointer(B);
1253 }
1254
1255 // Special handling for PHI and Select.
1256 if (const PHINode *PN = dyn_cast<PHINode>(A))
1257 return relatedPHI(PN, B);
1258 if (const PHINode *PN = dyn_cast<PHINode>(B))
1259 return relatedPHI(PN, A);
1260 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1261 return relatedSelect(S, B);
1262 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1263 return relatedSelect(S, A);
1264
1265 // Conservative.
1266 return true;
1267}
1268
1269bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1270 // Begin by inserting a conservative value into the map. If the insertion
1271 // fails, we have the answer already. If it succeeds, leave it there until we
1272 // compute the real answer to guard against recursive queries.
1273 if (A > B) std::swap(A, B);
1274 std::pair<CachedResultsTy::iterator, bool> Pair =
1275 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1276 if (!Pair.second)
1277 return Pair.first->second;
1278
1279 bool Result = relatedCheck(A, B);
1280 CachedResults[ValuePairTy(A, B)] = Result;
1281 return Result;
1282}
1283
1284namespace {
1285 // Sequence - A sequence of states that a pointer may go through in which an
1286 // objc_retain and objc_release are actually needed.
1287 enum Sequence {
1288 S_None,
1289 S_Retain, ///< objc_retain(x)
1290 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1291 S_Use, ///< any use of x
1292 S_Stop, ///< like S_Release, but code motion is stopped
1293 S_Release, ///< objc_release(x)
1294 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1295 };
1296}
1297
1298static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1299 // The easy cases.
1300 if (A == B)
1301 return A;
1302 if (A == S_None || B == S_None)
1303 return S_None;
1304
John McCall9fbd3182011-06-15 23:37:01 +00001305 if (A > B) std::swap(A, B);
1306 if (TopDown) {
1307 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001308 if ((A == S_Retain || A == S_CanRelease) &&
1309 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001310 return B;
1311 } else {
1312 // Choose the side which is further along in the sequence.
1313 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001314 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001315 return A;
1316 // If both sides are releases, choose the more conservative one.
1317 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1318 return A;
1319 if (A == S_Release && B == S_MovableRelease)
1320 return A;
1321 }
1322
1323 return S_None;
1324}
1325
1326namespace {
1327 /// RRInfo - Unidirectional information about either a
1328 /// retain-decrement-use-release sequence or release-use-decrement-retain
1329 /// reverese sequence.
1330 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001331 /// KnownSafe - After an objc_retain, the reference count of the referenced
1332 /// object is known to be positive. Similarly, before an objc_release, the
1333 /// reference count of the referenced object is known to be positive. If
1334 /// there are retain-release pairs in code regions where the retain count
1335 /// is known to be positive, they can be eliminated, regardless of any side
1336 /// effects between them.
1337 ///
1338 /// Also, a retain+release pair nested within another retain+release
1339 /// pair all on the known same pointer value can be eliminated, regardless
1340 /// of any intervening side effects.
1341 ///
1342 /// KnownSafe is true when either of these conditions is satisfied.
1343 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001344
1345 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1346 /// opposed to objc_retain calls).
1347 bool IsRetainBlock;
1348
1349 /// IsTailCallRelease - True of the objc_release calls are all marked
1350 /// with the "tail" keyword.
1351 bool IsTailCallRelease;
1352
1353 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1354 /// a clang.imprecise_release tag, this is the metadata tag.
1355 MDNode *ReleaseMetadata;
1356
1357 /// Calls - For a top-down sequence, the set of objc_retains or
1358 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1359 SmallPtrSet<Instruction *, 2> Calls;
1360
1361 /// ReverseInsertPts - The set of optimal insert positions for
1362 /// moving calls in the opposite sequence.
1363 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1364
1365 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001366 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001367 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001368 ReleaseMetadata(0) {}
1369
1370 void clear();
1371 };
1372}
1373
1374void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001375 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001376 IsRetainBlock = false;
1377 IsTailCallRelease = false;
1378 ReleaseMetadata = 0;
1379 Calls.clear();
1380 ReverseInsertPts.clear();
1381}
1382
1383namespace {
1384 /// PtrState - This class summarizes several per-pointer runtime properties
1385 /// which are propogated through the flow graph.
1386 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001387 /// KnownPositiveRefCount - True if the reference count is known to
1388 /// be incremented.
1389 bool KnownPositiveRefCount;
1390
1391 /// Partial - True of we've seen an opportunity for partial RR elimination,
1392 /// such as pushing calls into a CFG triangle or into one side of a
1393 /// CFG diamond.
1394 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001395
1396 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001397 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001398
1399 public:
1400 /// RRI - Unidirectional information about the current sequence.
1401 /// TODO: Encapsulate this better.
1402 RRInfo RRI;
1403
Dan Gohman230768b2012-09-04 23:16:20 +00001404 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001405 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001406
Dan Gohman50ade652012-04-25 00:50:46 +00001407 void SetKnownPositiveRefCount() {
1408 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001409 }
1410
Dan Gohman50ade652012-04-25 00:50:46 +00001411 void ClearRefCount() {
1412 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001413 }
1414
John McCall9fbd3182011-06-15 23:37:01 +00001415 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001416 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001417 }
1418
1419 void SetSeq(Sequence NewSeq) {
1420 Seq = NewSeq;
1421 }
1422
John McCall9fbd3182011-06-15 23:37:01 +00001423 Sequence GetSeq() const {
1424 return Seq;
1425 }
1426
1427 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001428 ResetSequenceProgress(S_None);
1429 }
1430
1431 void ResetSequenceProgress(Sequence NewSeq) {
1432 Seq = NewSeq;
1433 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001434 RRI.clear();
1435 }
1436
1437 void Merge(const PtrState &Other, bool TopDown);
1438 };
1439}
1440
1441void
1442PtrState::Merge(const PtrState &Other, bool TopDown) {
1443 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001444 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001445
1446 // We can't merge a plain objc_retain with an objc_retainBlock.
1447 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1448 Seq = S_None;
1449
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001450 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001451 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001452 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001453 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001454 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001455 // If we're doing a merge on a path that's previously seen a partial
1456 // merge, conservatively drop the sequence, to avoid doing partial
1457 // RR elimination. If the branch predicates for the two merge differ,
1458 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001459 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001460 } else {
1461 // Conservatively merge the ReleaseMetadata information.
1462 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1463 RRI.ReleaseMetadata = 0;
1464
Dan Gohmane6d5e882011-08-19 00:26:36 +00001465 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001466 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1467 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001468 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001469
1470 // Merge the insert point sets. If there are any differences,
1471 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001472 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001473 for (SmallPtrSet<Instruction *, 2>::const_iterator
1474 I = Other.RRI.ReverseInsertPts.begin(),
1475 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001476 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001477 }
1478}
1479
1480namespace {
1481 /// BBState - Per-BasicBlock state.
1482 class BBState {
1483 /// TopDownPathCount - The number of unique control paths from the entry
1484 /// which can reach this block.
1485 unsigned TopDownPathCount;
1486
1487 /// BottomUpPathCount - The number of unique control paths to exits
1488 /// from this block.
1489 unsigned BottomUpPathCount;
1490
1491 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1492 typedef MapVector<const Value *, PtrState> MapTy;
1493
1494 /// PerPtrTopDown - The top-down traversal uses this to record information
1495 /// known about a pointer at the bottom of each block.
1496 MapTy PerPtrTopDown;
1497
1498 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1499 /// known about a pointer at the top of each block.
1500 MapTy PerPtrBottomUp;
1501
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001502 /// Preds, Succs - Effective successors and predecessors of the current
1503 /// block (this ignores ignorable edges and ignored backedges).
1504 SmallVector<BasicBlock *, 2> Preds;
1505 SmallVector<BasicBlock *, 2> Succs;
1506
John McCall9fbd3182011-06-15 23:37:01 +00001507 public:
1508 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1509
1510 typedef MapTy::iterator ptr_iterator;
1511 typedef MapTy::const_iterator ptr_const_iterator;
1512
1513 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1514 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1515 ptr_const_iterator top_down_ptr_begin() const {
1516 return PerPtrTopDown.begin();
1517 }
1518 ptr_const_iterator top_down_ptr_end() const {
1519 return PerPtrTopDown.end();
1520 }
1521
1522 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1523 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1524 ptr_const_iterator bottom_up_ptr_begin() const {
1525 return PerPtrBottomUp.begin();
1526 }
1527 ptr_const_iterator bottom_up_ptr_end() const {
1528 return PerPtrBottomUp.end();
1529 }
1530
1531 /// SetAsEntry - Mark this block as being an entry block, which has one
1532 /// path from the entry by definition.
1533 void SetAsEntry() { TopDownPathCount = 1; }
1534
1535 /// SetAsExit - Mark this block as being an exit block, which has one
1536 /// path to an exit by definition.
1537 void SetAsExit() { BottomUpPathCount = 1; }
1538
1539 PtrState &getPtrTopDownState(const Value *Arg) {
1540 return PerPtrTopDown[Arg];
1541 }
1542
1543 PtrState &getPtrBottomUpState(const Value *Arg) {
1544 return PerPtrBottomUp[Arg];
1545 }
1546
1547 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001548 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001549 }
1550
1551 void clearTopDownPointers() {
1552 PerPtrTopDown.clear();
1553 }
1554
1555 void InitFromPred(const BBState &Other);
1556 void InitFromSucc(const BBState &Other);
1557 void MergePred(const BBState &Other);
1558 void MergeSucc(const BBState &Other);
1559
1560 /// GetAllPathCount - Return the number of possible unique paths from an
1561 /// entry to an exit which pass through this block. This is only valid
1562 /// after both the top-down and bottom-up traversals are complete.
1563 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001564 assert(TopDownPathCount != 0);
1565 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001566 return TopDownPathCount * BottomUpPathCount;
1567 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001568
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001569 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001570 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001571 edge_iterator pred_begin() { return Preds.begin(); }
1572 edge_iterator pred_end() { return Preds.end(); }
1573 edge_iterator succ_begin() { return Succs.begin(); }
1574 edge_iterator succ_end() { return Succs.end(); }
1575
1576 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1577 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1578
1579 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001580 };
1581}
1582
1583void BBState::InitFromPred(const BBState &Other) {
1584 PerPtrTopDown = Other.PerPtrTopDown;
1585 TopDownPathCount = Other.TopDownPathCount;
1586}
1587
1588void BBState::InitFromSucc(const BBState &Other) {
1589 PerPtrBottomUp = Other.PerPtrBottomUp;
1590 BottomUpPathCount = Other.BottomUpPathCount;
1591}
1592
1593/// MergePred - The top-down traversal uses this to merge information about
1594/// predecessors to form the initial state for a new block.
1595void BBState::MergePred(const BBState &Other) {
1596 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1597 // loop backedge. Loop backedges are special.
1598 TopDownPathCount += Other.TopDownPathCount;
1599
1600 // For each entry in the other set, if our set has an entry with the same key,
1601 // merge the entries. Otherwise, copy the entry and merge it with an empty
1602 // entry.
1603 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1604 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1605 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1606 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1607 /*TopDown=*/true);
1608 }
1609
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001610 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001611 // same key, force it to merge with an empty entry.
1612 for (ptr_iterator MI = top_down_ptr_begin(),
1613 ME = top_down_ptr_end(); MI != ME; ++MI)
1614 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1615 MI->second.Merge(PtrState(), /*TopDown=*/true);
1616}
1617
1618/// MergeSucc - The bottom-up traversal uses this to merge information about
1619/// successors to form the initial state for a new block.
1620void BBState::MergeSucc(const BBState &Other) {
1621 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1622 // loop backedge. Loop backedges are special.
1623 BottomUpPathCount += Other.BottomUpPathCount;
1624
1625 // For each entry in the other set, if our set has an entry with the
1626 // same key, merge the entries. Otherwise, copy the entry and merge
1627 // it with an empty entry.
1628 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1629 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1630 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1631 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1632 /*TopDown=*/false);
1633 }
1634
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001635 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001636 // with the same key, force it to merge with an empty entry.
1637 for (ptr_iterator MI = bottom_up_ptr_begin(),
1638 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1639 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1640 MI->second.Merge(PtrState(), /*TopDown=*/false);
1641}
1642
1643namespace {
1644 /// ObjCARCOpt - The main ARC optimization pass.
1645 class ObjCARCOpt : public FunctionPass {
1646 bool Changed;
1647 ProvenanceAnalysis PA;
1648
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001649 /// Run - A flag indicating whether this optimization pass should run.
1650 bool Run;
1651
John McCall9fbd3182011-06-15 23:37:01 +00001652 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1653 /// functions, for use in creating calls to them. These are initialized
1654 /// lazily to avoid cluttering up the Module with unused declarations.
1655 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001656 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001657
1658 /// UsedInThisFunciton - Flags which determine whether each of the
1659 /// interesting runtine functions is in fact used in the current function.
1660 unsigned UsedInThisFunction;
1661
1662 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1663 /// metadata.
1664 unsigned ImpreciseReleaseMDKind;
1665
Dan Gohman62e5b402011-12-12 18:20:00 +00001666 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001667 /// metadata.
1668 unsigned CopyOnEscapeMDKind;
1669
Dan Gohmandbe266b2012-02-17 18:59:53 +00001670 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1671 /// clang.arc.no_objc_arc_exceptions metadata.
1672 unsigned NoObjCARCExceptionsMDKind;
1673
John McCall9fbd3182011-06-15 23:37:01 +00001674 Constant *getRetainRVCallee(Module *M);
1675 Constant *getAutoreleaseRVCallee(Module *M);
1676 Constant *getReleaseCallee(Module *M);
1677 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001678 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001679 Constant *getAutoreleaseCallee(Module *M);
1680
Dan Gohman79522dc2012-01-13 00:39:07 +00001681 bool IsRetainBlockOptimizable(const Instruction *Inst);
1682
John McCall9fbd3182011-06-15 23:37:01 +00001683 void OptimizeRetainCall(Function &F, Instruction *Retain);
1684 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1685 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1686 void OptimizeIndividualCalls(Function &F);
1687
1688 void CheckForCFGHazards(const BasicBlock *BB,
1689 DenseMap<const BasicBlock *, BBState> &BBStates,
1690 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001691 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001692 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001693 MapVector<Value *, RRInfo> &Retains,
1694 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001695 bool VisitBottomUp(BasicBlock *BB,
1696 DenseMap<const BasicBlock *, BBState> &BBStates,
1697 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001698 bool VisitInstructionTopDown(Instruction *Inst,
1699 DenseMap<Value *, RRInfo> &Releases,
1700 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001701 bool VisitTopDown(BasicBlock *BB,
1702 DenseMap<const BasicBlock *, BBState> &BBStates,
1703 DenseMap<Value *, RRInfo> &Releases);
1704 bool Visit(Function &F,
1705 DenseMap<const BasicBlock *, BBState> &BBStates,
1706 MapVector<Value *, RRInfo> &Retains,
1707 DenseMap<Value *, RRInfo> &Releases);
1708
1709 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1710 MapVector<Value *, RRInfo> &Retains,
1711 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001712 SmallVectorImpl<Instruction *> &DeadInsts,
1713 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001714
1715 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1716 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001717 DenseMap<Value *, RRInfo> &Releases,
1718 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001719
1720 void OptimizeWeakCalls(Function &F);
1721
1722 bool OptimizeSequences(Function &F);
1723
1724 void OptimizeReturns(Function &F);
1725
1726 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1727 virtual bool doInitialization(Module &M);
1728 virtual bool runOnFunction(Function &F);
1729 virtual void releaseMemory();
1730
1731 public:
1732 static char ID;
1733 ObjCARCOpt() : FunctionPass(ID) {
1734 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1735 }
1736 };
1737}
1738
1739char ObjCARCOpt::ID = 0;
1740INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1741 "objc-arc", "ObjC ARC optimization", false, false)
1742INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1743INITIALIZE_PASS_END(ObjCARCOpt,
1744 "objc-arc", "ObjC ARC optimization", false, false)
1745
1746Pass *llvm::createObjCARCOptPass() {
1747 return new ObjCARCOpt();
1748}
1749
1750void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1751 AU.addRequired<ObjCARCAliasAnalysis>();
1752 AU.addRequired<AliasAnalysis>();
1753 // ARC optimization doesn't currently split critical edges.
1754 AU.setPreservesCFG();
1755}
1756
Dan Gohman79522dc2012-01-13 00:39:07 +00001757bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1758 // Without the magic metadata tag, we have to assume this might be an
1759 // objc_retainBlock call inserted to convert a block pointer to an id,
1760 // in which case it really is needed.
1761 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1762 return false;
1763
1764 // If the pointer "escapes" (not including being used in a call),
1765 // the copy may be needed.
1766 if (DoesObjCBlockEscape(Inst))
1767 return false;
1768
1769 // Otherwise, it's not needed.
1770 return true;
1771}
1772
John McCall9fbd3182011-06-15 23:37:01 +00001773Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1774 if (!RetainRVCallee) {
1775 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001776 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001777 Type *Params[] = { I8X };
1778 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1779 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001780 RetainRVCallee =
1781 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1782 Attributes);
1783 }
1784 return RetainRVCallee;
1785}
1786
1787Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1788 if (!AutoreleaseRVCallee) {
1789 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001790 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001791 Type *Params[] = { I8X };
1792 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1793 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001794 AutoreleaseRVCallee =
1795 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1796 Attributes);
1797 }
1798 return AutoreleaseRVCallee;
1799}
1800
1801Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1802 if (!ReleaseCallee) {
1803 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001804 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1805 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001806 ReleaseCallee =
1807 M->getOrInsertFunction(
1808 "objc_release",
1809 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1810 Attributes);
1811 }
1812 return ReleaseCallee;
1813}
1814
1815Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1816 if (!RetainCallee) {
1817 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001818 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1819 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001820 RetainCallee =
1821 M->getOrInsertFunction(
1822 "objc_retain",
1823 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1824 Attributes);
1825 }
1826 return RetainCallee;
1827}
1828
Dan Gohman44280692011-07-22 22:29:21 +00001829Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1830 if (!RetainBlockCallee) {
1831 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001832 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001833 // objc_retainBlock is not nounwind because it calls user copy constructors
1834 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001835 RetainBlockCallee =
1836 M->getOrInsertFunction(
1837 "objc_retainBlock",
1838 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001839 AttrListPtr());
Dan Gohman44280692011-07-22 22:29:21 +00001840 }
1841 return RetainBlockCallee;
1842}
1843
John McCall9fbd3182011-06-15 23:37:01 +00001844Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1845 if (!AutoreleaseCallee) {
1846 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001847 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1848 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00001849 AutoreleaseCallee =
1850 M->getOrInsertFunction(
1851 "objc_autorelease",
1852 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1853 Attributes);
1854 }
1855 return AutoreleaseCallee;
1856}
1857
Dan Gohman230768b2012-09-04 23:16:20 +00001858/// IsPotentialUse - Test whether the given value is possible a
1859/// reference-counted pointer, including tests which utilize AliasAnalysis.
1860static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1861 // First make the rudimentary check.
1862 if (!IsPotentialUse(Op))
1863 return false;
1864
1865 // Objects in constant memory are not reference-counted.
1866 if (AA.pointsToConstantMemory(Op))
1867 return false;
1868
1869 // Pointers in constant memory are not pointing to reference-counted objects.
1870 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1871 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1872 return false;
1873
1874 // Otherwise assume the worst.
1875 return true;
1876}
1877
John McCall9fbd3182011-06-15 23:37:01 +00001878/// CanAlterRefCount - Test whether the given instruction can result in a
1879/// reference count modification (positive or negative) for the pointer's
1880/// object.
1881static bool
1882CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1883 ProvenanceAnalysis &PA, InstructionClass Class) {
1884 switch (Class) {
1885 case IC_Autorelease:
1886 case IC_AutoreleaseRV:
1887 case IC_User:
1888 // These operations never directly modify a reference count.
1889 return false;
1890 default: break;
1891 }
1892
1893 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1894 assert(CS && "Only calls can alter reference counts!");
1895
1896 // See if AliasAnalysis can help us with the call.
1897 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1898 if (AliasAnalysis::onlyReadsMemory(MRB))
1899 return false;
1900 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1901 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1902 I != E; ++I) {
1903 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001904 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001905 return true;
1906 }
1907 return false;
1908 }
1909
1910 // Assume the worst.
1911 return true;
1912}
1913
1914/// CanUse - Test whether the given instruction can "use" the given pointer's
1915/// object in a way that requires the reference count to be positive.
1916static bool
1917CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1918 InstructionClass Class) {
1919 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1920 if (Class == IC_Call)
1921 return false;
1922
1923 // Consider various instructions which may have pointer arguments which are
1924 // not "uses".
1925 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1926 // Comparing a pointer with null, or any other constant, isn't really a use,
1927 // because we don't care what the pointer points to, or about the values
1928 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001929 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001930 return false;
1931 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1932 // For calls, just check the arguments (and not the callee operand).
1933 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1934 OE = CS.arg_end(); OI != OE; ++OI) {
1935 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001936 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001937 return true;
1938 }
1939 return false;
1940 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1941 // Special-case stores, because we don't care about the stored value, just
1942 // the store address.
1943 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1944 // If we can't tell what the underlying object was, assume there is a
1945 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001946 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001947 }
1948
1949 // Check each operand for a match.
1950 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1951 OI != OE; ++OI) {
1952 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001953 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001954 return true;
1955 }
1956 return false;
1957}
1958
1959/// CanInterruptRV - Test whether the given instruction can autorelease
1960/// any pointer or cause an autoreleasepool pop.
1961static bool
1962CanInterruptRV(InstructionClass Class) {
1963 switch (Class) {
1964 case IC_AutoreleasepoolPop:
1965 case IC_CallOrUser:
1966 case IC_Call:
1967 case IC_Autorelease:
1968 case IC_AutoreleaseRV:
1969 case IC_FusedRetainAutorelease:
1970 case IC_FusedRetainAutoreleaseRV:
1971 return true;
1972 default:
1973 return false;
1974 }
1975}
1976
1977namespace {
1978 /// DependenceKind - There are several kinds of dependence-like concepts in
1979 /// use here.
1980 enum DependenceKind {
1981 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00001982 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00001983 CanChangeRetainCount,
1984 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1985 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1986 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1987 };
1988}
1989
1990/// Depends - Test if there can be dependencies on Inst through Arg. This
1991/// function only tests dependencies relevant for removing pairs of calls.
1992static bool
1993Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1994 ProvenanceAnalysis &PA) {
1995 // If we've reached the definition of Arg, stop.
1996 if (Inst == Arg)
1997 return true;
1998
1999 switch (Flavor) {
2000 case NeedsPositiveRetainCount: {
2001 InstructionClass Class = GetInstructionClass(Inst);
2002 switch (Class) {
2003 case IC_AutoreleasepoolPop:
2004 case IC_AutoreleasepoolPush:
2005 case IC_None:
2006 return false;
2007 default:
2008 return CanUse(Inst, Arg, PA, Class);
2009 }
2010 }
2011
Dan Gohman511568d2012-04-13 00:59:57 +00002012 case AutoreleasePoolBoundary: {
2013 InstructionClass Class = GetInstructionClass(Inst);
2014 switch (Class) {
2015 case IC_AutoreleasepoolPop:
2016 case IC_AutoreleasepoolPush:
2017 // These mark the end and begin of an autorelease pool scope.
2018 return true;
2019 default:
2020 // Nothing else does this.
2021 return false;
2022 }
2023 }
2024
John McCall9fbd3182011-06-15 23:37:01 +00002025 case CanChangeRetainCount: {
2026 InstructionClass Class = GetInstructionClass(Inst);
2027 switch (Class) {
2028 case IC_AutoreleasepoolPop:
2029 // Conservatively assume this can decrement any count.
2030 return true;
2031 case IC_AutoreleasepoolPush:
2032 case IC_None:
2033 return false;
2034 default:
2035 return CanAlterRefCount(Inst, Arg, PA, Class);
2036 }
2037 }
2038
2039 case RetainAutoreleaseDep:
2040 switch (GetBasicInstructionClass(Inst)) {
2041 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002042 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002043 // Don't merge an objc_autorelease with an objc_retain inside a different
2044 // autoreleasepool scope.
2045 return true;
2046 case IC_Retain:
2047 case IC_RetainRV:
2048 // Check for a retain of the same pointer for merging.
2049 return GetObjCArg(Inst) == Arg;
2050 default:
2051 // Nothing else matters for objc_retainAutorelease formation.
2052 return false;
2053 }
John McCall9fbd3182011-06-15 23:37:01 +00002054
2055 case RetainAutoreleaseRVDep: {
2056 InstructionClass Class = GetBasicInstructionClass(Inst);
2057 switch (Class) {
2058 case IC_Retain:
2059 case IC_RetainRV:
2060 // Check for a retain of the same pointer for merging.
2061 return GetObjCArg(Inst) == Arg;
2062 default:
2063 // Anything that can autorelease interrupts
2064 // retainAutoreleaseReturnValue formation.
2065 return CanInterruptRV(Class);
2066 }
John McCall9fbd3182011-06-15 23:37:01 +00002067 }
2068
2069 case RetainRVDep:
2070 return CanInterruptRV(GetBasicInstructionClass(Inst));
2071 }
2072
2073 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002074}
2075
2076/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2077/// find local and non-local dependencies on Arg.
2078/// TODO: Cache results?
2079static void
2080FindDependencies(DependenceKind Flavor,
2081 const Value *Arg,
2082 BasicBlock *StartBB, Instruction *StartInst,
2083 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2084 SmallPtrSet<const BasicBlock *, 4> &Visited,
2085 ProvenanceAnalysis &PA) {
2086 BasicBlock::iterator StartPos = StartInst;
2087
2088 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2089 Worklist.push_back(std::make_pair(StartBB, StartPos));
2090 do {
2091 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2092 Worklist.pop_back_val();
2093 BasicBlock *LocalStartBB = Pair.first;
2094 BasicBlock::iterator LocalStartPos = Pair.second;
2095 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2096 for (;;) {
2097 if (LocalStartPos == StartBBBegin) {
2098 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2099 if (PI == PE)
2100 // If we've reached the function entry, produce a null dependence.
2101 DependingInstructions.insert(0);
2102 else
2103 // Add the predecessors to the worklist.
2104 do {
2105 BasicBlock *PredBB = *PI;
2106 if (Visited.insert(PredBB))
2107 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2108 } while (++PI != PE);
2109 break;
2110 }
2111
2112 Instruction *Inst = --LocalStartPos;
2113 if (Depends(Flavor, Inst, Arg, PA)) {
2114 DependingInstructions.insert(Inst);
2115 break;
2116 }
2117 }
2118 } while (!Worklist.empty());
2119
2120 // Determine whether the original StartBB post-dominates all of the blocks we
2121 // visited. If not, insert a sentinal indicating that most optimizations are
2122 // not safe.
2123 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2124 E = Visited.end(); I != E; ++I) {
2125 const BasicBlock *BB = *I;
2126 if (BB == StartBB)
2127 continue;
2128 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2129 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2130 const BasicBlock *Succ = *SI;
2131 if (Succ != StartBB && !Visited.count(Succ)) {
2132 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2133 return;
2134 }
2135 }
2136 }
2137}
2138
2139static bool isNullOrUndef(const Value *V) {
2140 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2141}
2142
2143static bool isNoopInstruction(const Instruction *I) {
2144 return isa<BitCastInst>(I) ||
2145 (isa<GetElementPtrInst>(I) &&
2146 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2147}
2148
2149/// OptimizeRetainCall - Turn objc_retain into
2150/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2151void
2152ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002153 ImmutableCallSite CS(GetObjCArg(Retain));
2154 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002155 if (!Call) return;
2156 if (Call->getParent() != Retain->getParent()) return;
2157
2158 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002159 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002160 ++I;
2161 while (isNoopInstruction(I)) ++I;
2162 if (&*I != Retain)
2163 return;
2164
2165 // Turn it to an objc_retainAutoreleasedReturnValue..
2166 Changed = true;
2167 ++NumPeeps;
2168 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2169}
2170
2171/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002172/// objc_retain if the operand is not a return value. Or, if it can be paired
2173/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002174bool
2175ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002176 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002177 const Value *Arg = GetObjCArg(RetainRV);
2178 ImmutableCallSite CS(Arg);
2179 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002180 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002181 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002182 ++I;
2183 while (isNoopInstruction(I)) ++I;
2184 if (&*I == RetainRV)
2185 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002186 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002187 BasicBlock *RetainRVParent = RetainRV->getParent();
2188 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002189 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002190 while (isNoopInstruction(I)) ++I;
2191 if (&*I == RetainRV)
2192 return false;
2193 }
John McCall9fbd3182011-06-15 23:37:01 +00002194 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002195 }
John McCall9fbd3182011-06-15 23:37:01 +00002196
2197 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2198 // pointer. In this case, we can delete the pair.
2199 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2200 if (I != Begin) {
2201 do --I; while (I != Begin && isNoopInstruction(I));
2202 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2203 GetObjCArg(I) == Arg) {
2204 Changed = true;
2205 ++NumPeeps;
2206 EraseInstruction(I);
2207 EraseInstruction(RetainRV);
2208 return true;
2209 }
2210 }
2211
2212 // Turn it to a plain objc_retain.
2213 Changed = true;
2214 ++NumPeeps;
2215 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2216 return false;
2217}
2218
2219/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2220/// objc_autorelease if the result is not used as a return value.
2221void
2222ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2223 // Check for a return of the pointer value.
2224 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002225 SmallVector<const Value *, 2> Users;
2226 Users.push_back(Ptr);
2227 do {
2228 Ptr = Users.pop_back_val();
2229 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2230 UI != UE; ++UI) {
2231 const User *I = *UI;
2232 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2233 return;
2234 if (isa<BitCastInst>(I))
2235 Users.push_back(I);
2236 }
2237 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002238
2239 Changed = true;
2240 ++NumPeeps;
2241 cast<CallInst>(AutoreleaseRV)->
2242 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2243}
2244
2245/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2246/// simplifications without doing any additional analysis.
2247void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2248 // Reset all the flags in preparation for recomputing them.
2249 UsedInThisFunction = 0;
2250
2251 // Visit all objc_* calls in F.
2252 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2253 Instruction *Inst = &*I++;
2254 InstructionClass Class = GetBasicInstructionClass(Inst);
2255
2256 switch (Class) {
2257 default: break;
2258
2259 // Delete no-op casts. These function calls have special semantics, but
2260 // the semantics are entirely implemented via lowering in the front-end,
2261 // so by the time they reach the optimizer, they are just no-op calls
2262 // which return their argument.
2263 //
2264 // There are gray areas here, as the ability to cast reference-counted
2265 // pointers to raw void* and back allows code to break ARC assumptions,
2266 // however these are currently considered to be unimportant.
2267 case IC_NoopCast:
2268 Changed = true;
2269 ++NumNoops;
2270 EraseInstruction(Inst);
2271 continue;
2272
2273 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2274 case IC_StoreWeak:
2275 case IC_LoadWeak:
2276 case IC_LoadWeakRetained:
2277 case IC_InitWeak:
2278 case IC_DestroyWeak: {
2279 CallInst *CI = cast<CallInst>(Inst);
2280 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002281 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002282 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002283 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2284 Constant::getNullValue(Ty),
2285 CI);
2286 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2287 CI->eraseFromParent();
2288 continue;
2289 }
2290 break;
2291 }
2292 case IC_CopyWeak:
2293 case IC_MoveWeak: {
2294 CallInst *CI = cast<CallInst>(Inst);
2295 if (isNullOrUndef(CI->getArgOperand(0)) ||
2296 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002297 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002298 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002299 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2300 Constant::getNullValue(Ty),
2301 CI);
2302 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2303 CI->eraseFromParent();
2304 continue;
2305 }
2306 break;
2307 }
2308 case IC_Retain:
2309 OptimizeRetainCall(F, Inst);
2310 break;
2311 case IC_RetainRV:
2312 if (OptimizeRetainRVCall(F, Inst))
2313 continue;
2314 break;
2315 case IC_AutoreleaseRV:
2316 OptimizeAutoreleaseRVCall(F, Inst);
2317 break;
2318 }
2319
2320 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2321 if (IsAutorelease(Class) && Inst->use_empty()) {
2322 CallInst *Call = cast<CallInst>(Inst);
2323 const Value *Arg = Call->getArgOperand(0);
2324 Arg = FindSingleUseIdentifiedObject(Arg);
2325 if (Arg) {
2326 Changed = true;
2327 ++NumAutoreleases;
2328
2329 // Create the declaration lazily.
2330 LLVMContext &C = Inst->getContext();
2331 CallInst *NewCall =
2332 CallInst::Create(getReleaseCallee(F.getParent()),
2333 Call->getArgOperand(0), "", Call);
2334 NewCall->setMetadata(ImpreciseReleaseMDKind,
2335 MDNode::get(C, ArrayRef<Value *>()));
2336 EraseInstruction(Call);
2337 Inst = NewCall;
2338 Class = IC_Release;
2339 }
2340 }
2341
2342 // For functions which can never be passed stack arguments, add
2343 // a tail keyword.
2344 if (IsAlwaysTail(Class)) {
2345 Changed = true;
2346 cast<CallInst>(Inst)->setTailCall();
2347 }
2348
2349 // Set nounwind as needed.
2350 if (IsNoThrow(Class)) {
2351 Changed = true;
2352 cast<CallInst>(Inst)->setDoesNotThrow();
2353 }
2354
2355 if (!IsNoopOnNull(Class)) {
2356 UsedInThisFunction |= 1 << Class;
2357 continue;
2358 }
2359
2360 const Value *Arg = GetObjCArg(Inst);
2361
2362 // ARC calls with null are no-ops. Delete them.
2363 if (isNullOrUndef(Arg)) {
2364 Changed = true;
2365 ++NumNoops;
2366 EraseInstruction(Inst);
2367 continue;
2368 }
2369
2370 // Keep track of which of retain, release, autorelease, and retain_block
2371 // are actually present in this function.
2372 UsedInThisFunction |= 1 << Class;
2373
2374 // If Arg is a PHI, and one or more incoming values to the
2375 // PHI are null, and the call is control-equivalent to the PHI, and there
2376 // are no relevant side effects between the PHI and the call, the call
2377 // could be pushed up to just those paths with non-null incoming values.
2378 // For now, don't bother splitting critical edges for this.
2379 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2380 Worklist.push_back(std::make_pair(Inst, Arg));
2381 do {
2382 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2383 Inst = Pair.first;
2384 Arg = Pair.second;
2385
2386 const PHINode *PN = dyn_cast<PHINode>(Arg);
2387 if (!PN) continue;
2388
2389 // Determine if the PHI has any null operands, or any incoming
2390 // critical edges.
2391 bool HasNull = false;
2392 bool HasCriticalEdges = false;
2393 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2394 Value *Incoming =
2395 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2396 if (isNullOrUndef(Incoming))
2397 HasNull = true;
2398 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2399 .getNumSuccessors() != 1) {
2400 HasCriticalEdges = true;
2401 break;
2402 }
2403 }
2404 // If we have null operands and no critical edges, optimize.
2405 if (!HasCriticalEdges && HasNull) {
2406 SmallPtrSet<Instruction *, 4> DependingInstructions;
2407 SmallPtrSet<const BasicBlock *, 4> Visited;
2408
2409 // Check that there is nothing that cares about the reference
2410 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002411 switch (Class) {
2412 case IC_Retain:
2413 case IC_RetainBlock:
2414 // These can always be moved up.
2415 break;
2416 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002417 // These can't be moved across things that care about the retain
2418 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002419 FindDependencies(NeedsPositiveRetainCount, Arg,
2420 Inst->getParent(), Inst,
2421 DependingInstructions, Visited, PA);
2422 break;
2423 case IC_Autorelease:
2424 // These can't be moved across autorelease pool scope boundaries.
2425 FindDependencies(AutoreleasePoolBoundary, Arg,
2426 Inst->getParent(), Inst,
2427 DependingInstructions, Visited, PA);
2428 break;
2429 case IC_RetainRV:
2430 case IC_AutoreleaseRV:
2431 // Don't move these; the RV optimization depends on the autoreleaseRV
2432 // being tail called, and the retainRV being immediately after a call
2433 // (which might still happen if we get lucky with codegen layout, but
2434 // it's not worth taking the chance).
2435 continue;
2436 default:
2437 llvm_unreachable("Invalid dependence flavor");
2438 }
2439
John McCall9fbd3182011-06-15 23:37:01 +00002440 if (DependingInstructions.size() == 1 &&
2441 *DependingInstructions.begin() == PN) {
2442 Changed = true;
2443 ++NumPartialNoops;
2444 // Clone the call into each predecessor that has a non-null value.
2445 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002446 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002447 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2448 Value *Incoming =
2449 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2450 if (!isNullOrUndef(Incoming)) {
2451 CallInst *Clone = cast<CallInst>(CInst->clone());
2452 Value *Op = PN->getIncomingValue(i);
2453 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2454 if (Op->getType() != ParamTy)
2455 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2456 Clone->setArgOperand(0, Op);
2457 Clone->insertBefore(InsertPos);
2458 Worklist.push_back(std::make_pair(Clone, Incoming));
2459 }
2460 }
2461 // Erase the original call.
2462 EraseInstruction(CInst);
2463 continue;
2464 }
2465 }
2466 } while (!Worklist.empty());
2467 }
2468}
2469
2470/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2471/// control flow, or other CFG structures where moving code across the edge
2472/// would result in it being executed more.
2473void
2474ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2475 DenseMap<const BasicBlock *, BBState> &BBStates,
2476 BBState &MyStates) const {
2477 // If any top-down local-use or possible-dec has a succ which is earlier in
2478 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002479 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002480 E = MyStates.top_down_ptr_end(); I != E; ++I)
2481 switch (I->second.GetSeq()) {
2482 default: break;
2483 case S_Use: {
2484 const Value *Arg = I->first;
2485 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2486 bool SomeSuccHasSame = false;
2487 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002488 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002489 succ_const_iterator SI(TI), SE(TI, false);
2490
2491 // If the terminator is an invoke marked with the
2492 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2493 // ignored, for ARC purposes.
2494 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2495 --SE;
2496
2497 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002498 Sequence SuccSSeq = S_None;
2499 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002500 // If VisitBottomUp has pointer information for this successor, take
2501 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002502 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2503 BBStates.find(*SI);
2504 assert(BBI != BBStates.end());
2505 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2506 SuccSSeq = SuccS.GetSeq();
2507 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002508 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002509 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002510 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002511 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002512 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002513 break;
2514 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002515 continue;
2516 }
John McCall9fbd3182011-06-15 23:37:01 +00002517 case S_Use:
2518 SomeSuccHasSame = true;
2519 break;
2520 case S_Stop:
2521 case S_Release:
2522 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002523 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002524 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002525 break;
2526 case S_Retain:
2527 llvm_unreachable("bottom-up pointer in retain state!");
2528 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002529 }
John McCall9fbd3182011-06-15 23:37:01 +00002530 // If the state at the other end of any of the successor edges
2531 // matches the current state, require all edges to match. This
2532 // guards against loops in the middle of a sequence.
2533 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002534 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002535 break;
John McCall9fbd3182011-06-15 23:37:01 +00002536 }
2537 case S_CanRelease: {
2538 const Value *Arg = I->first;
2539 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2540 bool SomeSuccHasSame = false;
2541 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002542 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002543 succ_const_iterator SI(TI), SE(TI, false);
2544
2545 // If the terminator is an invoke marked with the
2546 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2547 // ignored, for ARC purposes.
2548 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2549 --SE;
2550
2551 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002552 Sequence SuccSSeq = S_None;
2553 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002554 // If VisitBottomUp has pointer information for this successor, take
2555 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002556 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2557 BBStates.find(*SI);
2558 assert(BBI != BBStates.end());
2559 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2560 SuccSSeq = SuccS.GetSeq();
2561 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002562 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002563 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002564 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002565 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002566 break;
2567 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002568 continue;
2569 }
John McCall9fbd3182011-06-15 23:37:01 +00002570 case S_CanRelease:
2571 SomeSuccHasSame = true;
2572 break;
2573 case S_Stop:
2574 case S_Release:
2575 case S_MovableRelease:
2576 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002577 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002578 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002579 break;
2580 case S_Retain:
2581 llvm_unreachable("bottom-up pointer in retain state!");
2582 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002583 }
John McCall9fbd3182011-06-15 23:37:01 +00002584 // If the state at the other end of any of the successor edges
2585 // matches the current state, require all edges to match. This
2586 // guards against loops in the middle of a sequence.
2587 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002588 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002589 break;
John McCall9fbd3182011-06-15 23:37:01 +00002590 }
2591 }
2592}
2593
2594bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002595ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002596 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002597 MapVector<Value *, RRInfo> &Retains,
2598 BBState &MyStates) {
2599 bool NestingDetected = false;
2600 InstructionClass Class = GetInstructionClass(Inst);
2601 const Value *Arg = 0;
2602
2603 switch (Class) {
2604 case IC_Release: {
2605 Arg = GetObjCArg(Inst);
2606
2607 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2608
2609 // If we see two releases in a row on the same pointer. If so, make
2610 // a note, and we'll cicle back to revisit it after we've
2611 // hopefully eliminated the second release, which may allow us to
2612 // eliminate the first release too.
2613 // Theoretically we could implement removal of nested retain+release
2614 // pairs by making PtrState hold a stack of states, but this is
2615 // simple and avoids adding overhead for the non-nested case.
2616 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2617 NestingDetected = true;
2618
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002619 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002620 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002621 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002622 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002623 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2624 S.RRI.Calls.insert(Inst);
2625
Dan Gohman230768b2012-09-04 23:16:20 +00002626 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002627 break;
2628 }
2629 case IC_RetainBlock:
2630 // An objc_retainBlock call with just a use may need to be kept,
2631 // because it may be copying a block from the stack to the heap.
2632 if (!IsRetainBlockOptimizable(Inst))
2633 break;
2634 // FALLTHROUGH
2635 case IC_Retain:
2636 case IC_RetainRV: {
2637 Arg = GetObjCArg(Inst);
2638
2639 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002640 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002641
2642 switch (S.GetSeq()) {
2643 case S_Stop:
2644 case S_Release:
2645 case S_MovableRelease:
2646 case S_Use:
2647 S.RRI.ReverseInsertPts.clear();
2648 // FALL THROUGH
2649 case S_CanRelease:
2650 // Don't do retain+release tracking for IC_RetainRV, because it's
2651 // better to let it remain as the first instruction after a call.
2652 if (Class != IC_RetainRV) {
2653 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2654 Retains[Inst] = S.RRI;
2655 }
2656 S.ClearSequenceProgress();
2657 break;
2658 case S_None:
2659 break;
2660 case S_Retain:
2661 llvm_unreachable("bottom-up pointer in retain state!");
2662 }
2663 return NestingDetected;
2664 }
2665 case IC_AutoreleasepoolPop:
2666 // Conservatively, clear MyStates for all known pointers.
2667 MyStates.clearBottomUpPointers();
2668 return NestingDetected;
2669 case IC_AutoreleasepoolPush:
2670 case IC_None:
2671 // These are irrelevant.
2672 return NestingDetected;
2673 default:
2674 break;
2675 }
2676
2677 // Consider any other possible effects of this instruction on each
2678 // pointer being tracked.
2679 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2680 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2681 const Value *Ptr = MI->first;
2682 if (Ptr == Arg)
2683 continue; // Handled above.
2684 PtrState &S = MI->second;
2685 Sequence Seq = S.GetSeq();
2686
2687 // Check for possible releases.
2688 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002689 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002690 switch (Seq) {
2691 case S_Use:
2692 S.SetSeq(S_CanRelease);
2693 continue;
2694 case S_CanRelease:
2695 case S_Release:
2696 case S_MovableRelease:
2697 case S_Stop:
2698 case S_None:
2699 break;
2700 case S_Retain:
2701 llvm_unreachable("bottom-up pointer in retain state!");
2702 }
2703 }
2704
2705 // Check for possible direct uses.
2706 switch (Seq) {
2707 case S_Release:
2708 case S_MovableRelease:
2709 if (CanUse(Inst, Ptr, PA, Class)) {
2710 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002711 // If this is an invoke instruction, we're scanning it as part of
2712 // one of its successor blocks, since we can't insert code after it
2713 // in its own block, and we don't want to split critical edges.
2714 if (isa<InvokeInst>(Inst))
2715 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2716 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002717 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002718 S.SetSeq(S_Use);
2719 } else if (Seq == S_Release &&
2720 (Class == IC_User || Class == IC_CallOrUser)) {
2721 // Non-movable releases depend on any possible objc pointer use.
2722 S.SetSeq(S_Stop);
2723 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002724 // As above; handle invoke specially.
2725 if (isa<InvokeInst>(Inst))
2726 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2727 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002728 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002729 }
2730 break;
2731 case S_Stop:
2732 if (CanUse(Inst, Ptr, PA, Class))
2733 S.SetSeq(S_Use);
2734 break;
2735 case S_CanRelease:
2736 case S_Use:
2737 case S_None:
2738 break;
2739 case S_Retain:
2740 llvm_unreachable("bottom-up pointer in retain state!");
2741 }
2742 }
2743
2744 return NestingDetected;
2745}
2746
2747bool
John McCall9fbd3182011-06-15 23:37:01 +00002748ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2749 DenseMap<const BasicBlock *, BBState> &BBStates,
2750 MapVector<Value *, RRInfo> &Retains) {
2751 bool NestingDetected = false;
2752 BBState &MyStates = BBStates[BB];
2753
2754 // Merge the states from each successor to compute the initial state
2755 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002756 BBState::edge_iterator SI(MyStates.succ_begin()),
2757 SE(MyStates.succ_end());
2758 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002759 const BasicBlock *Succ = *SI;
2760 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2761 assert(I != BBStates.end());
2762 MyStates.InitFromSucc(I->second);
2763 ++SI;
2764 for (; SI != SE; ++SI) {
2765 Succ = *SI;
2766 I = BBStates.find(Succ);
2767 assert(I != BBStates.end());
2768 MyStates.MergeSucc(I->second);
2769 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002770 }
John McCall9fbd3182011-06-15 23:37:01 +00002771
2772 // Visit all the instructions, bottom-up.
2773 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2774 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002775
2776 // Invoke instructions are visited as part of their successors (below).
2777 if (isa<InvokeInst>(Inst))
2778 continue;
2779
2780 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2781 }
2782
Dan Gohman447989c2012-04-27 18:56:31 +00002783 // If there's a predecessor with an invoke, visit the invoke as if it were
2784 // part of this block, since we can't insert code after an invoke in its own
2785 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002786 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2787 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002788 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002789 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2790 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002791 }
John McCall9fbd3182011-06-15 23:37:01 +00002792
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002793 return NestingDetected;
2794}
John McCall9fbd3182011-06-15 23:37:01 +00002795
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002796bool
2797ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2798 DenseMap<Value *, RRInfo> &Releases,
2799 BBState &MyStates) {
2800 bool NestingDetected = false;
2801 InstructionClass Class = GetInstructionClass(Inst);
2802 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002803
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002804 switch (Class) {
2805 case IC_RetainBlock:
2806 // An objc_retainBlock call with just a use may need to be kept,
2807 // because it may be copying a block from the stack to the heap.
2808 if (!IsRetainBlockOptimizable(Inst))
2809 break;
2810 // FALLTHROUGH
2811 case IC_Retain:
2812 case IC_RetainRV: {
2813 Arg = GetObjCArg(Inst);
2814
2815 PtrState &S = MyStates.getPtrTopDownState(Arg);
2816
2817 // Don't do retain+release tracking for IC_RetainRV, because it's
2818 // better to let it remain as the first instruction after a call.
2819 if (Class != IC_RetainRV) {
2820 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002821 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002822 // hopefully eliminated the second retain, which may allow us to
2823 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002824 // Theoretically we could implement removal of nested retain+release
2825 // pairs by making PtrState hold a stack of states, but this is
2826 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002827 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002828 NestingDetected = true;
2829
Dan Gohman50ade652012-04-25 00:50:46 +00002830 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002831 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002832 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002833 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002834 }
John McCall9fbd3182011-06-15 23:37:01 +00002835
Dan Gohman230768b2012-09-04 23:16:20 +00002836 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002837
2838 // A retain can be a potential use; procede to the generic checking
2839 // code below.
2840 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002841 }
2842 case IC_Release: {
2843 Arg = GetObjCArg(Inst);
2844
2845 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00002846 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002847
2848 switch (S.GetSeq()) {
2849 case S_Retain:
2850 case S_CanRelease:
2851 S.RRI.ReverseInsertPts.clear();
2852 // FALL THROUGH
2853 case S_Use:
2854 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2855 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2856 Releases[Inst] = S.RRI;
2857 S.ClearSequenceProgress();
2858 break;
2859 case S_None:
2860 break;
2861 case S_Stop:
2862 case S_Release:
2863 case S_MovableRelease:
2864 llvm_unreachable("top-down pointer in release state!");
2865 }
2866 break;
2867 }
2868 case IC_AutoreleasepoolPop:
2869 // Conservatively, clear MyStates for all known pointers.
2870 MyStates.clearTopDownPointers();
2871 return NestingDetected;
2872 case IC_AutoreleasepoolPush:
2873 case IC_None:
2874 // These are irrelevant.
2875 return NestingDetected;
2876 default:
2877 break;
2878 }
2879
2880 // Consider any other possible effects of this instruction on each
2881 // pointer being tracked.
2882 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2883 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2884 const Value *Ptr = MI->first;
2885 if (Ptr == Arg)
2886 continue; // Handled above.
2887 PtrState &S = MI->second;
2888 Sequence Seq = S.GetSeq();
2889
2890 // Check for possible releases.
2891 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002892 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002893 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002894 case S_Retain:
2895 S.SetSeq(S_CanRelease);
2896 assert(S.RRI.ReverseInsertPts.empty());
2897 S.RRI.ReverseInsertPts.insert(Inst);
2898
2899 // One call can't cause a transition from S_Retain to S_CanRelease
2900 // and S_CanRelease to S_Use. If we've made the first transition,
2901 // we're done.
2902 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002903 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002904 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00002905 case S_None:
2906 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002907 case S_Stop:
2908 case S_Release:
2909 case S_MovableRelease:
2910 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00002911 }
2912 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002913
2914 // Check for possible direct uses.
2915 switch (Seq) {
2916 case S_CanRelease:
2917 if (CanUse(Inst, Ptr, PA, Class))
2918 S.SetSeq(S_Use);
2919 break;
2920 case S_Retain:
2921 case S_Use:
2922 case S_None:
2923 break;
2924 case S_Stop:
2925 case S_Release:
2926 case S_MovableRelease:
2927 llvm_unreachable("top-down pointer in release state!");
2928 }
John McCall9fbd3182011-06-15 23:37:01 +00002929 }
2930
2931 return NestingDetected;
2932}
2933
2934bool
2935ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2936 DenseMap<const BasicBlock *, BBState> &BBStates,
2937 DenseMap<Value *, RRInfo> &Releases) {
2938 bool NestingDetected = false;
2939 BBState &MyStates = BBStates[BB];
2940
2941 // Merge the states from each predecessor to compute the initial state
2942 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002943 BBState::edge_iterator PI(MyStates.pred_begin()),
2944 PE(MyStates.pred_end());
2945 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002946 const BasicBlock *Pred = *PI;
2947 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2948 assert(I != BBStates.end());
2949 MyStates.InitFromPred(I->second);
2950 ++PI;
2951 for (; PI != PE; ++PI) {
2952 Pred = *PI;
2953 I = BBStates.find(Pred);
2954 assert(I != BBStates.end());
2955 MyStates.MergePred(I->second);
2956 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002957 }
John McCall9fbd3182011-06-15 23:37:01 +00002958
2959 // Visit all the instructions, top-down.
2960 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2961 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002962 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00002963 }
2964
2965 CheckForCFGHazards(BB, BBStates, MyStates);
2966 return NestingDetected;
2967}
2968
Dan Gohman59a1c932011-12-12 19:42:25 +00002969static void
2970ComputePostOrders(Function &F,
2971 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002972 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2973 unsigned NoObjCARCExceptionsMDKind,
2974 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00002975 /// Visited - The visited set, for doing DFS walks.
2976 SmallPtrSet<BasicBlock *, 16> Visited;
2977
2978 // Do DFS, computing the PostOrder.
2979 SmallPtrSet<BasicBlock *, 16> OnStack;
2980 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002981
2982 // Functions always have exactly one entry block, and we don't have
2983 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00002984 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00002985 BBState &MyStates = BBStates[EntryBB];
2986 MyStates.SetAsEntry();
2987 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2988 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00002989 Visited.insert(EntryBB);
2990 OnStack.insert(EntryBB);
2991 do {
2992 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002993 BasicBlock *CurrBB = SuccStack.back().first;
2994 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2995 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00002996
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002997 // If the terminator is an invoke marked with the
2998 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2999 // ignored, for ARC purposes.
3000 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3001 --SE;
3002
3003 while (SuccStack.back().second != SE) {
3004 BasicBlock *SuccBB = *SuccStack.back().second++;
3005 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003006 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3007 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003008 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003009 BBState &SuccStates = BBStates[SuccBB];
3010 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003011 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003012 goto dfs_next_succ;
3013 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003014
3015 if (!OnStack.count(SuccBB)) {
3016 BBStates[CurrBB].addSucc(SuccBB);
3017 BBStates[SuccBB].addPred(CurrBB);
3018 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003019 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003020 OnStack.erase(CurrBB);
3021 PostOrder.push_back(CurrBB);
3022 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003023 } while (!SuccStack.empty());
3024
3025 Visited.clear();
3026
Dan Gohman59a1c932011-12-12 19:42:25 +00003027 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003028 // Functions may have many exits, and there also blocks which we treat
3029 // as exits due to ignored edges.
3030 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3031 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3032 BasicBlock *ExitBB = I;
3033 BBState &MyStates = BBStates[ExitBB];
3034 if (!MyStates.isExit())
3035 continue;
3036
Dan Gohman447989c2012-04-27 18:56:31 +00003037 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003038
3039 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003040 Visited.insert(ExitBB);
3041 while (!PredStack.empty()) {
3042 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003043 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3044 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003045 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003046 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003047 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003048 goto reverse_dfs_next_succ;
3049 }
3050 }
3051 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3052 }
3053 }
3054}
3055
John McCall9fbd3182011-06-15 23:37:01 +00003056// Visit - Visit the function both top-down and bottom-up.
3057bool
3058ObjCARCOpt::Visit(Function &F,
3059 DenseMap<const BasicBlock *, BBState> &BBStates,
3060 MapVector<Value *, RRInfo> &Retains,
3061 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003062
3063 // Use reverse-postorder traversals, because we magically know that loops
3064 // will be well behaved, i.e. they won't repeatedly call retain on a single
3065 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3066 // class here because we want the reverse-CFG postorder to consider each
3067 // function exit point, and we want to ignore selected cycle edges.
3068 SmallVector<BasicBlock *, 16> PostOrder;
3069 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003070 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3071 NoObjCARCExceptionsMDKind,
3072 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003073
3074 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003075 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003076 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003077 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3078 I != E; ++I)
3079 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003080
Dan Gohman59a1c932011-12-12 19:42:25 +00003081 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003082 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003083 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3084 PostOrder.rbegin(), E = PostOrder.rend();
3085 I != E; ++I)
3086 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003087
3088 return TopDownNestingDetected && BottomUpNestingDetected;
3089}
3090
3091/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3092void ObjCARCOpt::MoveCalls(Value *Arg,
3093 RRInfo &RetainsToMove,
3094 RRInfo &ReleasesToMove,
3095 MapVector<Value *, RRInfo> &Retains,
3096 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003097 SmallVectorImpl<Instruction *> &DeadInsts,
3098 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003099 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003100 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003101
3102 // Insert the new retain and release calls.
3103 for (SmallPtrSet<Instruction *, 2>::const_iterator
3104 PI = ReleasesToMove.ReverseInsertPts.begin(),
3105 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3106 Instruction *InsertPt = *PI;
3107 Value *MyArg = ArgTy == ParamTy ? Arg :
3108 new BitCastInst(Arg, ParamTy, "", InsertPt);
3109 CallInst *Call =
3110 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003111 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003112 MyArg, "", InsertPt);
3113 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003114 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003115 Call->setMetadata(CopyOnEscapeMDKind,
3116 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003117 else
John McCall9fbd3182011-06-15 23:37:01 +00003118 Call->setTailCall();
3119 }
3120 for (SmallPtrSet<Instruction *, 2>::const_iterator
3121 PI = RetainsToMove.ReverseInsertPts.begin(),
3122 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003123 Instruction *InsertPt = *PI;
3124 Value *MyArg = ArgTy == ParamTy ? Arg :
3125 new BitCastInst(Arg, ParamTy, "", InsertPt);
3126 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3127 "", InsertPt);
3128 // Attach a clang.imprecise_release metadata tag, if appropriate.
3129 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3130 Call->setMetadata(ImpreciseReleaseMDKind, M);
3131 Call->setDoesNotThrow();
3132 if (ReleasesToMove.IsTailCallRelease)
3133 Call->setTailCall();
John McCall9fbd3182011-06-15 23:37:01 +00003134 }
3135
3136 // Delete the original retain and release calls.
3137 for (SmallPtrSet<Instruction *, 2>::const_iterator
3138 AI = RetainsToMove.Calls.begin(),
3139 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3140 Instruction *OrigRetain = *AI;
3141 Retains.blot(OrigRetain);
3142 DeadInsts.push_back(OrigRetain);
3143 }
3144 for (SmallPtrSet<Instruction *, 2>::const_iterator
3145 AI = ReleasesToMove.Calls.begin(),
3146 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3147 Instruction *OrigRelease = *AI;
3148 Releases.erase(OrigRelease);
3149 DeadInsts.push_back(OrigRelease);
3150 }
3151}
3152
Dan Gohmand6bf2012012-04-13 18:57:48 +00003153/// PerformCodePlacement - Identify pairings between the retains and releases,
3154/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003155bool
3156ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3157 &BBStates,
3158 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003159 DenseMap<Value *, RRInfo> &Releases,
3160 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003161 bool AnyPairsCompletelyEliminated = false;
3162 RRInfo RetainsToMove;
3163 RRInfo ReleasesToMove;
3164 SmallVector<Instruction *, 4> NewRetains;
3165 SmallVector<Instruction *, 4> NewReleases;
3166 SmallVector<Instruction *, 8> DeadInsts;
3167
Dan Gohmand6bf2012012-04-13 18:57:48 +00003168 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003169 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003170 E = Retains.end(); I != E; ++I) {
3171 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003172 if (!V) continue; // blotted
3173
3174 Instruction *Retain = cast<Instruction>(V);
3175 Value *Arg = GetObjCArg(Retain);
3176
Dan Gohman79522dc2012-01-13 00:39:07 +00003177 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003178 // not being managed by ObjC reference counting, so we can delete pairs
3179 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003180 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003181
Dan Gohman1b31ea82011-08-22 17:29:11 +00003182 // A constant pointer can't be pointing to an object on the heap. It may
3183 // be reference-counted, but it won't be deleted.
3184 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3185 if (const GlobalVariable *GV =
3186 dyn_cast<GlobalVariable>(
3187 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3188 if (GV->isConstant())
3189 KnownSafe = true;
3190
John McCall9fbd3182011-06-15 23:37:01 +00003191 // If a pair happens in a region where it is known that the reference count
3192 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003193 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003194
3195 // Connect the dots between the top-down-collected RetainsToMove and
3196 // bottom-up-collected ReleasesToMove to form sets of related calls.
3197 // This is an iterative process so that we connect multiple releases
3198 // to multiple retains if needed.
3199 unsigned OldDelta = 0;
3200 unsigned NewDelta = 0;
3201 unsigned OldCount = 0;
3202 unsigned NewCount = 0;
3203 bool FirstRelease = true;
3204 bool FirstRetain = true;
3205 NewRetains.push_back(Retain);
3206 for (;;) {
3207 for (SmallVectorImpl<Instruction *>::const_iterator
3208 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3209 Instruction *NewRetain = *NI;
3210 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3211 assert(It != Retains.end());
3212 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003213 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003214 for (SmallPtrSet<Instruction *, 2>::const_iterator
3215 LI = NewRetainRRI.Calls.begin(),
3216 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3217 Instruction *NewRetainRelease = *LI;
3218 DenseMap<Value *, RRInfo>::const_iterator Jt =
3219 Releases.find(NewRetainRelease);
3220 if (Jt == Releases.end())
3221 goto next_retain;
3222 const RRInfo &NewRetainReleaseRRI = Jt->second;
3223 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3224 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3225 OldDelta -=
3226 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3227
3228 // Merge the ReleaseMetadata and IsTailCallRelease values.
3229 if (FirstRelease) {
3230 ReleasesToMove.ReleaseMetadata =
3231 NewRetainReleaseRRI.ReleaseMetadata;
3232 ReleasesToMove.IsTailCallRelease =
3233 NewRetainReleaseRRI.IsTailCallRelease;
3234 FirstRelease = false;
3235 } else {
3236 if (ReleasesToMove.ReleaseMetadata !=
3237 NewRetainReleaseRRI.ReleaseMetadata)
3238 ReleasesToMove.ReleaseMetadata = 0;
3239 if (ReleasesToMove.IsTailCallRelease !=
3240 NewRetainReleaseRRI.IsTailCallRelease)
3241 ReleasesToMove.IsTailCallRelease = false;
3242 }
3243
3244 // Collect the optimal insertion points.
3245 if (!KnownSafe)
3246 for (SmallPtrSet<Instruction *, 2>::const_iterator
3247 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3248 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3249 RI != RE; ++RI) {
3250 Instruction *RIP = *RI;
3251 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3252 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3253 }
3254 NewReleases.push_back(NewRetainRelease);
3255 }
3256 }
3257 }
3258 NewRetains.clear();
3259 if (NewReleases.empty()) break;
3260
3261 // Back the other way.
3262 for (SmallVectorImpl<Instruction *>::const_iterator
3263 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3264 Instruction *NewRelease = *NI;
3265 DenseMap<Value *, RRInfo>::const_iterator It =
3266 Releases.find(NewRelease);
3267 assert(It != Releases.end());
3268 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003269 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003270 for (SmallPtrSet<Instruction *, 2>::const_iterator
3271 LI = NewReleaseRRI.Calls.begin(),
3272 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3273 Instruction *NewReleaseRetain = *LI;
3274 MapVector<Value *, RRInfo>::const_iterator Jt =
3275 Retains.find(NewReleaseRetain);
3276 if (Jt == Retains.end())
3277 goto next_retain;
3278 const RRInfo &NewReleaseRetainRRI = Jt->second;
3279 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3280 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3281 unsigned PathCount =
3282 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3283 OldDelta += PathCount;
3284 OldCount += PathCount;
3285
3286 // Merge the IsRetainBlock values.
3287 if (FirstRetain) {
3288 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3289 FirstRetain = false;
3290 } else if (ReleasesToMove.IsRetainBlock !=
3291 NewReleaseRetainRRI.IsRetainBlock)
3292 // It's not possible to merge the sequences if one uses
3293 // objc_retain and the other uses objc_retainBlock.
3294 goto next_retain;
3295
3296 // Collect the optimal insertion points.
3297 if (!KnownSafe)
3298 for (SmallPtrSet<Instruction *, 2>::const_iterator
3299 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3300 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3301 RI != RE; ++RI) {
3302 Instruction *RIP = *RI;
3303 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3304 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3305 NewDelta += PathCount;
3306 NewCount += PathCount;
3307 }
3308 }
3309 NewRetains.push_back(NewReleaseRetain);
3310 }
3311 }
3312 }
3313 NewReleases.clear();
3314 if (NewRetains.empty()) break;
3315 }
3316
Dan Gohmane6d5e882011-08-19 00:26:36 +00003317 // If the pointer is known incremented or nested, we can safely delete the
3318 // pair regardless of what's between them.
3319 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003320 RetainsToMove.ReverseInsertPts.clear();
3321 ReleasesToMove.ReverseInsertPts.clear();
3322 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003323 } else {
3324 // Determine whether the new insertion points we computed preserve the
3325 // balance of retain and release calls through the program.
3326 // TODO: If the fully aggressive solution isn't valid, try to find a
3327 // less aggressive solution which is.
3328 if (NewDelta != 0)
3329 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003330 }
3331
3332 // Determine whether the original call points are balanced in the retain and
3333 // release calls through the program. If not, conservatively don't touch
3334 // them.
3335 // TODO: It's theoretically possible to do code motion in this case, as
3336 // long as the existing imbalances are maintained.
3337 if (OldDelta != 0)
3338 goto next_retain;
3339
John McCall9fbd3182011-06-15 23:37:01 +00003340 // Ok, everything checks out and we're all set. Let's move some code!
3341 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003342 assert(OldCount != 0 && "Unreachable code?");
3343 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003344 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003345 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3346 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003347
3348 next_retain:
3349 NewReleases.clear();
3350 NewRetains.clear();
3351 RetainsToMove.clear();
3352 ReleasesToMove.clear();
3353 }
3354
3355 // Now that we're done moving everything, we can delete the newly dead
3356 // instructions, as we no longer need them as insert points.
3357 while (!DeadInsts.empty())
3358 EraseInstruction(DeadInsts.pop_back_val());
3359
3360 return AnyPairsCompletelyEliminated;
3361}
3362
3363/// OptimizeWeakCalls - Weak pointer optimizations.
3364void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3365 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3366 // itself because it uses AliasAnalysis and we need to do provenance
3367 // queries instead.
3368 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3369 Instruction *Inst = &*I++;
3370 InstructionClass Class = GetBasicInstructionClass(Inst);
3371 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3372 continue;
3373
3374 // Delete objc_loadWeak calls with no users.
3375 if (Class == IC_LoadWeak && Inst->use_empty()) {
3376 Inst->eraseFromParent();
3377 continue;
3378 }
3379
3380 // TODO: For now, just look for an earlier available version of this value
3381 // within the same block. Theoretically, we could do memdep-style non-local
3382 // analysis too, but that would want caching. A better approach would be to
3383 // use the technique that EarlyCSE uses.
3384 inst_iterator Current = llvm::prior(I);
3385 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3386 for (BasicBlock::iterator B = CurrentBB->begin(),
3387 J = Current.getInstructionIterator();
3388 J != B; --J) {
3389 Instruction *EarlierInst = &*llvm::prior(J);
3390 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3391 switch (EarlierClass) {
3392 case IC_LoadWeak:
3393 case IC_LoadWeakRetained: {
3394 // If this is loading from the same pointer, replace this load's value
3395 // with that one.
3396 CallInst *Call = cast<CallInst>(Inst);
3397 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3398 Value *Arg = Call->getArgOperand(0);
3399 Value *EarlierArg = EarlierCall->getArgOperand(0);
3400 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3401 case AliasAnalysis::MustAlias:
3402 Changed = true;
3403 // If the load has a builtin retain, insert a plain retain for it.
3404 if (Class == IC_LoadWeakRetained) {
3405 CallInst *CI =
3406 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3407 "", Call);
3408 CI->setTailCall();
3409 }
3410 // Zap the fully redundant load.
3411 Call->replaceAllUsesWith(EarlierCall);
3412 Call->eraseFromParent();
3413 goto clobbered;
3414 case AliasAnalysis::MayAlias:
3415 case AliasAnalysis::PartialAlias:
3416 goto clobbered;
3417 case AliasAnalysis::NoAlias:
3418 break;
3419 }
3420 break;
3421 }
3422 case IC_StoreWeak:
3423 case IC_InitWeak: {
3424 // If this is storing to the same pointer and has the same size etc.
3425 // replace this load's value with the stored value.
3426 CallInst *Call = cast<CallInst>(Inst);
3427 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3428 Value *Arg = Call->getArgOperand(0);
3429 Value *EarlierArg = EarlierCall->getArgOperand(0);
3430 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3431 case AliasAnalysis::MustAlias:
3432 Changed = true;
3433 // If the load has a builtin retain, insert a plain retain for it.
3434 if (Class == IC_LoadWeakRetained) {
3435 CallInst *CI =
3436 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3437 "", Call);
3438 CI->setTailCall();
3439 }
3440 // Zap the fully redundant load.
3441 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3442 Call->eraseFromParent();
3443 goto clobbered;
3444 case AliasAnalysis::MayAlias:
3445 case AliasAnalysis::PartialAlias:
3446 goto clobbered;
3447 case AliasAnalysis::NoAlias:
3448 break;
3449 }
3450 break;
3451 }
3452 case IC_MoveWeak:
3453 case IC_CopyWeak:
3454 // TOOD: Grab the copied value.
3455 goto clobbered;
3456 case IC_AutoreleasepoolPush:
3457 case IC_None:
3458 case IC_User:
3459 // Weak pointers are only modified through the weak entry points
3460 // (and arbitrary calls, which could call the weak entry points).
3461 break;
3462 default:
3463 // Anything else could modify the weak pointer.
3464 goto clobbered;
3465 }
3466 }
3467 clobbered:;
3468 }
3469
3470 // Then, for each destroyWeak with an alloca operand, check to see if
3471 // the alloca and all its users can be zapped.
3472 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3473 Instruction *Inst = &*I++;
3474 InstructionClass Class = GetBasicInstructionClass(Inst);
3475 if (Class != IC_DestroyWeak)
3476 continue;
3477
3478 CallInst *Call = cast<CallInst>(Inst);
3479 Value *Arg = Call->getArgOperand(0);
3480 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3481 for (Value::use_iterator UI = Alloca->use_begin(),
3482 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003483 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003484 switch (GetBasicInstructionClass(UserInst)) {
3485 case IC_InitWeak:
3486 case IC_StoreWeak:
3487 case IC_DestroyWeak:
3488 continue;
3489 default:
3490 goto done;
3491 }
3492 }
3493 Changed = true;
3494 for (Value::use_iterator UI = Alloca->use_begin(),
3495 UE = Alloca->use_end(); UI != UE; ) {
3496 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003497 switch (GetBasicInstructionClass(UserInst)) {
3498 case IC_InitWeak:
3499 case IC_StoreWeak:
3500 // These functions return their second argument.
3501 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3502 break;
3503 case IC_DestroyWeak:
3504 // No return value.
3505 break;
3506 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003507 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003508 }
John McCall9fbd3182011-06-15 23:37:01 +00003509 UserInst->eraseFromParent();
3510 }
3511 Alloca->eraseFromParent();
3512 done:;
3513 }
3514 }
3515}
3516
3517/// OptimizeSequences - Identify program paths which execute sequences of
3518/// retains and releases which can be eliminated.
3519bool ObjCARCOpt::OptimizeSequences(Function &F) {
3520 /// Releases, Retains - These are used to store the results of the main flow
3521 /// analysis. These use Value* as the key instead of Instruction* so that the
3522 /// map stays valid when we get around to rewriting code and calls get
3523 /// replaced by arguments.
3524 DenseMap<Value *, RRInfo> Releases;
3525 MapVector<Value *, RRInfo> Retains;
3526
3527 /// BBStates, This is used during the traversal of the function to track the
3528 /// states for each identified object at each block.
3529 DenseMap<const BasicBlock *, BBState> BBStates;
3530
3531 // Analyze the CFG of the function, and all instructions.
3532 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3533
3534 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003535 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3536 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003537}
3538
3539/// OptimizeReturns - Look for this pattern:
3540///
3541/// %call = call i8* @something(...)
3542/// %2 = call i8* @objc_retain(i8* %call)
3543/// %3 = call i8* @objc_autorelease(i8* %2)
3544/// ret i8* %3
3545///
3546/// And delete the retain and autorelease.
3547///
3548/// Otherwise if it's just this:
3549///
3550/// %3 = call i8* @objc_autorelease(i8* %2)
3551/// ret i8* %3
3552///
3553/// convert the autorelease to autoreleaseRV.
3554void ObjCARCOpt::OptimizeReturns(Function &F) {
3555 if (!F.getReturnType()->isPointerTy())
3556 return;
3557
3558 SmallPtrSet<Instruction *, 4> DependingInstructions;
3559 SmallPtrSet<const BasicBlock *, 4> Visited;
3560 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3561 BasicBlock *BB = FI;
3562 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3563 if (!Ret) continue;
3564
3565 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3566 FindDependencies(NeedsPositiveRetainCount, Arg,
3567 BB, Ret, DependingInstructions, Visited, PA);
3568 if (DependingInstructions.size() != 1)
3569 goto next_block;
3570
3571 {
3572 CallInst *Autorelease =
3573 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3574 if (!Autorelease)
3575 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003576 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003577 if (!IsAutorelease(AutoreleaseClass))
3578 goto next_block;
3579 if (GetObjCArg(Autorelease) != Arg)
3580 goto next_block;
3581
3582 DependingInstructions.clear();
3583 Visited.clear();
3584
3585 // Check that there is nothing that can affect the reference
3586 // count between the autorelease and the retain.
3587 FindDependencies(CanChangeRetainCount, Arg,
3588 BB, Autorelease, DependingInstructions, Visited, PA);
3589 if (DependingInstructions.size() != 1)
3590 goto next_block;
3591
3592 {
3593 CallInst *Retain =
3594 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3595
3596 // Check that we found a retain with the same argument.
3597 if (!Retain ||
3598 !IsRetain(GetBasicInstructionClass(Retain)) ||
3599 GetObjCArg(Retain) != Arg)
3600 goto next_block;
3601
3602 DependingInstructions.clear();
3603 Visited.clear();
3604
3605 // Convert the autorelease to an autoreleaseRV, since it's
3606 // returning the value.
3607 if (AutoreleaseClass == IC_Autorelease) {
3608 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3609 AutoreleaseClass = IC_AutoreleaseRV;
3610 }
3611
3612 // Check that there is nothing that can affect the reference
3613 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003614 // Note that Retain need not be in BB.
3615 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003616 DependingInstructions, Visited, PA);
3617 if (DependingInstructions.size() != 1)
3618 goto next_block;
3619
3620 {
3621 CallInst *Call =
3622 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3623
3624 // Check that the pointer is the return value of the call.
3625 if (!Call || Arg != Call)
3626 goto next_block;
3627
3628 // Check that the call is a regular call.
3629 InstructionClass Class = GetBasicInstructionClass(Call);
3630 if (Class != IC_CallOrUser && Class != IC_Call)
3631 goto next_block;
3632
3633 // If so, we can zap the retain and autorelease.
3634 Changed = true;
3635 ++NumRets;
3636 EraseInstruction(Retain);
3637 EraseInstruction(Autorelease);
3638 }
3639 }
3640 }
3641
3642 next_block:
3643 DependingInstructions.clear();
3644 Visited.clear();
3645 }
3646}
3647
3648bool ObjCARCOpt::doInitialization(Module &M) {
3649 if (!EnableARCOpts)
3650 return false;
3651
Dan Gohmand6bf2012012-04-13 18:57:48 +00003652 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003653 Run = ModuleHasARC(M);
3654 if (!Run)
3655 return false;
3656
John McCall9fbd3182011-06-15 23:37:01 +00003657 // Identify the imprecise release metadata kind.
3658 ImpreciseReleaseMDKind =
3659 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003660 CopyOnEscapeMDKind =
3661 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003662 NoObjCARCExceptionsMDKind =
3663 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003664
John McCall9fbd3182011-06-15 23:37:01 +00003665 // Intuitively, objc_retain and others are nocapture, however in practice
3666 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003667 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003668
3669 // These are initialized lazily.
3670 RetainRVCallee = 0;
3671 AutoreleaseRVCallee = 0;
3672 ReleaseCallee = 0;
3673 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003674 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003675 AutoreleaseCallee = 0;
3676
3677 return false;
3678}
3679
3680bool ObjCARCOpt::runOnFunction(Function &F) {
3681 if (!EnableARCOpts)
3682 return false;
3683
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003684 // If nothing in the Module uses ARC, don't do anything.
3685 if (!Run)
3686 return false;
3687
John McCall9fbd3182011-06-15 23:37:01 +00003688 Changed = false;
3689
3690 PA.setAA(&getAnalysis<AliasAnalysis>());
3691
3692 // This pass performs several distinct transformations. As a compile-time aid
3693 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3694 // library functions aren't declared.
3695
3696 // Preliminary optimizations. This also computs UsedInThisFunction.
3697 OptimizeIndividualCalls(F);
3698
3699 // Optimizations for weak pointers.
3700 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3701 (1 << IC_LoadWeakRetained) |
3702 (1 << IC_StoreWeak) |
3703 (1 << IC_InitWeak) |
3704 (1 << IC_CopyWeak) |
3705 (1 << IC_MoveWeak) |
3706 (1 << IC_DestroyWeak)))
3707 OptimizeWeakCalls(F);
3708
3709 // Optimizations for retain+release pairs.
3710 if (UsedInThisFunction & ((1 << IC_Retain) |
3711 (1 << IC_RetainRV) |
3712 (1 << IC_RetainBlock)))
3713 if (UsedInThisFunction & (1 << IC_Release))
3714 // Run OptimizeSequences until it either stops making changes or
3715 // no retain+release pair nesting is detected.
3716 while (OptimizeSequences(F)) {}
3717
3718 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003719 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3720 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003721 OptimizeReturns(F);
3722
3723 return Changed;
3724}
3725
3726void ObjCARCOpt::releaseMemory() {
3727 PA.clear();
3728}
3729
3730//===----------------------------------------------------------------------===//
3731// ARC contraction.
3732//===----------------------------------------------------------------------===//
3733
3734// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3735// dominated by single calls.
3736
3737#include "llvm/Operator.h"
3738#include "llvm/InlineAsm.h"
3739#include "llvm/Analysis/Dominators.h"
3740
3741STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3742
3743namespace {
3744 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3745 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3746 class ObjCARCContract : public FunctionPass {
3747 bool Changed;
3748 AliasAnalysis *AA;
3749 DominatorTree *DT;
3750 ProvenanceAnalysis PA;
3751
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003752 /// Run - A flag indicating whether this optimization pass should run.
3753 bool Run;
3754
John McCall9fbd3182011-06-15 23:37:01 +00003755 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3756 /// functions, for use in creating calls to them. These are initialized
3757 /// lazily to avoid cluttering up the Module with unused declarations.
3758 Constant *StoreStrongCallee,
3759 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3760
3761 /// RetainRVMarker - The inline asm string to insert between calls and
3762 /// RetainRV calls to make the optimization work on targets which need it.
3763 const MDString *RetainRVMarker;
3764
Dan Gohman0cdece42012-01-19 19:14:36 +00003765 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3766 /// at the end of walking the function we have found no alloca
3767 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003768 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003769
John McCall9fbd3182011-06-15 23:37:01 +00003770 Constant *getStoreStrongCallee(Module *M);
3771 Constant *getRetainAutoreleaseCallee(Module *M);
3772 Constant *getRetainAutoreleaseRVCallee(Module *M);
3773
3774 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3775 InstructionClass Class,
3776 SmallPtrSet<Instruction *, 4>
3777 &DependingInstructions,
3778 SmallPtrSet<const BasicBlock *, 4>
3779 &Visited);
3780
3781 void ContractRelease(Instruction *Release,
3782 inst_iterator &Iter);
3783
3784 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3785 virtual bool doInitialization(Module &M);
3786 virtual bool runOnFunction(Function &F);
3787
3788 public:
3789 static char ID;
3790 ObjCARCContract() : FunctionPass(ID) {
3791 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3792 }
3793 };
3794}
3795
3796char ObjCARCContract::ID = 0;
3797INITIALIZE_PASS_BEGIN(ObjCARCContract,
3798 "objc-arc-contract", "ObjC ARC contraction", false, false)
3799INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3800INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3801INITIALIZE_PASS_END(ObjCARCContract,
3802 "objc-arc-contract", "ObjC ARC contraction", false, false)
3803
3804Pass *llvm::createObjCARCContractPass() {
3805 return new ObjCARCContract();
3806}
3807
3808void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3809 AU.addRequired<AliasAnalysis>();
3810 AU.addRequired<DominatorTree>();
3811 AU.setPreservesCFG();
3812}
3813
3814Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3815 if (!StoreStrongCallee) {
3816 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003817 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3818 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003819 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00003820
Dan Gohman0daef3d2012-05-08 23:39:44 +00003821 AttrListPtr Attributes = AttrListPtr()
3822 .addAttr(~0u, Attribute::NoUnwind)
3823 .addAttr(1, Attribute::NoCapture);
John McCall9fbd3182011-06-15 23:37:01 +00003824
3825 StoreStrongCallee =
3826 M->getOrInsertFunction(
3827 "objc_storeStrong",
3828 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3829 Attributes);
3830 }
3831 return StoreStrongCallee;
3832}
3833
3834Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3835 if (!RetainAutoreleaseCallee) {
3836 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003837 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003838 Type *Params[] = { I8X };
3839 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3840 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00003841 RetainAutoreleaseCallee =
3842 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3843 }
3844 return RetainAutoreleaseCallee;
3845}
3846
3847Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3848 if (!RetainAutoreleaseRVCallee) {
3849 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003850 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003851 Type *Params[] = { I8X };
3852 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3853 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
John McCall9fbd3182011-06-15 23:37:01 +00003854 RetainAutoreleaseRVCallee =
3855 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3856 Attributes);
3857 }
3858 return RetainAutoreleaseRVCallee;
3859}
3860
Dan Gohman447989c2012-04-27 18:56:31 +00003861/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00003862bool
3863ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3864 InstructionClass Class,
3865 SmallPtrSet<Instruction *, 4>
3866 &DependingInstructions,
3867 SmallPtrSet<const BasicBlock *, 4>
3868 &Visited) {
3869 const Value *Arg = GetObjCArg(Autorelease);
3870
3871 // Check that there are no instructions between the retain and the autorelease
3872 // (such as an autorelease_pop) which may change the count.
3873 CallInst *Retain = 0;
3874 if (Class == IC_AutoreleaseRV)
3875 FindDependencies(RetainAutoreleaseRVDep, Arg,
3876 Autorelease->getParent(), Autorelease,
3877 DependingInstructions, Visited, PA);
3878 else
3879 FindDependencies(RetainAutoreleaseDep, Arg,
3880 Autorelease->getParent(), Autorelease,
3881 DependingInstructions, Visited, PA);
3882
3883 Visited.clear();
3884 if (DependingInstructions.size() != 1) {
3885 DependingInstructions.clear();
3886 return false;
3887 }
3888
3889 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3890 DependingInstructions.clear();
3891
3892 if (!Retain ||
3893 GetBasicInstructionClass(Retain) != IC_Retain ||
3894 GetObjCArg(Retain) != Arg)
3895 return false;
3896
3897 Changed = true;
3898 ++NumPeeps;
3899
3900 if (Class == IC_AutoreleaseRV)
3901 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3902 else
3903 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3904
3905 EraseInstruction(Autorelease);
3906 return true;
3907}
3908
3909/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3910/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3911/// the instructions don't always appear in order, and there may be unrelated
3912/// intervening instructions.
3913void ObjCARCContract::ContractRelease(Instruction *Release,
3914 inst_iterator &Iter) {
3915 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003916 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003917
3918 // For now, require everything to be in one basic block.
3919 BasicBlock *BB = Release->getParent();
3920 if (Load->getParent() != BB) return;
3921
Dan Gohman4670dac2012-05-08 23:34:08 +00003922 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00003923 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00003924 ++I;
3925 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00003926 StoreInst *Store = 0;
3927 bool SawRelease = false;
3928 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00003929 if (I == End)
3930 return;
3931
Dan Gohman4670dac2012-05-08 23:34:08 +00003932 Instruction *Inst = I;
3933 if (Inst == Release) {
3934 SawRelease = true;
3935 continue;
3936 }
3937
3938 InstructionClass Class = GetBasicInstructionClass(Inst);
3939
3940 // Unrelated retains are harmless.
3941 if (IsRetain(Class))
3942 continue;
3943
3944 if (Store) {
3945 // The store is the point where we're going to put the objc_storeStrong,
3946 // so make sure there are no uses after it.
3947 if (CanUse(Inst, Load, PA, Class))
3948 return;
3949 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3950 // We are moving the load down to the store, so check for anything
3951 // else which writes to the memory between the load and the store.
3952 Store = dyn_cast<StoreInst>(Inst);
3953 if (!Store || !Store->isSimple()) return;
3954 if (Store->getPointerOperand() != Loc.Ptr) return;
3955 }
3956 }
John McCall9fbd3182011-06-15 23:37:01 +00003957
3958 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3959
3960 // Walk up to find the retain.
3961 I = Store;
3962 BasicBlock::iterator Begin = BB->begin();
3963 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3964 --I;
3965 Instruction *Retain = I;
3966 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3967 if (GetObjCArg(Retain) != New) return;
3968
3969 Changed = true;
3970 ++NumStoreStrongs;
3971
3972 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003973 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3974 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003975
3976 Value *Args[] = { Load->getPointerOperand(), New };
3977 if (Args[0]->getType() != I8XX)
3978 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3979 if (Args[1]->getType() != I8X)
3980 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3981 CallInst *StoreStrong =
3982 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003983 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003984 StoreStrong->setDoesNotThrow();
3985 StoreStrong->setDebugLoc(Store->getDebugLoc());
3986
Dan Gohman0cdece42012-01-19 19:14:36 +00003987 // We can't set the tail flag yet, because we haven't yet determined
3988 // whether there are any escaping allocas. Remember this call, so that
3989 // we can set the tail flag once we know it's safe.
3990 StoreStrongCalls.insert(StoreStrong);
3991
John McCall9fbd3182011-06-15 23:37:01 +00003992 if (&*Iter == Store) ++Iter;
3993 Store->eraseFromParent();
3994 Release->eraseFromParent();
3995 EraseInstruction(Retain);
3996 if (Load->use_empty())
3997 Load->eraseFromParent();
3998}
3999
4000bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004001 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004002 Run = ModuleHasARC(M);
4003 if (!Run)
4004 return false;
4005
John McCall9fbd3182011-06-15 23:37:01 +00004006 // These are initialized lazily.
4007 StoreStrongCallee = 0;
4008 RetainAutoreleaseCallee = 0;
4009 RetainAutoreleaseRVCallee = 0;
4010
4011 // Initialize RetainRVMarker.
4012 RetainRVMarker = 0;
4013 if (NamedMDNode *NMD =
4014 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4015 if (NMD->getNumOperands() == 1) {
4016 const MDNode *N = NMD->getOperand(0);
4017 if (N->getNumOperands() == 1)
4018 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4019 RetainRVMarker = S;
4020 }
4021
4022 return false;
4023}
4024
4025bool ObjCARCContract::runOnFunction(Function &F) {
4026 if (!EnableARCOpts)
4027 return false;
4028
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004029 // If nothing in the Module uses ARC, don't do anything.
4030 if (!Run)
4031 return false;
4032
John McCall9fbd3182011-06-15 23:37:01 +00004033 Changed = false;
4034 AA = &getAnalysis<AliasAnalysis>();
4035 DT = &getAnalysis<DominatorTree>();
4036
4037 PA.setAA(&getAnalysis<AliasAnalysis>());
4038
Dan Gohman0cdece42012-01-19 19:14:36 +00004039 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4040 // keyword. Be conservative if the function has variadic arguments.
4041 // It seems that functions which "return twice" are also unsafe for the
4042 // "tail" argument, because they are setjmp, which could need to
4043 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004044 bool TailOkForStoreStrongs = !F.isVarArg() &&
4045 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004046
John McCall9fbd3182011-06-15 23:37:01 +00004047 // For ObjC library calls which return their argument, replace uses of the
4048 // argument with uses of the call return value, if it dominates the use. This
4049 // reduces register pressure.
4050 SmallPtrSet<Instruction *, 4> DependingInstructions;
4051 SmallPtrSet<const BasicBlock *, 4> Visited;
4052 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4053 Instruction *Inst = &*I++;
4054
4055 // Only these library routines return their argument. In particular,
4056 // objc_retainBlock does not necessarily return its argument.
4057 InstructionClass Class = GetBasicInstructionClass(Inst);
4058 switch (Class) {
4059 case IC_Retain:
4060 case IC_FusedRetainAutorelease:
4061 case IC_FusedRetainAutoreleaseRV:
4062 break;
4063 case IC_Autorelease:
4064 case IC_AutoreleaseRV:
4065 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4066 continue;
4067 break;
4068 case IC_RetainRV: {
4069 // If we're compiling for a target which needs a special inline-asm
4070 // marker to do the retainAutoreleasedReturnValue optimization,
4071 // insert it now.
4072 if (!RetainRVMarker)
4073 break;
4074 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004075 BasicBlock *InstParent = Inst->getParent();
4076
4077 // Step up to see if the call immediately precedes the RetainRV call.
4078 // If it's an invoke, we have to cross a block boundary. And we have
4079 // to carefully dodge no-op instructions.
4080 do {
4081 if (&*BBI == InstParent->begin()) {
4082 BasicBlock *Pred = InstParent->getSinglePredecessor();
4083 if (!Pred)
4084 goto decline_rv_optimization;
4085 BBI = Pred->getTerminator();
4086 break;
4087 }
4088 --BBI;
4089 } while (isNoopInstruction(BBI));
4090
John McCall9fbd3182011-06-15 23:37:01 +00004091 if (&*BBI == GetObjCArg(Inst)) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004092 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004093 InlineAsm *IA =
4094 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4095 /*isVarArg=*/false),
4096 RetainRVMarker->getString(),
4097 /*Constraints=*/"", /*hasSideEffects=*/true);
4098 CallInst::Create(IA, "", Inst);
4099 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004100 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004101 break;
4102 }
4103 case IC_InitWeak: {
4104 // objc_initWeak(p, null) => *p = null
4105 CallInst *CI = cast<CallInst>(Inst);
4106 if (isNullOrUndef(CI->getArgOperand(1))) {
4107 Value *Null =
4108 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4109 Changed = true;
4110 new StoreInst(Null, CI->getArgOperand(0), CI);
4111 CI->replaceAllUsesWith(Null);
4112 CI->eraseFromParent();
4113 }
4114 continue;
4115 }
4116 case IC_Release:
4117 ContractRelease(Inst, I);
4118 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004119 case IC_User:
4120 // Be conservative if the function has any alloca instructions.
4121 // Technically we only care about escaping alloca instructions,
4122 // but this is sufficient to handle some interesting cases.
4123 if (isa<AllocaInst>(Inst))
4124 TailOkForStoreStrongs = false;
4125 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004126 default:
4127 continue;
4128 }
4129
4130 // Don't use GetObjCArg because we don't want to look through bitcasts
4131 // and such; to do the replacement, the argument must have type i8*.
4132 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4133 for (;;) {
4134 // If we're compiling bugpointed code, don't get in trouble.
4135 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4136 break;
4137 // Look through the uses of the pointer.
4138 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4139 UI != UE; ) {
4140 Use &U = UI.getUse();
4141 unsigned OperandNo = UI.getOperandNo();
4142 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004143
4144 // If the call's return value dominates a use of the call's argument
4145 // value, rewrite the use to use the return value. We check for
4146 // reachability here because an unreachable call is considered to
4147 // trivially dominate itself, which would lead us to rewriting its
4148 // argument in terms of its return value, which would lead to
4149 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004150 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004151 Changed = true;
4152 Instruction *Replacement = Inst;
4153 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004154 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004155 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004156 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4157 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004158 if (Replacement->getType() != UseTy)
4159 Replacement = new BitCastInst(Replacement, UseTy, "",
4160 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004161 // While we're here, rewrite all edges for this PHI, rather
4162 // than just one use at a time, to minimize the number of
4163 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004164 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004165 if (PHI->getIncomingBlock(i) == BB) {
4166 // Keep the UI iterator valid.
4167 if (&PHI->getOperandUse(
4168 PHINode::getOperandNumForIncomingValue(i)) ==
4169 &UI.getUse())
4170 ++UI;
4171 PHI->setIncomingValue(i, Replacement);
4172 }
4173 } else {
4174 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004175 Replacement = new BitCastInst(Replacement, UseTy, "",
4176 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004177 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004178 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004179 }
John McCall9fbd3182011-06-15 23:37:01 +00004180 }
4181
Dan Gohman447989c2012-04-27 18:56:31 +00004182 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004183 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4184 Arg = BI->getOperand(0);
4185 else if (isa<GEPOperator>(Arg) &&
4186 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4187 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4188 else if (isa<GlobalAlias>(Arg) &&
4189 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4190 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4191 else
4192 break;
4193 }
4194 }
4195
Dan Gohman0cdece42012-01-19 19:14:36 +00004196 // If this function has no escaping allocas or suspicious vararg usage,
4197 // objc_storeStrong calls can be marked with the "tail" keyword.
4198 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004199 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004200 E = StoreStrongCalls.end(); I != E; ++I)
4201 (*I)->setTailCall();
4202 StoreStrongCalls.clear();
4203
John McCall9fbd3182011-06-15 23:37:01 +00004204 return Changed;
4205}