blob: a3f9ad31c68ba2c1884eeaa99e85cf80ef0c92ee [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//===----------------------------------------------------------------------===//
Michael Gottesman81c61212013-01-14 00:35:14 +00009/// \file
10/// This file defines ObjC ARC optimizations. ARC stands for Automatic
11/// Reference Counting and is a system for managing reference counts for objects
12/// in Objective C.
13///
14/// The optimizations performed include elimination of redundant, partially
15/// redundant, and inconsequential reference count operations, elimination of
16/// redundant weak pointer operations, pattern-matching and replacement of
17/// low-level operations into higher-level operations, and numerous minor
18/// simplifications.
19///
20/// This file also defines a simple ARC-aware AliasAnalysis.
21///
22/// WARNING: This file knows about certain library functions. It recognizes them
23/// by name, and hardwires knowledge of their semantics.
24///
25/// WARNING: This file knows about how certain Objective-C library functions are
26/// used. Naive LLVM IR transformations which would otherwise be
27/// behavior-preserving may break these assumptions.
28///
John McCall9fbd3182011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCall9fbd3182011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesman6056b852013-01-13 22:12:06 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruth58a2cbe2013-01-02 10:22:59 +000035#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000037using namespace llvm;
38
Michael Gottesman81c61212013-01-14 00:35:14 +000039/// \brief A handy option to enable/disable all optimizations in this file.
John McCall9fbd3182011-06-15 23:37:01 +000040static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
Michael Gottesman81c61212013-01-14 00:35:14 +000042/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
43/// @{
John McCall9fbd3182011-06-15 23:37:01 +000044
45namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +000046 /// \brief An associative container with fast insertion-order (deterministic)
47 /// iteration over its elements. Plus the special blot operation.
John McCall9fbd3182011-06-15 23:37:01 +000048 template<class KeyT, class ValueT>
49 class MapVector {
Michael Gottesman81c61212013-01-14 00:35:14 +000050 /// Map keys to indices in Vector.
John McCall9fbd3182011-06-15 23:37:01 +000051 typedef DenseMap<KeyT, size_t> MapTy;
52 MapTy Map;
53
John McCall9fbd3182011-06-15 23:37:01 +000054 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman81c61212013-01-14 00:35:14 +000055 /// Keys and values.
John McCall9fbd3182011-06-15 23:37:01 +000056 VectorTy Vector;
57
58 public:
59 typedef typename VectorTy::iterator iterator;
60 typedef typename VectorTy::const_iterator const_iterator;
61 iterator begin() { return Vector.begin(); }
62 iterator end() { return Vector.end(); }
63 const_iterator begin() const { return Vector.begin(); }
64 const_iterator end() const { return Vector.end(); }
65
66#ifdef XDEBUG
67 ~MapVector() {
68 assert(Vector.size() >= Map.size()); // May differ due to blotting.
69 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70 I != E; ++I) {
71 assert(I->second < Vector.size());
72 assert(Vector[I->second].first == I->first);
73 }
74 for (typename VectorTy::const_iterator I = Vector.begin(),
75 E = Vector.end(); I != E; ++I)
76 assert(!I->first ||
77 (Map.count(I->first) &&
78 Map[I->first] == size_t(I - Vector.begin())));
79 }
80#endif
81
Dan Gohman22cc4cc2012-03-02 01:13:53 +000082 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000083 std::pair<typename MapTy::iterator, bool> Pair =
84 Map.insert(std::make_pair(Arg, size_t(0)));
85 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000086 size_t Num = Vector.size();
87 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000088 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000089 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000090 }
91 return Vector[Pair.first->second].second;
92 }
93
94 std::pair<iterator, bool>
95 insert(const std::pair<KeyT, ValueT> &InsertPair) {
96 std::pair<typename MapTy::iterator, bool> Pair =
97 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000099 size_t Num = Vector.size();
100 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000101 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000102 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000103 }
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
105 }
106
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000107 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000108 typename MapTy::const_iterator It = Map.find(Key);
109 if (It == Map.end()) return Vector.end();
110 return Vector.begin() + It->second;
111 }
112
Michael Gottesman81c61212013-01-14 00:35:14 +0000113 /// This is similar to erase, but instead of removing the element from the
114 /// vector, it just zeros out the key in the vector. This leaves iterators
115 /// intact, but clients must be prepared for zeroed-out keys when 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000130/// @}
131///
132/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
133/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000134
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000135#include "llvm/ADT/StringSwitch.h"
136#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000137#include "llvm/IR/Intrinsics.h"
138#include "llvm/IR/Module.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000139#include "llvm/Support/CallSite.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000140#include "llvm/Transforms/Utils/Local.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000141
John McCall9fbd3182011-06-15 23:37:01 +0000142namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000143 /// \enum InstructionClass
144 /// \brief A simple classification for instructions.
John McCall9fbd3182011-06-15 23:37:01 +0000145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
169 };
170}
171
Michael Gottesman81c61212013-01-14 00:35:14 +0000172/// \brief Test whether the given value is possible a reference-counted pointer.
John McCall9fbd3182011-06-15 23:37:01 +0000173static bool IsPotentialUse(const Value *Op) {
174 // Pointers to static or stack storage are not reference-counted pointers.
175 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
176 return false;
177 // Special arguments are not reference-counted.
178 if (const Argument *Arg = dyn_cast<Argument>(Op))
179 if (Arg->hasByValAttr() ||
180 Arg->hasNestAttr() ||
181 Arg->hasStructRetAttr())
182 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000183 // Only consider values with pointer types.
184 // It seemes intuitive to exclude function pointer types as well, since
185 // functions are never reference-counted, however clang occasionally
186 // bitcasts reference-counted pointers to function-pointer type
187 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000188 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000189 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000190 return false;
191 // Conservatively assume anything else is a potential use.
192 return true;
193}
194
Michael Gottesman81c61212013-01-14 00:35:14 +0000195/// \brief Helper for GetInstructionClass. Determines what kind of construct CS is.
John McCall9fbd3182011-06-15 23:37:01 +0000196static 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000205/// \brief Determine if F is one of the special known Functions. If it isn't,
206/// return IC_CallOrUser.
John McCall9fbd3182011-06-15 23:37:01 +0000207static 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000278/// \brief Determine what kind of construct V is.
John McCall9fbd3182011-06-15 23:37:01 +0000279static 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000368/// \brief Determine which objc runtime call instruction class V belongs to.
369///
370/// This is similar to GetInstructionClass except that it only detects objc
371/// runtime calls. This allows it to be faster.
372///
John McCall9fbd3182011-06-15 23:37:01 +0000373static InstructionClass GetBasicInstructionClass(const Value *V) {
374 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
375 if (const Function *F = CI->getCalledFunction())
376 return GetFunctionClass(F);
377 // Otherwise, be conservative.
378 return IC_CallOrUser;
379 }
380
381 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000382 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000383}
384
Michael Gottesman81c61212013-01-14 00:35:14 +0000385/// \brief Test if the given class is objc_retain or equivalent.
John McCall9fbd3182011-06-15 23:37:01 +0000386static bool IsRetain(InstructionClass Class) {
387 return Class == IC_Retain ||
388 Class == IC_RetainRV;
389}
390
Michael Gottesman81c61212013-01-14 00:35:14 +0000391/// \brief Test if the given class is objc_autorelease or equivalent.
John McCall9fbd3182011-06-15 23:37:01 +0000392static bool IsAutorelease(InstructionClass Class) {
393 return Class == IC_Autorelease ||
394 Class == IC_AutoreleaseRV;
395}
396
Michael Gottesman81c61212013-01-14 00:35:14 +0000397/// \brief Test if the given class represents instructions which return their
398/// argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000399static 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000410/// \brief Test if the given class represents instructions which do nothing if
411/// passed a null pointer.
John McCall9fbd3182011-06-15 23:37:01 +0000412static 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000421/// \brief Test if the given class represents instructions which are always safe to
422/// mark with the "tail" keyword.
John McCall9fbd3182011-06-15 23:37:01 +0000423static bool IsAlwaysTail(InstructionClass Class) {
424 // IC_RetainBlock may be given a stack argument.
425 return Class == IC_Retain ||
426 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000427 Class == IC_AutoreleaseRV;
428}
429
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000430/// \brief Test if the given class represents instructions which are never safe
431/// to mark with the "tail" keyword.
432static bool IsNeverTail(InstructionClass Class) {
433 /// It is never safe to tail call objc_autorelease since by tail calling
434 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
435 /// fast autoreleasing causing our object to be potentially reclaimed from the
436 /// autorelease pool which violates the semantics of __autoreleasing types in
437 /// ARC.
438 return Class == IC_Autorelease;
439}
440
Michael Gottesman81c61212013-01-14 00:35:14 +0000441/// \brief Test if the given class represents instructions which are always safe
442/// to mark with the nounwind attribute.
John McCall9fbd3182011-06-15 23:37:01 +0000443static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000444 // objc_retainBlock is not nounwind because it calls user copy constructors
445 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000446 return Class == IC_Retain ||
447 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000448 Class == IC_Release ||
449 Class == IC_Autorelease ||
450 Class == IC_AutoreleaseRV ||
451 Class == IC_AutoreleasepoolPush ||
452 Class == IC_AutoreleasepoolPop;
453}
454
Michael Gottesman81c61212013-01-14 00:35:14 +0000455/// \brief Erase the given instruction.
456///
457/// Many ObjC calls return their argument verbatim,
458/// so if it's such a call and the return value has users, replace them with the
459/// argument value.
460///
John McCall9fbd3182011-06-15 23:37:01 +0000461static void EraseInstruction(Instruction *CI) {
462 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
463
464 bool Unused = CI->use_empty();
465
466 if (!Unused) {
467 // Replace the return value with the argument.
468 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
469 "Can't delete non-forwarding instruction with users!");
470 CI->replaceAllUsesWith(OldArg);
471 }
472
473 CI->eraseFromParent();
474
475 if (Unused)
476 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
477}
478
Michael Gottesman81c61212013-01-14 00:35:14 +0000479/// \brief This is a wrapper around getUnderlyingObject which also knows how to
480/// look through objc_retain and objc_autorelease calls, which we know to return
481/// their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000482static const Value *GetUnderlyingObjCPtr(const Value *V) {
483 for (;;) {
484 V = GetUnderlyingObject(V);
485 if (!IsForwarding(GetBasicInstructionClass(V)))
486 break;
487 V = cast<CallInst>(V)->getArgOperand(0);
488 }
489
490 return V;
491}
492
Michael Gottesman81c61212013-01-14 00:35:14 +0000493/// \brief This is a wrapper around Value::stripPointerCasts which also knows
494/// how to look through objc_retain and objc_autorelease calls, which we know to
495/// return their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000496static const Value *StripPointerCastsAndObjCCalls(const 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
Michael Gottesman81c61212013-01-14 00:35:14 +0000506/// \brief This is a wrapper around Value::stripPointerCasts which also knows
507/// how to look through objc_retain and objc_autorelease calls, which we know to
508/// return their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000509static Value *StripPointerCastsAndObjCCalls(Value *V) {
510 for (;;) {
511 V = V->stripPointerCasts();
512 if (!IsForwarding(GetBasicInstructionClass(V)))
513 break;
514 V = cast<CallInst>(V)->getArgOperand(0);
515 }
516 return V;
517}
518
Michael Gottesman81c61212013-01-14 00:35:14 +0000519/// \brief Assuming the given instruction is one of the special calls such as
520/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCall9fbd3182011-06-15 23:37:01 +0000521/// casts and forwarding calls.
522static Value *GetObjCArg(Value *Inst) {
523 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
524}
525
Michael Gottesman81c61212013-01-14 00:35:14 +0000526/// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
527/// that it uses special knowledge of ObjC conventions.
John McCall9fbd3182011-06-15 23:37:01 +0000528static bool IsObjCIdentifiedObject(const Value *V) {
529 // Assume that call results and arguments have their own "provenance".
530 // Constants (including GlobalVariables) and Allocas are never
531 // reference-counted.
532 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
533 isa<Argument>(V) || isa<Constant>(V) ||
534 isa<AllocaInst>(V))
535 return true;
536
537 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
538 const Value *Pointer =
539 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
540 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000541 // A constant pointer can't be pointing to an object on the heap. It may
542 // be reference-counted, but it won't be deleted.
543 if (GV->isConstant())
544 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000545 StringRef Name = GV->getName();
546 // These special variables are known to hold values which are not
547 // reference-counted pointers.
548 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
549 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
551 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
552 Name.startswith("\01l_objc_msgSend_fixup_"))
553 return true;
554 }
555 }
556
557 return false;
558}
559
Michael Gottesman81c61212013-01-14 00:35:14 +0000560/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
561/// as it finds a value with multiple uses.
John McCall9fbd3182011-06-15 23:37:01 +0000562static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
563 if (Arg->hasOneUse()) {
564 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
565 return FindSingleUseIdentifiedObject(BC->getOperand(0));
566 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
567 if (GEP->hasAllZeroIndices())
568 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
569 if (IsForwarding(GetBasicInstructionClass(Arg)))
570 return FindSingleUseIdentifiedObject(
571 cast<CallInst>(Arg)->getArgOperand(0));
572 if (!IsObjCIdentifiedObject(Arg))
573 return 0;
574 return Arg;
575 }
576
Dan Gohman0daef3d2012-05-08 23:39:44 +0000577 // If we found an identifiable object but it has multiple uses, but they are
578 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000579 if (IsObjCIdentifiedObject(Arg)) {
580 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
581 UI != UE; ++UI) {
582 const User *U = *UI;
583 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
584 return 0;
585 }
586
587 return Arg;
588 }
589
590 return 0;
591}
592
Michael Gottesman81c61212013-01-14 00:35:14 +0000593/// \brief Test if the given module looks interesting to run ARC optimization
594/// on.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000595static bool ModuleHasARC(const Module &M) {
596 return
597 M.getNamedValue("objc_retain") ||
598 M.getNamedValue("objc_release") ||
599 M.getNamedValue("objc_autorelease") ||
600 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
601 M.getNamedValue("objc_retainBlock") ||
602 M.getNamedValue("objc_autoreleaseReturnValue") ||
603 M.getNamedValue("objc_autoreleasePoolPush") ||
604 M.getNamedValue("objc_loadWeakRetained") ||
605 M.getNamedValue("objc_loadWeak") ||
606 M.getNamedValue("objc_destroyWeak") ||
607 M.getNamedValue("objc_storeWeak") ||
608 M.getNamedValue("objc_initWeak") ||
609 M.getNamedValue("objc_moveWeak") ||
610 M.getNamedValue("objc_copyWeak") ||
611 M.getNamedValue("objc_retainedObject") ||
612 M.getNamedValue("objc_unretainedObject") ||
613 M.getNamedValue("objc_unretainedPointer");
614}
615
Michael Gottesman81c61212013-01-14 00:35:14 +0000616/// \brief Test whether the given pointer, which is an Objective C block pointer, does
617/// not "escape".
618///
619/// This differs from regular escape analysis in that a use as an
620/// argument to a call is not considered an escape.
621///
Dan Gohman79522dc2012-01-13 00:39:07 +0000622static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman981308c2013-01-13 07:47:32 +0000623
624 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
625
Dan Gohman79522dc2012-01-13 00:39:07 +0000626 // Walk the def-use chains.
627 SmallVector<const Value *, 4> Worklist;
628 Worklist.push_back(BlockPtr);
Michael Gottesman6056b852013-01-13 22:12:06 +0000629
630 // Ensure we do not visit any value twice.
631 SmallPtrSet<const Value *, 4> VisitedSet;
632
Dan Gohman79522dc2012-01-13 00:39:07 +0000633 do {
634 const Value *V = Worklist.pop_back_val();
Michael Gottesman981308c2013-01-13 07:47:32 +0000635
636 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
637
Dan Gohman79522dc2012-01-13 00:39:07 +0000638 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
639 UI != UE; ++UI) {
640 const User *UUser = *UI;
Michael Gottesman981308c2013-01-13 07:47:32 +0000641
642 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
643
Dan Gohman79522dc2012-01-13 00:39:07 +0000644 // Special - Use by a call (callee or argument) is not considered
645 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000646 switch (GetBasicInstructionClass(UUser)) {
647 case IC_StoreWeak:
648 case IC_InitWeak:
649 case IC_StoreStrong:
650 case IC_Autorelease:
Michael Gottesman981308c2013-01-13 07:47:32 +0000651 case IC_AutoreleaseRV: {
652 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
653 "Block Escapes!\n");
Dan Gohman44234772012-04-13 18:28:58 +0000654 // These special functions make copies of their pointer arguments.
655 return true;
Michael Gottesman981308c2013-01-13 07:47:32 +0000656 }
Dan Gohman44234772012-04-13 18:28:58 +0000657 case IC_User:
658 case IC_None:
659 // Use by an instruction which copies the value is an escape if the
660 // result is an escape.
661 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
662 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesman6056b852013-01-13 22:12:06 +0000663
664 if (!VisitedSet.count(UUser)) {
665 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes if "
666 "result escapes. Adding to list.\n");
667 VisitedSet.insert(V);
668 Worklist.push_back(UUser);
669 } else {
670 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
671 }
Dan Gohman44234772012-04-13 18:28:58 +0000672 continue;
673 }
674 // Use by a load is not an escape.
675 if (isa<LoadInst>(UUser))
676 continue;
677 // Use by a store is not an escape if the use is the address.
678 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
679 if (V != SI->getValueOperand())
680 continue;
681 break;
682 default:
683 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000684 continue;
685 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000686 // Otherwise, conservatively assume an escape.
Michael Gottesman981308c2013-01-13 07:47:32 +0000687 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000688 return true;
689 }
690 } while (!Worklist.empty());
691
692 // No escapes found.
Michael Gottesman981308c2013-01-13 07:47:32 +0000693 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000694 return false;
695}
696
Michael Gottesman81c61212013-01-14 00:35:14 +0000697/// @}
698///
699/// \defgroup ARCAA An extension of alias analysis using ObjC specific knowledge.
700/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000701
John McCall9fbd3182011-06-15 23:37:01 +0000702#include "llvm/Analysis/AliasAnalysis.h"
703#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000704#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000705
706namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000707 /// \brief This is a simple alias analysis implementation that uses knowledge
708 /// of ARC constructs to answer queries.
John McCall9fbd3182011-06-15 23:37:01 +0000709 ///
710 /// TODO: This class could be generalized to know about other ObjC-specific
711 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
712 /// even though their offsets are dynamic.
713 class ObjCARCAliasAnalysis : public ImmutablePass,
714 public AliasAnalysis {
715 public:
716 static char ID; // Class identification, replacement for typeinfo
717 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
718 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
719 }
720
721 private:
722 virtual void initializePass() {
723 InitializeAliasAnalysis(this);
724 }
725
Michael Gottesman81c61212013-01-14 00:35:14 +0000726 /// This method is used when a pass implements an analysis interface through
727 /// multiple inheritance. If needed, it should override this to adjust the
728 /// this pointer as needed for the specified pass info.
John McCall9fbd3182011-06-15 23:37:01 +0000729 virtual void *getAdjustedAnalysisPointer(const void *PI) {
730 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000731 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000732 return this;
733 }
734
735 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
736 virtual AliasResult alias(const Location &LocA, const Location &LocB);
737 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
738 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
739 virtual ModRefBehavior getModRefBehavior(const Function *F);
740 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
741 const Location &Loc);
742 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
743 ImmutableCallSite CS2);
744 };
745} // End of anonymous namespace
746
747// Register this pass...
748char ObjCARCAliasAnalysis::ID = 0;
749INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
750 "ObjC-ARC-Based Alias Analysis", false, true, false)
751
752ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
753 return new ObjCARCAliasAnalysis();
754}
755
756void
757ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
758 AU.setPreservesAll();
759 AliasAnalysis::getAnalysisUsage(AU);
760}
761
762AliasAnalysis::AliasResult
763ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
764 if (!EnableARCOpts)
765 return AliasAnalysis::alias(LocA, LocB);
766
767 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
768 // precise alias query.
769 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
770 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
771 AliasResult Result =
772 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
773 Location(SB, LocB.Size, LocB.TBAATag));
774 if (Result != MayAlias)
775 return Result;
776
777 // If that failed, climb to the underlying object, including climbing through
778 // ObjC-specific no-ops, and try making an imprecise alias query.
779 const Value *UA = GetUnderlyingObjCPtr(SA);
780 const Value *UB = GetUnderlyingObjCPtr(SB);
781 if (UA != SA || UB != SB) {
782 Result = AliasAnalysis::alias(Location(UA), Location(UB));
783 // We can't use MustAlias or PartialAlias results here because
784 // GetUnderlyingObjCPtr may return an offsetted pointer value.
785 if (Result == NoAlias)
786 return NoAlias;
787 }
788
789 // If that failed, fail. We don't need to chain here, since that's covered
790 // by the earlier precise query.
791 return MayAlias;
792}
793
794bool
795ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
796 bool OrLocal) {
797 if (!EnableARCOpts)
798 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
799
800 // First, strip off no-ops, including ObjC-specific no-ops, and try making
801 // a precise alias query.
802 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
803 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
804 OrLocal))
805 return true;
806
807 // If that failed, climb to the underlying object, including climbing through
808 // ObjC-specific no-ops, and try making an imprecise alias query.
809 const Value *U = GetUnderlyingObjCPtr(S);
810 if (U != S)
811 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
812
813 // If that failed, fail. We don't need to chain here, since that's covered
814 // by the earlier precise query.
815 return false;
816}
817
818AliasAnalysis::ModRefBehavior
819ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
820 // We have nothing to do. Just chain to the next AliasAnalysis.
821 return AliasAnalysis::getModRefBehavior(CS);
822}
823
824AliasAnalysis::ModRefBehavior
825ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
826 if (!EnableARCOpts)
827 return AliasAnalysis::getModRefBehavior(F);
828
829 switch (GetFunctionClass(F)) {
830 case IC_NoopCast:
831 return DoesNotAccessMemory;
832 default:
833 break;
834 }
835
836 return AliasAnalysis::getModRefBehavior(F);
837}
838
839AliasAnalysis::ModRefResult
840ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
841 if (!EnableARCOpts)
842 return AliasAnalysis::getModRefInfo(CS, Loc);
843
844 switch (GetBasicInstructionClass(CS.getInstruction())) {
845 case IC_Retain:
846 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000847 case IC_Autorelease:
848 case IC_AutoreleaseRV:
849 case IC_NoopCast:
850 case IC_AutoreleasepoolPush:
851 case IC_FusedRetainAutorelease:
852 case IC_FusedRetainAutoreleaseRV:
853 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000854 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000855 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000856 return NoModRef;
857 default:
858 break;
859 }
860
861 return AliasAnalysis::getModRefInfo(CS, Loc);
862}
863
864AliasAnalysis::ModRefResult
865ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
866 ImmutableCallSite CS2) {
867 // TODO: Theoretically we could check for dependencies between objc_* calls
868 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
869 return AliasAnalysis::getModRefInfo(CS1, CS2);
870}
871
Michael Gottesman81c61212013-01-14 00:35:14 +0000872/// @}
873///
874/// \defgroup ARCExpansion Early ARC Optimizations.
875/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000876
877#include "llvm/Support/InstIterator.h"
878#include "llvm/Transforms/Scalar.h"
879
880namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000881 /// \brief Early ARC transformations.
John McCall9fbd3182011-06-15 23:37:01 +0000882 class ObjCARCExpand : public FunctionPass {
883 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000884 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000885 virtual bool runOnFunction(Function &F);
886
Michael Gottesman81c61212013-01-14 00:35:14 +0000887 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000888 bool Run;
889
John McCall9fbd3182011-06-15 23:37:01 +0000890 public:
891 static char ID;
892 ObjCARCExpand() : FunctionPass(ID) {
893 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
894 }
895 };
896}
897
898char ObjCARCExpand::ID = 0;
899INITIALIZE_PASS(ObjCARCExpand,
900 "objc-arc-expand", "ObjC ARC expansion", false, false)
901
902Pass *llvm::createObjCARCExpandPass() {
903 return new ObjCARCExpand();
904}
905
906void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
907 AU.setPreservesCFG();
908}
909
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000910bool ObjCARCExpand::doInitialization(Module &M) {
911 Run = ModuleHasARC(M);
912 return false;
913}
914
John McCall9fbd3182011-06-15 23:37:01 +0000915bool ObjCARCExpand::runOnFunction(Function &F) {
916 if (!EnableARCOpts)
917 return false;
918
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000919 // If nothing in the Module uses ARC, don't do anything.
920 if (!Run)
921 return false;
922
John McCall9fbd3182011-06-15 23:37:01 +0000923 bool Changed = false;
924
Michael Gottesmancf140052013-01-13 07:00:51 +0000925 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
926
John McCall9fbd3182011-06-15 23:37:01 +0000927 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
928 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000929
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000930 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000931
John McCall9fbd3182011-06-15 23:37:01 +0000932 switch (GetBasicInstructionClass(Inst)) {
933 case IC_Retain:
934 case IC_RetainRV:
935 case IC_Autorelease:
936 case IC_AutoreleaseRV:
937 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000938 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000939 // These calls return their argument verbatim, as a low-level
940 // optimization. However, this makes high-level optimizations
941 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000942 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000943 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000944 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
945 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
946 " New = " << *Value << "\n");
947 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000948 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000949 }
John McCall9fbd3182011-06-15 23:37:01 +0000950 default:
951 break;
952 }
953 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000954
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000955 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000956
John McCall9fbd3182011-06-15 23:37:01 +0000957 return Changed;
958}
959
Michael Gottesman81c61212013-01-14 00:35:14 +0000960/// @}
961///
962/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
963/// @{
Dan Gohman2f6263c2012-01-17 20:52:24 +0000964
Dan Gohman0daef3d2012-05-08 23:39:44 +0000965#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000966#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000967
Dan Gohman2f6263c2012-01-17 20:52:24 +0000968namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000969 /// \brief Autorelease pool elimination.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000970 class ObjCARCAPElim : public ModulePass {
971 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
972 virtual bool runOnModule(Module &M);
973
Dan Gohman447989c2012-04-27 18:56:31 +0000974 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
975 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000976
977 public:
978 static char ID;
979 ObjCARCAPElim() : ModulePass(ID) {
980 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
981 }
982 };
983}
984
985char ObjCARCAPElim::ID = 0;
986INITIALIZE_PASS(ObjCARCAPElim,
987 "objc-arc-apelim",
988 "ObjC ARC autorelease pool elimination",
989 false, false)
990
991Pass *llvm::createObjCARCAPElimPass() {
992 return new ObjCARCAPElim();
993}
994
995void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
996 AU.setPreservesCFG();
997}
998
Michael Gottesman81c61212013-01-14 00:35:14 +0000999/// Interprocedurally determine if calls made by the given call site can
1000/// possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +00001001bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1002 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +00001003 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1004 return true;
Dan Gohman447989c2012-04-27 18:56:31 +00001005 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +00001006 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +00001007 const BasicBlock *BB = I;
1008 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1009 J != F; ++J)
1010 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +00001011 // This recursion depth limit is arbitrary. It's just great
1012 // enough to cover known interesting testcases.
1013 if (Depth < 3 &&
1014 !JCS.onlyReadsMemory() &&
1015 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001016 return true;
1017 }
1018 return false;
1019 }
1020
1021 return true;
1022}
1023
1024bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1025 bool Changed = false;
1026
1027 Instruction *Push = 0;
1028 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1029 Instruction *Inst = I++;
1030 switch (GetBasicInstructionClass(Inst)) {
1031 case IC_AutoreleasepoolPush:
1032 Push = Inst;
1033 break;
1034 case IC_AutoreleasepoolPop:
1035 // If this pop matches a push and nothing in between can autorelease,
1036 // zap the pair.
1037 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1038 Changed = true;
Michael Gottesman5c0ae472013-01-04 21:29:57 +00001039 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001040 << " Pop: " << *Inst << "\n"
1041 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001042 Inst->eraseFromParent();
1043 Push->eraseFromParent();
1044 }
1045 Push = 0;
1046 break;
1047 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001048 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001049 Push = 0;
1050 break;
1051 default:
1052 break;
1053 }
1054 }
1055
1056 return Changed;
1057}
1058
1059bool ObjCARCAPElim::runOnModule(Module &M) {
1060 if (!EnableARCOpts)
1061 return false;
1062
1063 // If nothing in the Module uses ARC, don't do anything.
1064 if (!ModuleHasARC(M))
1065 return false;
1066
Dan Gohman1dae3e92012-01-18 21:19:38 +00001067 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001068 // identifying the global constructors. In theory, unnecessary autorelease
1069 // pools could occur anywhere, but in practice it's pretty rare. Global
1070 // ctors are a place where autorelease pools get inserted automatically,
1071 // so it's pretty common for them to be unnecessary, and it's pretty
1072 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001073 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1074 if (!GV)
1075 return false;
1076
1077 assert(GV->hasDefinitiveInitializer() &&
1078 "llvm.global_ctors is uncooperative!");
1079
Dan Gohman2f6263c2012-01-17 20:52:24 +00001080 bool Changed = false;
1081
Dan Gohman1dae3e92012-01-18 21:19:38 +00001082 // Dig the constructor functions out of GV's initializer.
1083 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1084 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1085 OI != OE; ++OI) {
1086 Value *Op = *OI;
1087 // llvm.global_ctors is an array of pairs where the second members
1088 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001089 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1090 // If the user used a constructor function with the wrong signature and
1091 // it got bitcasted or whatever, look the other way.
1092 if (!F)
1093 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001094 // Only look at function definitions.
1095 if (F->isDeclaration())
1096 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001097 // Only look at functions with one basic block.
1098 if (llvm::next(F->begin()) != F->end())
1099 continue;
1100 // Ok, a single-block constructor function definition. Try to optimize it.
1101 Changed |= OptimizeBB(F->begin());
1102 }
1103
1104 return Changed;
1105}
1106
Michael Gottesman81c61212013-01-14 00:35:14 +00001107/// @}
1108///
1109/// \defgroup ARCOpt ARC Optimization.
1110/// @{
John McCall9fbd3182011-06-15 23:37:01 +00001111
1112// TODO: On code like this:
1113//
1114// objc_retain(%x)
1115// stuff_that_cannot_release()
1116// objc_autorelease(%x)
1117// stuff_that_cannot_release()
1118// objc_retain(%x)
1119// stuff_that_cannot_release()
1120// objc_autorelease(%x)
1121//
1122// The second retain and autorelease can be deleted.
1123
1124// TODO: It should be possible to delete
1125// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1126// pairs if nothing is actually autoreleased between them. Also, autorelease
1127// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1128// after inlining) can be turned into plain release calls.
1129
1130// TODO: Critical-edge splitting. If the optimial insertion point is
1131// a critical edge, the current algorithm has to fail, because it doesn't
1132// know how to split edges. It should be possible to make the optimizer
1133// think in terms of edges, rather than blocks, and then split critical
1134// edges on demand.
1135
1136// TODO: OptimizeSequences could generalized to be Interprocedural.
1137
1138// TODO: Recognize that a bunch of other objc runtime calls have
1139// non-escaping arguments and non-releasing arguments, and may be
1140// non-autoreleasing.
1141
1142// TODO: Sink autorelease calls as far as possible. Unfortunately we
1143// usually can't sink them past other calls, which would be the main
1144// case where it would be useful.
1145
Dan Gohmane6d5e882011-08-19 00:26:36 +00001146// TODO: The pointer returned from objc_loadWeakRetained is retained.
1147
1148// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001149
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001150#include "llvm/ADT/SmallPtrSet.h"
1151#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001152#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001153#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001154
1155STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1156STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1157STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1158STATISTIC(NumRets, "Number of return value forwarding "
1159 "retain+autoreleaes eliminated");
1160STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1161STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1162
1163namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001164 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1165 /// techniques, except it uses special ObjC-specific reasoning about pointer
1166 /// relationships.
John McCall9fbd3182011-06-15 23:37:01 +00001167 class ProvenanceAnalysis {
1168 AliasAnalysis *AA;
1169
1170 typedef std::pair<const Value *, const Value *> ValuePairTy;
1171 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1172 CachedResultsTy CachedResults;
1173
1174 bool relatedCheck(const Value *A, const Value *B);
1175 bool relatedSelect(const SelectInst *A, const Value *B);
1176 bool relatedPHI(const PHINode *A, const Value *B);
1177
Craig Topperc2945e42012-09-18 02:01:41 +00001178 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1179 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001180
1181 public:
1182 ProvenanceAnalysis() {}
1183
1184 void setAA(AliasAnalysis *aa) { AA = aa; }
1185
1186 AliasAnalysis *getAA() const { return AA; }
1187
1188 bool related(const Value *A, const Value *B);
1189
1190 void clear() {
1191 CachedResults.clear();
1192 }
1193 };
1194}
1195
1196bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1197 // If the values are Selects with the same condition, we can do a more precise
1198 // check: just check for relations between the values on corresponding arms.
1199 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001200 if (A->getCondition() == SB->getCondition())
1201 return related(A->getTrueValue(), SB->getTrueValue()) ||
1202 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001203
1204 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001205 return related(A->getTrueValue(), B) ||
1206 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001207}
1208
1209bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1210 // If the values are PHIs in the same block, we can do a more precise as well
1211 // as efficient check: just check for relations between the values on
1212 // corresponding edges.
1213 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1214 if (PNB->getParent() == A->getParent()) {
1215 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1216 if (related(A->getIncomingValue(i),
1217 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1218 return true;
1219 return false;
1220 }
1221
1222 // Check each unique source of the PHI node against B.
1223 SmallPtrSet<const Value *, 4> UniqueSrc;
1224 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1225 const Value *PV1 = A->getIncomingValue(i);
1226 if (UniqueSrc.insert(PV1) && related(PV1, B))
1227 return true;
1228 }
1229
1230 // All of the arms checked out.
1231 return false;
1232}
1233
Michael Gottesman81c61212013-01-14 00:35:14 +00001234/// Test if the value of P, or any value covered by its provenance, is ever
1235/// stored within the function (not counting callees).
John McCall9fbd3182011-06-15 23:37:01 +00001236static bool isStoredObjCPointer(const Value *P) {
1237 SmallPtrSet<const Value *, 8> Visited;
1238 SmallVector<const Value *, 8> Worklist;
1239 Worklist.push_back(P);
1240 Visited.insert(P);
1241 do {
1242 P = Worklist.pop_back_val();
1243 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1244 UI != UE; ++UI) {
1245 const User *Ur = *UI;
1246 if (isa<StoreInst>(Ur)) {
1247 if (UI.getOperandNo() == 0)
1248 // The pointer is stored.
1249 return true;
1250 // The pointed is stored through.
1251 continue;
1252 }
1253 if (isa<CallInst>(Ur))
1254 // The pointer is passed as an argument, ignore this.
1255 continue;
1256 if (isa<PtrToIntInst>(P))
1257 // Assume the worst.
1258 return true;
1259 if (Visited.insert(Ur))
1260 Worklist.push_back(Ur);
1261 }
1262 } while (!Worklist.empty());
1263
1264 // Everything checked out.
1265 return false;
1266}
1267
1268bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1269 // Skip past provenance pass-throughs.
1270 A = GetUnderlyingObjCPtr(A);
1271 B = GetUnderlyingObjCPtr(B);
1272
1273 // Quick check.
1274 if (A == B)
1275 return true;
1276
1277 // Ask regular AliasAnalysis, for a first approximation.
1278 switch (AA->alias(A, B)) {
1279 case AliasAnalysis::NoAlias:
1280 return false;
1281 case AliasAnalysis::MustAlias:
1282 case AliasAnalysis::PartialAlias:
1283 return true;
1284 case AliasAnalysis::MayAlias:
1285 break;
1286 }
1287
1288 bool AIsIdentified = IsObjCIdentifiedObject(A);
1289 bool BIsIdentified = IsObjCIdentifiedObject(B);
1290
1291 // An ObjC-Identified object can't alias a load if it is never locally stored.
1292 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001293 // Check for an obvious escape.
1294 if (isa<LoadInst>(B))
1295 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001296 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001297 // Check for an obvious escape.
1298 if (isa<LoadInst>(A))
1299 return isStoredObjCPointer(B);
1300 // Both pointers are identified and escapes aren't an evident problem.
1301 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001302 }
Dan Gohman230768b2012-09-04 23:16:20 +00001303 } else if (BIsIdentified) {
1304 // Check for an obvious escape.
1305 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001306 return isStoredObjCPointer(B);
1307 }
1308
1309 // Special handling for PHI and Select.
1310 if (const PHINode *PN = dyn_cast<PHINode>(A))
1311 return relatedPHI(PN, B);
1312 if (const PHINode *PN = dyn_cast<PHINode>(B))
1313 return relatedPHI(PN, A);
1314 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1315 return relatedSelect(S, B);
1316 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1317 return relatedSelect(S, A);
1318
1319 // Conservative.
1320 return true;
1321}
1322
1323bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1324 // Begin by inserting a conservative value into the map. If the insertion
1325 // fails, we have the answer already. If it succeeds, leave it there until we
1326 // compute the real answer to guard against recursive queries.
1327 if (A > B) std::swap(A, B);
1328 std::pair<CachedResultsTy::iterator, bool> Pair =
1329 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1330 if (!Pair.second)
1331 return Pair.first->second;
1332
1333 bool Result = relatedCheck(A, B);
1334 CachedResults[ValuePairTy(A, B)] = Result;
1335 return Result;
1336}
1337
1338namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001339 /// \enum Sequence
1340 ///
1341 /// \brief A sequence of states that a pointer may go through in which an
1342 /// objc_retain and objc_release are actually needed.
John McCall9fbd3182011-06-15 23:37:01 +00001343 enum Sequence {
1344 S_None,
1345 S_Retain, ///< objc_retain(x)
1346 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1347 S_Use, ///< any use of x
1348 S_Stop, ///< like S_Release, but code motion is stopped
1349 S_Release, ///< objc_release(x)
1350 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1351 };
1352}
1353
1354static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1355 // The easy cases.
1356 if (A == B)
1357 return A;
1358 if (A == S_None || B == S_None)
1359 return S_None;
1360
John McCall9fbd3182011-06-15 23:37:01 +00001361 if (A > B) std::swap(A, B);
1362 if (TopDown) {
1363 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001364 if ((A == S_Retain || A == S_CanRelease) &&
1365 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001366 return B;
1367 } else {
1368 // Choose the side which is further along in the sequence.
1369 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001370 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001371 return A;
1372 // If both sides are releases, choose the more conservative one.
1373 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1374 return A;
1375 if (A == S_Release && B == S_MovableRelease)
1376 return A;
1377 }
1378
1379 return S_None;
1380}
1381
1382namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001383 /// \brief Unidirectional information about either a
John McCall9fbd3182011-06-15 23:37:01 +00001384 /// retain-decrement-use-release sequence or release-use-decrement-retain
1385 /// reverese sequence.
1386 struct RRInfo {
Michael Gottesman81c61212013-01-14 00:35:14 +00001387 /// After an objc_retain, the reference count of the referenced
Dan Gohmane6d5e882011-08-19 00:26:36 +00001388 /// object is known to be positive. Similarly, before an objc_release, the
1389 /// reference count of the referenced object is known to be positive. If
1390 /// there are retain-release pairs in code regions where the retain count
1391 /// is known to be positive, they can be eliminated, regardless of any side
1392 /// effects between them.
1393 ///
1394 /// Also, a retain+release pair nested within another retain+release
1395 /// pair all on the known same pointer value can be eliminated, regardless
1396 /// of any intervening side effects.
1397 ///
1398 /// KnownSafe is true when either of these conditions is satisfied.
1399 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001400
Michael Gottesman81c61212013-01-14 00:35:14 +00001401 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1402 /// calls).
John McCall9fbd3182011-06-15 23:37:01 +00001403 bool IsRetainBlock;
1404
Michael Gottesman81c61212013-01-14 00:35:14 +00001405 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCall9fbd3182011-06-15 23:37:01 +00001406 bool IsTailCallRelease;
1407
Michael Gottesman81c61212013-01-14 00:35:14 +00001408 /// If the Calls are objc_release calls and they all have a
1409 /// clang.imprecise_release tag, this is the metadata tag.
John McCall9fbd3182011-06-15 23:37:01 +00001410 MDNode *ReleaseMetadata;
1411
Michael Gottesman81c61212013-01-14 00:35:14 +00001412 /// For a top-down sequence, the set of objc_retains or
John McCall9fbd3182011-06-15 23:37:01 +00001413 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1414 SmallPtrSet<Instruction *, 2> Calls;
1415
Michael Gottesman81c61212013-01-14 00:35:14 +00001416 /// The set of optimal insert positions for moving calls in the opposite
1417 /// sequence.
John McCall9fbd3182011-06-15 23:37:01 +00001418 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1419
1420 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001421 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001422 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001423 ReleaseMetadata(0) {}
1424
1425 void clear();
1426 };
1427}
1428
1429void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001430 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001431 IsRetainBlock = false;
1432 IsTailCallRelease = false;
1433 ReleaseMetadata = 0;
1434 Calls.clear();
1435 ReverseInsertPts.clear();
1436}
1437
1438namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001439 /// \brief This class summarizes several per-pointer runtime properties which
1440 /// are propogated through the flow graph.
John McCall9fbd3182011-06-15 23:37:01 +00001441 class PtrState {
Michael Gottesman81c61212013-01-14 00:35:14 +00001442 /// True if the reference count is known to be incremented.
Dan Gohman50ade652012-04-25 00:50:46 +00001443 bool KnownPositiveRefCount;
1444
Michael Gottesman81c61212013-01-14 00:35:14 +00001445 /// True of we've seen an opportunity for partial RR elimination, such as
1446 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman50ade652012-04-25 00:50:46 +00001447 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001448
Michael Gottesman81c61212013-01-14 00:35:14 +00001449 /// The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001450 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001451
1452 public:
Michael Gottesman81c61212013-01-14 00:35:14 +00001453 /// Unidirectional information about the current sequence.
1454 ///
John McCall9fbd3182011-06-15 23:37:01 +00001455 /// TODO: Encapsulate this better.
1456 RRInfo RRI;
1457
Dan Gohman230768b2012-09-04 23:16:20 +00001458 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001459 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001460
Dan Gohman50ade652012-04-25 00:50:46 +00001461 void SetKnownPositiveRefCount() {
1462 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001463 }
1464
Dan Gohman50ade652012-04-25 00:50:46 +00001465 void ClearRefCount() {
1466 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001467 }
1468
John McCall9fbd3182011-06-15 23:37:01 +00001469 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001470 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001471 }
1472
1473 void SetSeq(Sequence NewSeq) {
1474 Seq = NewSeq;
1475 }
1476
John McCall9fbd3182011-06-15 23:37:01 +00001477 Sequence GetSeq() const {
1478 return Seq;
1479 }
1480
1481 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001482 ResetSequenceProgress(S_None);
1483 }
1484
1485 void ResetSequenceProgress(Sequence NewSeq) {
1486 Seq = NewSeq;
1487 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001488 RRI.clear();
1489 }
1490
1491 void Merge(const PtrState &Other, bool TopDown);
1492 };
1493}
1494
1495void
1496PtrState::Merge(const PtrState &Other, bool TopDown) {
1497 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001498 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001499
1500 // We can't merge a plain objc_retain with an objc_retainBlock.
1501 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1502 Seq = S_None;
1503
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001504 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001505 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001506 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001507 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001508 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001509 // If we're doing a merge on a path that's previously seen a partial
1510 // merge, conservatively drop the sequence, to avoid doing partial
1511 // RR elimination. If the branch predicates for the two merge differ,
1512 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001513 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001514 } else {
1515 // Conservatively merge the ReleaseMetadata information.
1516 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1517 RRI.ReleaseMetadata = 0;
1518
Dan Gohmane6d5e882011-08-19 00:26:36 +00001519 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001520 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1521 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001522 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001523
1524 // Merge the insert point sets. If there are any differences,
1525 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001526 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001527 for (SmallPtrSet<Instruction *, 2>::const_iterator
1528 I = Other.RRI.ReverseInsertPts.begin(),
1529 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001530 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001531 }
1532}
1533
1534namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001535 /// \brief Per-BasicBlock state.
John McCall9fbd3182011-06-15 23:37:01 +00001536 class BBState {
Michael Gottesman81c61212013-01-14 00:35:14 +00001537 /// The number of unique control paths from the entry which can reach this
1538 /// block.
John McCall9fbd3182011-06-15 23:37:01 +00001539 unsigned TopDownPathCount;
1540
Michael Gottesman81c61212013-01-14 00:35:14 +00001541 /// The number of unique control paths to exits from this block.
John McCall9fbd3182011-06-15 23:37:01 +00001542 unsigned BottomUpPathCount;
1543
Michael Gottesman81c61212013-01-14 00:35:14 +00001544 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCall9fbd3182011-06-15 23:37:01 +00001545 typedef MapVector<const Value *, PtrState> MapTy;
1546
Michael Gottesman81c61212013-01-14 00:35:14 +00001547 /// The top-down traversal uses this to record information known about a
1548 /// pointer at the bottom of each block.
John McCall9fbd3182011-06-15 23:37:01 +00001549 MapTy PerPtrTopDown;
1550
Michael Gottesman81c61212013-01-14 00:35:14 +00001551 /// The bottom-up traversal uses this to record information known about a
1552 /// pointer at the top of each block.
John McCall9fbd3182011-06-15 23:37:01 +00001553 MapTy PerPtrBottomUp;
1554
Michael Gottesman81c61212013-01-14 00:35:14 +00001555 /// Effective predecessors of the current block ignoring ignorable edges and
1556 /// ignored backedges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001557 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman81c61212013-01-14 00:35:14 +00001558 /// Effective successors of the current block ignoring ignorable edges and
1559 /// ignored backedges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001560 SmallVector<BasicBlock *, 2> Succs;
1561
John McCall9fbd3182011-06-15 23:37:01 +00001562 public:
1563 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1564
1565 typedef MapTy::iterator ptr_iterator;
1566 typedef MapTy::const_iterator ptr_const_iterator;
1567
1568 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1569 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1570 ptr_const_iterator top_down_ptr_begin() const {
1571 return PerPtrTopDown.begin();
1572 }
1573 ptr_const_iterator top_down_ptr_end() const {
1574 return PerPtrTopDown.end();
1575 }
1576
1577 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1578 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1579 ptr_const_iterator bottom_up_ptr_begin() const {
1580 return PerPtrBottomUp.begin();
1581 }
1582 ptr_const_iterator bottom_up_ptr_end() const {
1583 return PerPtrBottomUp.end();
1584 }
1585
Michael Gottesman81c61212013-01-14 00:35:14 +00001586 /// Mark this block as being an entry block, which has one path from the
1587 /// entry by definition.
John McCall9fbd3182011-06-15 23:37:01 +00001588 void SetAsEntry() { TopDownPathCount = 1; }
1589
Michael Gottesman81c61212013-01-14 00:35:14 +00001590 /// Mark this block as being an exit block, which has one path to an exit by
1591 /// definition.
John McCall9fbd3182011-06-15 23:37:01 +00001592 void SetAsExit() { BottomUpPathCount = 1; }
1593
1594 PtrState &getPtrTopDownState(const Value *Arg) {
1595 return PerPtrTopDown[Arg];
1596 }
1597
1598 PtrState &getPtrBottomUpState(const Value *Arg) {
1599 return PerPtrBottomUp[Arg];
1600 }
1601
1602 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001603 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001604 }
1605
1606 void clearTopDownPointers() {
1607 PerPtrTopDown.clear();
1608 }
1609
1610 void InitFromPred(const BBState &Other);
1611 void InitFromSucc(const BBState &Other);
1612 void MergePred(const BBState &Other);
1613 void MergeSucc(const BBState &Other);
1614
Michael Gottesman81c61212013-01-14 00:35:14 +00001615 /// Return the number of possible unique paths from an entry to an exit
1616 /// which pass through this block. This is only valid after both the
1617 /// top-down and bottom-up traversals are complete.
John McCall9fbd3182011-06-15 23:37:01 +00001618 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001619 assert(TopDownPathCount != 0);
1620 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001621 return TopDownPathCount * BottomUpPathCount;
1622 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001623
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001624 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001625 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001626 edge_iterator pred_begin() { return Preds.begin(); }
1627 edge_iterator pred_end() { return Preds.end(); }
1628 edge_iterator succ_begin() { return Succs.begin(); }
1629 edge_iterator succ_end() { return Succs.end(); }
1630
1631 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1632 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1633
1634 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001635 };
1636}
1637
1638void BBState::InitFromPred(const BBState &Other) {
1639 PerPtrTopDown = Other.PerPtrTopDown;
1640 TopDownPathCount = Other.TopDownPathCount;
1641}
1642
1643void BBState::InitFromSucc(const BBState &Other) {
1644 PerPtrBottomUp = Other.PerPtrBottomUp;
1645 BottomUpPathCount = Other.BottomUpPathCount;
1646}
1647
Michael Gottesman81c61212013-01-14 00:35:14 +00001648/// The top-down traversal uses this to merge information about predecessors to
1649/// form the initial state for a new block.
John McCall9fbd3182011-06-15 23:37:01 +00001650void BBState::MergePred(const BBState &Other) {
1651 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1652 // loop backedge. Loop backedges are special.
1653 TopDownPathCount += Other.TopDownPathCount;
1654
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001655 // Check for overflow. If we have overflow, fall back to conservative behavior.
1656 if (TopDownPathCount < Other.TopDownPathCount) {
1657 clearTopDownPointers();
1658 return;
1659 }
1660
John McCall9fbd3182011-06-15 23:37:01 +00001661 // For each entry in the other set, if our set has an entry with the same key,
1662 // merge the entries. Otherwise, copy the entry and merge it with an empty
1663 // entry.
1664 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1665 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1666 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1667 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1668 /*TopDown=*/true);
1669 }
1670
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001671 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001672 // same key, force it to merge with an empty entry.
1673 for (ptr_iterator MI = top_down_ptr_begin(),
1674 ME = top_down_ptr_end(); MI != ME; ++MI)
1675 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1676 MI->second.Merge(PtrState(), /*TopDown=*/true);
1677}
1678
Michael Gottesman81c61212013-01-14 00:35:14 +00001679/// The bottom-up traversal uses this to merge information about successors to
1680/// form the initial state for a new block.
John McCall9fbd3182011-06-15 23:37:01 +00001681void BBState::MergeSucc(const BBState &Other) {
1682 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1683 // loop backedge. Loop backedges are special.
1684 BottomUpPathCount += Other.BottomUpPathCount;
1685
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001686 // Check for overflow. If we have overflow, fall back to conservative behavior.
1687 if (BottomUpPathCount < Other.BottomUpPathCount) {
1688 clearBottomUpPointers();
1689 return;
1690 }
1691
John McCall9fbd3182011-06-15 23:37:01 +00001692 // For each entry in the other set, if our set has an entry with the
1693 // same key, merge the entries. Otherwise, copy the entry and merge
1694 // it with an empty entry.
1695 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1696 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1697 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1698 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1699 /*TopDown=*/false);
1700 }
1701
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001702 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001703 // with the same key, force it to merge with an empty entry.
1704 for (ptr_iterator MI = bottom_up_ptr_begin(),
1705 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1706 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1707 MI->second.Merge(PtrState(), /*TopDown=*/false);
1708}
1709
1710namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001711 /// \brief The main ARC optimization pass.
John McCall9fbd3182011-06-15 23:37:01 +00001712 class ObjCARCOpt : public FunctionPass {
1713 bool Changed;
1714 ProvenanceAnalysis PA;
1715
Michael Gottesman81c61212013-01-14 00:35:14 +00001716 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001717 bool Run;
1718
Michael Gottesman81c61212013-01-14 00:35:14 +00001719 /// Declarations for ObjC runtime functions, for use in creating calls to
1720 /// them. These are initialized lazily to avoid cluttering up the Module
1721 /// with unused declarations.
John McCall9fbd3182011-06-15 23:37:01 +00001722
Michael Gottesman81c61212013-01-14 00:35:14 +00001723 /// Declaration for ObjC runtime function
1724 /// objc_retainAutoreleasedReturnValue.
1725 Constant *RetainRVCallee;
1726 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1727 Constant *AutoreleaseRVCallee;
1728 /// Declaration for ObjC runtime function objc_release.
1729 Constant *ReleaseCallee;
1730 /// Declaration for ObjC runtime function objc_retain.
1731 Constant *RetainCallee;
1732 /// Declaration for ObjC runtime function objc_retainBlock.
1733 Constant *RetainBlockCallee;
1734 /// Declaration for ObjC runtime function objc_autorelease.
1735 Constant *AutoreleaseCallee;
1736
1737 /// Flags which determine whether each of the interesting runtine functions
1738 /// is in fact used in the current function.
John McCall9fbd3182011-06-15 23:37:01 +00001739 unsigned UsedInThisFunction;
1740
Michael Gottesman81c61212013-01-14 00:35:14 +00001741 /// The Metadata Kind for clang.imprecise_release metadata.
John McCall9fbd3182011-06-15 23:37:01 +00001742 unsigned ImpreciseReleaseMDKind;
1743
Michael Gottesman81c61212013-01-14 00:35:14 +00001744 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana974bea2011-10-17 22:53:25 +00001745 unsigned CopyOnEscapeMDKind;
1746
Michael Gottesman81c61212013-01-14 00:35:14 +00001747 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohmandbe266b2012-02-17 18:59:53 +00001748 unsigned NoObjCARCExceptionsMDKind;
1749
John McCall9fbd3182011-06-15 23:37:01 +00001750 Constant *getRetainRVCallee(Module *M);
1751 Constant *getAutoreleaseRVCallee(Module *M);
1752 Constant *getReleaseCallee(Module *M);
1753 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001754 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001755 Constant *getAutoreleaseCallee(Module *M);
1756
Dan Gohman79522dc2012-01-13 00:39:07 +00001757 bool IsRetainBlockOptimizable(const Instruction *Inst);
1758
John McCall9fbd3182011-06-15 23:37:01 +00001759 void OptimizeRetainCall(Function &F, Instruction *Retain);
1760 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001761 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1762 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001763 void OptimizeIndividualCalls(Function &F);
1764
1765 void CheckForCFGHazards(const BasicBlock *BB,
1766 DenseMap<const BasicBlock *, BBState> &BBStates,
1767 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001768 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001769 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001770 MapVector<Value *, RRInfo> &Retains,
1771 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001772 bool VisitBottomUp(BasicBlock *BB,
1773 DenseMap<const BasicBlock *, BBState> &BBStates,
1774 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001775 bool VisitInstructionTopDown(Instruction *Inst,
1776 DenseMap<Value *, RRInfo> &Releases,
1777 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001778 bool VisitTopDown(BasicBlock *BB,
1779 DenseMap<const BasicBlock *, BBState> &BBStates,
1780 DenseMap<Value *, RRInfo> &Releases);
1781 bool Visit(Function &F,
1782 DenseMap<const BasicBlock *, BBState> &BBStates,
1783 MapVector<Value *, RRInfo> &Retains,
1784 DenseMap<Value *, RRInfo> &Releases);
1785
1786 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1787 MapVector<Value *, RRInfo> &Retains,
1788 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001789 SmallVectorImpl<Instruction *> &DeadInsts,
1790 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001791
1792 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1793 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001794 DenseMap<Value *, RRInfo> &Releases,
1795 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001796
1797 void OptimizeWeakCalls(Function &F);
1798
1799 bool OptimizeSequences(Function &F);
1800
1801 void OptimizeReturns(Function &F);
1802
1803 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1804 virtual bool doInitialization(Module &M);
1805 virtual bool runOnFunction(Function &F);
1806 virtual void releaseMemory();
1807
1808 public:
1809 static char ID;
1810 ObjCARCOpt() : FunctionPass(ID) {
1811 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1812 }
1813 };
1814}
1815
1816char ObjCARCOpt::ID = 0;
1817INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1818 "objc-arc", "ObjC ARC optimization", false, false)
1819INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1820INITIALIZE_PASS_END(ObjCARCOpt,
1821 "objc-arc", "ObjC ARC optimization", false, false)
1822
1823Pass *llvm::createObjCARCOptPass() {
1824 return new ObjCARCOpt();
1825}
1826
1827void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1828 AU.addRequired<ObjCARCAliasAnalysis>();
1829 AU.addRequired<AliasAnalysis>();
1830 // ARC optimization doesn't currently split critical edges.
1831 AU.setPreservesCFG();
1832}
1833
Dan Gohman79522dc2012-01-13 00:39:07 +00001834bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1835 // Without the magic metadata tag, we have to assume this might be an
1836 // objc_retainBlock call inserted to convert a block pointer to an id,
1837 // in which case it really is needed.
1838 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1839 return false;
1840
1841 // If the pointer "escapes" (not including being used in a call),
1842 // the copy may be needed.
1843 if (DoesObjCBlockEscape(Inst))
1844 return false;
1845
1846 // Otherwise, it's not needed.
1847 return true;
1848}
1849
John McCall9fbd3182011-06-15 23:37:01 +00001850Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1851 if (!RetainRVCallee) {
1852 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001853 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001854 Type *Params[] = { I8X };
1855 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001856 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001857 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001858 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001859 RetainRVCallee =
1860 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001861 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001862 }
1863 return RetainRVCallee;
1864}
1865
1866Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1867 if (!AutoreleaseRVCallee) {
1868 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001869 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001870 Type *Params[] = { I8X };
1871 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001872 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001873 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001874 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001875 AutoreleaseRVCallee =
1876 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001877 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001878 }
1879 return AutoreleaseRVCallee;
1880}
1881
1882Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1883 if (!ReleaseCallee) {
1884 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001885 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001886 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001887 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001888 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001889 ReleaseCallee =
1890 M->getOrInsertFunction(
1891 "objc_release",
1892 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001893 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001894 }
1895 return ReleaseCallee;
1896}
1897
1898Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1899 if (!RetainCallee) {
1900 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001901 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001902 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001903 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001904 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001905 RetainCallee =
1906 M->getOrInsertFunction(
1907 "objc_retain",
1908 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001909 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001910 }
1911 return RetainCallee;
1912}
1913
Dan Gohman44280692011-07-22 22:29:21 +00001914Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1915 if (!RetainBlockCallee) {
1916 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001917 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001918 // objc_retainBlock is not nounwind because it calls user copy constructors
1919 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001920 RetainBlockCallee =
1921 M->getOrInsertFunction(
1922 "objc_retainBlock",
1923 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001924 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001925 }
1926 return RetainBlockCallee;
1927}
1928
John McCall9fbd3182011-06-15 23:37:01 +00001929Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1930 if (!AutoreleaseCallee) {
1931 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001932 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001933 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001934 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001935 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001936 AutoreleaseCallee =
1937 M->getOrInsertFunction(
1938 "objc_autorelease",
1939 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001940 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001941 }
1942 return AutoreleaseCallee;
1943}
1944
Michael Gottesman81c61212013-01-14 00:35:14 +00001945/// Test whether the given value is possible a reference-counted pointer,
1946/// including tests which utilize AliasAnalysis.
Dan Gohman230768b2012-09-04 23:16:20 +00001947static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1948 // First make the rudimentary check.
1949 if (!IsPotentialUse(Op))
1950 return false;
1951
1952 // Objects in constant memory are not reference-counted.
1953 if (AA.pointsToConstantMemory(Op))
1954 return false;
1955
1956 // Pointers in constant memory are not pointing to reference-counted objects.
1957 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1958 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1959 return false;
1960
1961 // Otherwise assume the worst.
1962 return true;
1963}
1964
Michael Gottesman81c61212013-01-14 00:35:14 +00001965/// Test whether the given instruction can result in a reference count
1966/// modification (positive or negative) for the pointer's object.
John McCall9fbd3182011-06-15 23:37:01 +00001967static bool
1968CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1969 ProvenanceAnalysis &PA, InstructionClass Class) {
1970 switch (Class) {
1971 case IC_Autorelease:
1972 case IC_AutoreleaseRV:
1973 case IC_User:
1974 // These operations never directly modify a reference count.
1975 return false;
1976 default: break;
1977 }
1978
1979 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1980 assert(CS && "Only calls can alter reference counts!");
1981
1982 // See if AliasAnalysis can help us with the call.
1983 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1984 if (AliasAnalysis::onlyReadsMemory(MRB))
1985 return false;
1986 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1987 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1988 I != E; ++I) {
1989 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001990 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001991 return true;
1992 }
1993 return false;
1994 }
1995
1996 // Assume the worst.
1997 return true;
1998}
1999
Michael Gottesman81c61212013-01-14 00:35:14 +00002000/// Test whether the given instruction can "use" the given pointer's object in a
2001/// way that requires the reference count to be positive.
John McCall9fbd3182011-06-15 23:37:01 +00002002static bool
2003CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2004 InstructionClass Class) {
2005 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2006 if (Class == IC_Call)
2007 return false;
2008
2009 // Consider various instructions which may have pointer arguments which are
2010 // not "uses".
2011 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2012 // Comparing a pointer with null, or any other constant, isn't really a use,
2013 // because we don't care what the pointer points to, or about the values
2014 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00002015 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00002016 return false;
2017 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2018 // For calls, just check the arguments (and not the callee operand).
2019 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2020 OE = CS.arg_end(); OI != OE; ++OI) {
2021 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002022 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002023 return true;
2024 }
2025 return false;
2026 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2027 // Special-case stores, because we don't care about the stored value, just
2028 // the store address.
2029 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2030 // If we can't tell what the underlying object was, assume there is a
2031 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00002032 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00002033 }
2034
2035 // Check each operand for a match.
2036 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2037 OI != OE; ++OI) {
2038 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002039 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002040 return true;
2041 }
2042 return false;
2043}
2044
Michael Gottesman81c61212013-01-14 00:35:14 +00002045/// Test whether the given instruction can autorelease any pointer or cause an
2046/// autoreleasepool pop.
John McCall9fbd3182011-06-15 23:37:01 +00002047static bool
2048CanInterruptRV(InstructionClass Class) {
2049 switch (Class) {
2050 case IC_AutoreleasepoolPop:
2051 case IC_CallOrUser:
2052 case IC_Call:
2053 case IC_Autorelease:
2054 case IC_AutoreleaseRV:
2055 case IC_FusedRetainAutorelease:
2056 case IC_FusedRetainAutoreleaseRV:
2057 return true;
2058 default:
2059 return false;
2060 }
2061}
2062
2063namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00002064 /// \enum DependenceKind
2065 /// \brief Defines different dependence kinds among various ARC constructs.
2066 ///
2067 /// There are several kinds of dependence-like concepts in use here.
2068 ///
John McCall9fbd3182011-06-15 23:37:01 +00002069 enum DependenceKind {
2070 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002071 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002072 CanChangeRetainCount,
2073 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2074 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2075 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2076 };
2077}
2078
Michael Gottesman81c61212013-01-14 00:35:14 +00002079/// Test if there can be dependencies on Inst through Arg. This function only
2080/// tests dependencies relevant for removing pairs of calls.
John McCall9fbd3182011-06-15 23:37:01 +00002081static bool
2082Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2083 ProvenanceAnalysis &PA) {
2084 // If we've reached the definition of Arg, stop.
2085 if (Inst == Arg)
2086 return true;
2087
2088 switch (Flavor) {
2089 case NeedsPositiveRetainCount: {
2090 InstructionClass Class = GetInstructionClass(Inst);
2091 switch (Class) {
2092 case IC_AutoreleasepoolPop:
2093 case IC_AutoreleasepoolPush:
2094 case IC_None:
2095 return false;
2096 default:
2097 return CanUse(Inst, Arg, PA, Class);
2098 }
2099 }
2100
Dan Gohman511568d2012-04-13 00:59:57 +00002101 case AutoreleasePoolBoundary: {
2102 InstructionClass Class = GetInstructionClass(Inst);
2103 switch (Class) {
2104 case IC_AutoreleasepoolPop:
2105 case IC_AutoreleasepoolPush:
2106 // These mark the end and begin of an autorelease pool scope.
2107 return true;
2108 default:
2109 // Nothing else does this.
2110 return false;
2111 }
2112 }
2113
John McCall9fbd3182011-06-15 23:37:01 +00002114 case CanChangeRetainCount: {
2115 InstructionClass Class = GetInstructionClass(Inst);
2116 switch (Class) {
2117 case IC_AutoreleasepoolPop:
2118 // Conservatively assume this can decrement any count.
2119 return true;
2120 case IC_AutoreleasepoolPush:
2121 case IC_None:
2122 return false;
2123 default:
2124 return CanAlterRefCount(Inst, Arg, PA, Class);
2125 }
2126 }
2127
2128 case RetainAutoreleaseDep:
2129 switch (GetBasicInstructionClass(Inst)) {
2130 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002131 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002132 // Don't merge an objc_autorelease with an objc_retain inside a different
2133 // autoreleasepool scope.
2134 return true;
2135 case IC_Retain:
2136 case IC_RetainRV:
2137 // Check for a retain of the same pointer for merging.
2138 return GetObjCArg(Inst) == Arg;
2139 default:
2140 // Nothing else matters for objc_retainAutorelease formation.
2141 return false;
2142 }
John McCall9fbd3182011-06-15 23:37:01 +00002143
2144 case RetainAutoreleaseRVDep: {
2145 InstructionClass Class = GetBasicInstructionClass(Inst);
2146 switch (Class) {
2147 case IC_Retain:
2148 case IC_RetainRV:
2149 // Check for a retain of the same pointer for merging.
2150 return GetObjCArg(Inst) == Arg;
2151 default:
2152 // Anything that can autorelease interrupts
2153 // retainAutoreleaseReturnValue formation.
2154 return CanInterruptRV(Class);
2155 }
John McCall9fbd3182011-06-15 23:37:01 +00002156 }
2157
2158 case RetainRVDep:
2159 return CanInterruptRV(GetBasicInstructionClass(Inst));
2160 }
2161
2162 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002163}
2164
Michael Gottesman81c61212013-01-14 00:35:14 +00002165/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2166/// non-local dependencies on Arg.
2167///
John McCall9fbd3182011-06-15 23:37:01 +00002168/// TODO: Cache results?
2169static void
2170FindDependencies(DependenceKind Flavor,
2171 const Value *Arg,
2172 BasicBlock *StartBB, Instruction *StartInst,
2173 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2174 SmallPtrSet<const BasicBlock *, 4> &Visited,
2175 ProvenanceAnalysis &PA) {
2176 BasicBlock::iterator StartPos = StartInst;
2177
2178 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2179 Worklist.push_back(std::make_pair(StartBB, StartPos));
2180 do {
2181 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2182 Worklist.pop_back_val();
2183 BasicBlock *LocalStartBB = Pair.first;
2184 BasicBlock::iterator LocalStartPos = Pair.second;
2185 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2186 for (;;) {
2187 if (LocalStartPos == StartBBBegin) {
2188 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2189 if (PI == PE)
2190 // If we've reached the function entry, produce a null dependence.
2191 DependingInstructions.insert(0);
2192 else
2193 // Add the predecessors to the worklist.
2194 do {
2195 BasicBlock *PredBB = *PI;
2196 if (Visited.insert(PredBB))
2197 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2198 } while (++PI != PE);
2199 break;
2200 }
2201
2202 Instruction *Inst = --LocalStartPos;
2203 if (Depends(Flavor, Inst, Arg, PA)) {
2204 DependingInstructions.insert(Inst);
2205 break;
2206 }
2207 }
2208 } while (!Worklist.empty());
2209
2210 // Determine whether the original StartBB post-dominates all of the blocks we
2211 // visited. If not, insert a sentinal indicating that most optimizations are
2212 // not safe.
2213 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2214 E = Visited.end(); I != E; ++I) {
2215 const BasicBlock *BB = *I;
2216 if (BB == StartBB)
2217 continue;
2218 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2219 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2220 const BasicBlock *Succ = *SI;
2221 if (Succ != StartBB && !Visited.count(Succ)) {
2222 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2223 return;
2224 }
2225 }
2226 }
2227}
2228
2229static bool isNullOrUndef(const Value *V) {
2230 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2231}
2232
2233static bool isNoopInstruction(const Instruction *I) {
2234 return isa<BitCastInst>(I) ||
2235 (isa<GetElementPtrInst>(I) &&
2236 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2237}
2238
Michael Gottesman81c61212013-01-14 00:35:14 +00002239/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2240/// return value.
John McCall9fbd3182011-06-15 23:37:01 +00002241void
2242ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002243 ImmutableCallSite CS(GetObjCArg(Retain));
2244 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002245 if (!Call) return;
2246 if (Call->getParent() != Retain->getParent()) return;
2247
2248 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002249 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002250 ++I;
2251 while (isNoopInstruction(I)) ++I;
2252 if (&*I != Retain)
2253 return;
2254
2255 // Turn it to an objc_retainAutoreleasedReturnValue..
2256 Changed = true;
2257 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002258
Michael Gottesman715f6a62013-01-04 21:30:38 +00002259 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002260 "objc_retain => objc_retainAutoreleasedReturnValue"
2261 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002262 " Old: "
2263 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002264
John McCall9fbd3182011-06-15 23:37:01 +00002265 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002266
2267 DEBUG(dbgs() << " New: "
2268 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002269}
2270
Michael Gottesman81c61212013-01-14 00:35:14 +00002271/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2272/// not a return value. Or, if it can be paired with an
2273/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002274bool
2275ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002276 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002277 const Value *Arg = GetObjCArg(RetainRV);
2278 ImmutableCallSite CS(Arg);
2279 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002280 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002281 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002282 ++I;
2283 while (isNoopInstruction(I)) ++I;
2284 if (&*I == RetainRV)
2285 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002286 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002287 BasicBlock *RetainRVParent = RetainRV->getParent();
2288 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002289 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002290 while (isNoopInstruction(I)) ++I;
2291 if (&*I == RetainRV)
2292 return false;
2293 }
John McCall9fbd3182011-06-15 23:37:01 +00002294 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002295 }
John McCall9fbd3182011-06-15 23:37:01 +00002296
2297 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2298 // pointer. In this case, we can delete the pair.
2299 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2300 if (I != Begin) {
2301 do --I; while (I != Begin && isNoopInstruction(I));
2302 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2303 GetObjCArg(I) == Arg) {
2304 Changed = true;
2305 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002306
Michael Gottesman87a0f022013-01-05 17:55:35 +00002307 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2308 << " Erasing " << *RetainRV
2309 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002310
John McCall9fbd3182011-06-15 23:37:01 +00002311 EraseInstruction(I);
2312 EraseInstruction(RetainRV);
2313 return true;
2314 }
2315 }
2316
2317 // Turn it to a plain objc_retain.
2318 Changed = true;
2319 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002320
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002321 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2322 "objc_retainAutoreleasedReturnValue => "
2323 "objc_retain since the operand is not a return value.\n"
2324 " Old: "
2325 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002326
John McCall9fbd3182011-06-15 23:37:01 +00002327 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002328
2329 DEBUG(dbgs() << " New: "
2330 << *RetainRV << "\n");
2331
John McCall9fbd3182011-06-15 23:37:01 +00002332 return false;
2333}
2334
Michael Gottesman81c61212013-01-14 00:35:14 +00002335/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2336/// used as a return value.
John McCall9fbd3182011-06-15 23:37:01 +00002337void
Michael Gottesman0e385452013-01-12 01:25:19 +00002338ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2339 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002340 // Check for a return of the pointer value.
2341 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002342 SmallVector<const Value *, 2> Users;
2343 Users.push_back(Ptr);
2344 do {
2345 Ptr = Users.pop_back_val();
2346 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2347 UI != UE; ++UI) {
2348 const User *I = *UI;
2349 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2350 return;
2351 if (isa<BitCastInst>(I))
2352 Users.push_back(I);
2353 }
2354 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002355
2356 Changed = true;
2357 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002358
2359 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2360 "objc_autoreleaseReturnValue => "
2361 "objc_autorelease since its operand is not used as a return "
2362 "value.\n"
2363 " Old: "
2364 << *AutoreleaseRV << "\n");
2365
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002366 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2367 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002368 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002369 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002370 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002371
Michael Gottesman48239c72013-01-06 21:07:11 +00002372 DEBUG(dbgs() << " New: "
2373 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002374
John McCall9fbd3182011-06-15 23:37:01 +00002375}
2376
Michael Gottesman81c61212013-01-14 00:35:14 +00002377/// Visit each call, one at a time, and make simplifications without doing any
2378/// additional analysis.
John McCall9fbd3182011-06-15 23:37:01 +00002379void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2380 // Reset all the flags in preparation for recomputing them.
2381 UsedInThisFunction = 0;
2382
2383 // Visit all objc_* calls in F.
2384 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2385 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002386
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002387 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002388 *Inst << "\n");
2389
John McCall9fbd3182011-06-15 23:37:01 +00002390 InstructionClass Class = GetBasicInstructionClass(Inst);
2391
2392 switch (Class) {
2393 default: break;
2394
2395 // Delete no-op casts. These function calls have special semantics, but
2396 // the semantics are entirely implemented via lowering in the front-end,
2397 // so by the time they reach the optimizer, they are just no-op calls
2398 // which return their argument.
2399 //
2400 // There are gray areas here, as the ability to cast reference-counted
2401 // pointers to raw void* and back allows code to break ARC assumptions,
2402 // however these are currently considered to be unimportant.
2403 case IC_NoopCast:
2404 Changed = true;
2405 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002406 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2407 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002408 EraseInstruction(Inst);
2409 continue;
2410
2411 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2412 case IC_StoreWeak:
2413 case IC_LoadWeak:
2414 case IC_LoadWeakRetained:
2415 case IC_InitWeak:
2416 case IC_DestroyWeak: {
2417 CallInst *CI = cast<CallInst>(Inst);
2418 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002419 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002420 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002421 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2422 Constant::getNullValue(Ty),
2423 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002424 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002425 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2426 "pointer-to-weak-pointer is undefined behavior.\n"
2427 " Old = " << *CI <<
2428 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002429 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002430 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002431 CI->eraseFromParent();
2432 continue;
2433 }
2434 break;
2435 }
2436 case IC_CopyWeak:
2437 case IC_MoveWeak: {
2438 CallInst *CI = cast<CallInst>(Inst);
2439 if (isNullOrUndef(CI->getArgOperand(0)) ||
2440 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002441 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002442 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002443 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2444 Constant::getNullValue(Ty),
2445 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002446
2447 llvm::Value *NewValue = UndefValue::get(CI->getType());
2448 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2449 "pointer-to-weak-pointer is undefined behavior.\n"
2450 " Old = " << *CI <<
2451 "\n New = " <<
2452 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002453
Michael Gottesmane5494922013-01-06 21:54:30 +00002454 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002455 CI->eraseFromParent();
2456 continue;
2457 }
2458 break;
2459 }
2460 case IC_Retain:
2461 OptimizeRetainCall(F, Inst);
2462 break;
2463 case IC_RetainRV:
2464 if (OptimizeRetainRVCall(F, Inst))
2465 continue;
2466 break;
2467 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002468 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002469 break;
2470 }
2471
2472 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2473 if (IsAutorelease(Class) && Inst->use_empty()) {
2474 CallInst *Call = cast<CallInst>(Inst);
2475 const Value *Arg = Call->getArgOperand(0);
2476 Arg = FindSingleUseIdentifiedObject(Arg);
2477 if (Arg) {
2478 Changed = true;
2479 ++NumAutoreleases;
2480
2481 // Create the declaration lazily.
2482 LLVMContext &C = Inst->getContext();
2483 CallInst *NewCall =
2484 CallInst::Create(getReleaseCallee(F.getParent()),
2485 Call->getArgOperand(0), "", Call);
2486 NewCall->setMetadata(ImpreciseReleaseMDKind,
2487 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002488
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002489 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2490 "objc_autorelease(x) with objc_release(x) since x is "
2491 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002492 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002493 "\n New: " <<
2494 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002495
John McCall9fbd3182011-06-15 23:37:01 +00002496 EraseInstruction(Call);
2497 Inst = NewCall;
2498 Class = IC_Release;
2499 }
2500 }
2501
2502 // For functions which can never be passed stack arguments, add
2503 // a tail keyword.
2504 if (IsAlwaysTail(Class)) {
2505 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002506 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2507 " to function since it can never be passed stack args: " << *Inst <<
2508 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002509 cast<CallInst>(Inst)->setTailCall();
2510 }
2511
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002512 // Ensure that functions that can never have a "tail" keyword due to the
2513 // semantics of ARC truly do not do so.
2514 if (IsNeverTail(Class)) {
2515 Changed = true;
2516 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2517 " from function: " << *Inst <<
2518 "\n");
2519 cast<CallInst>(Inst)->setTailCall(false);
2520 }
2521
John McCall9fbd3182011-06-15 23:37:01 +00002522 // Set nounwind as needed.
2523 if (IsNoThrow(Class)) {
2524 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002525 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2526 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002527 cast<CallInst>(Inst)->setDoesNotThrow();
2528 }
2529
2530 if (!IsNoopOnNull(Class)) {
2531 UsedInThisFunction |= 1 << Class;
2532 continue;
2533 }
2534
2535 const Value *Arg = GetObjCArg(Inst);
2536
2537 // ARC calls with null are no-ops. Delete them.
2538 if (isNullOrUndef(Arg)) {
2539 Changed = true;
2540 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002541 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2542 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002543 EraseInstruction(Inst);
2544 continue;
2545 }
2546
2547 // Keep track of which of retain, release, autorelease, and retain_block
2548 // are actually present in this function.
2549 UsedInThisFunction |= 1 << Class;
2550
2551 // If Arg is a PHI, and one or more incoming values to the
2552 // PHI are null, and the call is control-equivalent to the PHI, and there
2553 // are no relevant side effects between the PHI and the call, the call
2554 // could be pushed up to just those paths with non-null incoming values.
2555 // For now, don't bother splitting critical edges for this.
2556 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2557 Worklist.push_back(std::make_pair(Inst, Arg));
2558 do {
2559 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2560 Inst = Pair.first;
2561 Arg = Pair.second;
2562
2563 const PHINode *PN = dyn_cast<PHINode>(Arg);
2564 if (!PN) continue;
2565
2566 // Determine if the PHI has any null operands, or any incoming
2567 // critical edges.
2568 bool HasNull = false;
2569 bool HasCriticalEdges = false;
2570 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2571 Value *Incoming =
2572 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2573 if (isNullOrUndef(Incoming))
2574 HasNull = true;
2575 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2576 .getNumSuccessors() != 1) {
2577 HasCriticalEdges = true;
2578 break;
2579 }
2580 }
2581 // If we have null operands and no critical edges, optimize.
2582 if (!HasCriticalEdges && HasNull) {
2583 SmallPtrSet<Instruction *, 4> DependingInstructions;
2584 SmallPtrSet<const BasicBlock *, 4> Visited;
2585
2586 // Check that there is nothing that cares about the reference
2587 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002588 switch (Class) {
2589 case IC_Retain:
2590 case IC_RetainBlock:
2591 // These can always be moved up.
2592 break;
2593 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002594 // These can't be moved across things that care about the retain
2595 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002596 FindDependencies(NeedsPositiveRetainCount, Arg,
2597 Inst->getParent(), Inst,
2598 DependingInstructions, Visited, PA);
2599 break;
2600 case IC_Autorelease:
2601 // These can't be moved across autorelease pool scope boundaries.
2602 FindDependencies(AutoreleasePoolBoundary, Arg,
2603 Inst->getParent(), Inst,
2604 DependingInstructions, Visited, PA);
2605 break;
2606 case IC_RetainRV:
2607 case IC_AutoreleaseRV:
2608 // Don't move these; the RV optimization depends on the autoreleaseRV
2609 // being tail called, and the retainRV being immediately after a call
2610 // (which might still happen if we get lucky with codegen layout, but
2611 // it's not worth taking the chance).
2612 continue;
2613 default:
2614 llvm_unreachable("Invalid dependence flavor");
2615 }
2616
John McCall9fbd3182011-06-15 23:37:01 +00002617 if (DependingInstructions.size() == 1 &&
2618 *DependingInstructions.begin() == PN) {
2619 Changed = true;
2620 ++NumPartialNoops;
2621 // Clone the call into each predecessor that has a non-null value.
2622 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002623 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002624 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2625 Value *Incoming =
2626 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2627 if (!isNullOrUndef(Incoming)) {
2628 CallInst *Clone = cast<CallInst>(CInst->clone());
2629 Value *Op = PN->getIncomingValue(i);
2630 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2631 if (Op->getType() != ParamTy)
2632 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2633 Clone->setArgOperand(0, Op);
2634 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002635
2636 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2637 << *CInst << "\n"
2638 " And inserting "
2639 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002640 Worklist.push_back(std::make_pair(Clone, Incoming));
2641 }
2642 }
2643 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002644 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002645 EraseInstruction(CInst);
2646 continue;
2647 }
2648 }
2649 } while (!Worklist.empty());
2650 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002651 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002652}
2653
Michael Gottesman81c61212013-01-14 00:35:14 +00002654/// Check for critical edges, loop boundaries, irreducible control flow, or
2655/// other CFG structures where moving code across the edge would result in it
2656/// being executed more.
John McCall9fbd3182011-06-15 23:37:01 +00002657void
2658ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2659 DenseMap<const BasicBlock *, BBState> &BBStates,
2660 BBState &MyStates) const {
2661 // If any top-down local-use or possible-dec has a succ which is earlier in
2662 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002663 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002664 E = MyStates.top_down_ptr_end(); I != E; ++I)
2665 switch (I->second.GetSeq()) {
2666 default: break;
2667 case S_Use: {
2668 const Value *Arg = I->first;
2669 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2670 bool SomeSuccHasSame = false;
2671 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002672 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002673 succ_const_iterator SI(TI), SE(TI, false);
2674
2675 // If the terminator is an invoke marked with the
2676 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2677 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002678 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2679 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2680 "terminator marked with "
2681 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2682 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002683 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002684 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002685
2686 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002687 Sequence SuccSSeq = S_None;
2688 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002689 // If VisitBottomUp has pointer information for this successor, take
2690 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002691 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2692 BBStates.find(*SI);
2693 assert(BBI != BBStates.end());
2694 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2695 SuccSSeq = SuccS.GetSeq();
2696 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002697 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002698 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002699 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002700 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002701 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002702 break;
2703 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002704 continue;
2705 }
John McCall9fbd3182011-06-15 23:37:01 +00002706 case S_Use:
2707 SomeSuccHasSame = true;
2708 break;
2709 case S_Stop:
2710 case S_Release:
2711 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002712 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002713 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002714 break;
2715 case S_Retain:
2716 llvm_unreachable("bottom-up pointer in retain state!");
2717 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002718 }
John McCall9fbd3182011-06-15 23:37:01 +00002719 // If the state at the other end of any of the successor edges
2720 // matches the current state, require all edges to match. This
2721 // guards against loops in the middle of a sequence.
2722 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002723 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002724 break;
John McCall9fbd3182011-06-15 23:37:01 +00002725 }
2726 case S_CanRelease: {
2727 const Value *Arg = I->first;
2728 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2729 bool SomeSuccHasSame = false;
2730 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002731 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002732 succ_const_iterator SI(TI), SE(TI, false);
2733
2734 // If the terminator is an invoke marked with the
2735 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2736 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002737 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2738 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2739 "terminator marked with "
2740 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2741 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002742 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002743 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002744
2745 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002746 Sequence SuccSSeq = S_None;
2747 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002748 // If VisitBottomUp has pointer information for this successor, take
2749 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002750 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2751 BBStates.find(*SI);
2752 assert(BBI != BBStates.end());
2753 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2754 SuccSSeq = SuccS.GetSeq();
2755 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002756 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002757 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002758 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002759 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002760 break;
2761 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002762 continue;
2763 }
John McCall9fbd3182011-06-15 23:37:01 +00002764 case S_CanRelease:
2765 SomeSuccHasSame = true;
2766 break;
2767 case S_Stop:
2768 case S_Release:
2769 case S_MovableRelease:
2770 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002771 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002772 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002773 break;
2774 case S_Retain:
2775 llvm_unreachable("bottom-up pointer in retain state!");
2776 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002777 }
John McCall9fbd3182011-06-15 23:37:01 +00002778 // If the state at the other end of any of the successor edges
2779 // matches the current state, require all edges to match. This
2780 // guards against loops in the middle of a sequence.
2781 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002782 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002783 break;
John McCall9fbd3182011-06-15 23:37:01 +00002784 }
2785 }
2786}
2787
2788bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002789ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002790 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002791 MapVector<Value *, RRInfo> &Retains,
2792 BBState &MyStates) {
2793 bool NestingDetected = false;
2794 InstructionClass Class = GetInstructionClass(Inst);
2795 const Value *Arg = 0;
2796
2797 switch (Class) {
2798 case IC_Release: {
2799 Arg = GetObjCArg(Inst);
2800
2801 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2802
2803 // If we see two releases in a row on the same pointer. If so, make
2804 // a note, and we'll cicle back to revisit it after we've
2805 // hopefully eliminated the second release, which may allow us to
2806 // eliminate the first release too.
2807 // Theoretically we could implement removal of nested retain+release
2808 // pairs by making PtrState hold a stack of states, but this is
2809 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmancf140052013-01-13 07:00:51 +00002810 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2811 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2812 "releases (i.e. a release pair)\n");
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002813 NestingDetected = true;
Michael Gottesmancf140052013-01-13 07:00:51 +00002814 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002815
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002816 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002817 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002818 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002819 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002820 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2821 S.RRI.Calls.insert(Inst);
2822
Dan Gohman230768b2012-09-04 23:16:20 +00002823 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002824 break;
2825 }
2826 case IC_RetainBlock:
2827 // An objc_retainBlock call with just a use may need to be kept,
2828 // because it may be copying a block from the stack to the heap.
2829 if (!IsRetainBlockOptimizable(Inst))
2830 break;
2831 // FALLTHROUGH
2832 case IC_Retain:
2833 case IC_RetainRV: {
2834 Arg = GetObjCArg(Inst);
2835
2836 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002837 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002838
2839 switch (S.GetSeq()) {
2840 case S_Stop:
2841 case S_Release:
2842 case S_MovableRelease:
2843 case S_Use:
2844 S.RRI.ReverseInsertPts.clear();
2845 // FALL THROUGH
2846 case S_CanRelease:
2847 // Don't do retain+release tracking for IC_RetainRV, because it's
2848 // better to let it remain as the first instruction after a call.
2849 if (Class != IC_RetainRV) {
2850 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2851 Retains[Inst] = S.RRI;
2852 }
2853 S.ClearSequenceProgress();
2854 break;
2855 case S_None:
2856 break;
2857 case S_Retain:
2858 llvm_unreachable("bottom-up pointer in retain state!");
2859 }
2860 return NestingDetected;
2861 }
2862 case IC_AutoreleasepoolPop:
2863 // Conservatively, clear MyStates for all known pointers.
2864 MyStates.clearBottomUpPointers();
2865 return NestingDetected;
2866 case IC_AutoreleasepoolPush:
2867 case IC_None:
2868 // These are irrelevant.
2869 return NestingDetected;
2870 default:
2871 break;
2872 }
2873
2874 // Consider any other possible effects of this instruction on each
2875 // pointer being tracked.
2876 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2877 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2878 const Value *Ptr = MI->first;
2879 if (Ptr == Arg)
2880 continue; // Handled above.
2881 PtrState &S = MI->second;
2882 Sequence Seq = S.GetSeq();
2883
2884 // Check for possible releases.
2885 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002886 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002887 switch (Seq) {
2888 case S_Use:
2889 S.SetSeq(S_CanRelease);
2890 continue;
2891 case S_CanRelease:
2892 case S_Release:
2893 case S_MovableRelease:
2894 case S_Stop:
2895 case S_None:
2896 break;
2897 case S_Retain:
2898 llvm_unreachable("bottom-up pointer in retain state!");
2899 }
2900 }
2901
2902 // Check for possible direct uses.
2903 switch (Seq) {
2904 case S_Release:
2905 case S_MovableRelease:
2906 if (CanUse(Inst, Ptr, PA, Class)) {
2907 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002908 // If this is an invoke instruction, we're scanning it as part of
2909 // one of its successor blocks, since we can't insert code after it
2910 // in its own block, and we don't want to split critical edges.
2911 if (isa<InvokeInst>(Inst))
2912 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2913 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002914 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002915 S.SetSeq(S_Use);
2916 } else if (Seq == S_Release &&
2917 (Class == IC_User || Class == IC_CallOrUser)) {
2918 // Non-movable releases depend on any possible objc pointer use.
2919 S.SetSeq(S_Stop);
2920 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002921 // As above; handle invoke specially.
2922 if (isa<InvokeInst>(Inst))
2923 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2924 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002925 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002926 }
2927 break;
2928 case S_Stop:
2929 if (CanUse(Inst, Ptr, PA, Class))
2930 S.SetSeq(S_Use);
2931 break;
2932 case S_CanRelease:
2933 case S_Use:
2934 case S_None:
2935 break;
2936 case S_Retain:
2937 llvm_unreachable("bottom-up pointer in retain state!");
2938 }
2939 }
2940
2941 return NestingDetected;
2942}
2943
2944bool
John McCall9fbd3182011-06-15 23:37:01 +00002945ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2946 DenseMap<const BasicBlock *, BBState> &BBStates,
2947 MapVector<Value *, RRInfo> &Retains) {
2948 bool NestingDetected = false;
2949 BBState &MyStates = BBStates[BB];
2950
2951 // Merge the states from each successor to compute the initial state
2952 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002953 BBState::edge_iterator SI(MyStates.succ_begin()),
2954 SE(MyStates.succ_end());
2955 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002956 const BasicBlock *Succ = *SI;
2957 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2958 assert(I != BBStates.end());
2959 MyStates.InitFromSucc(I->second);
2960 ++SI;
2961 for (; SI != SE; ++SI) {
2962 Succ = *SI;
2963 I = BBStates.find(Succ);
2964 assert(I != BBStates.end());
2965 MyStates.MergeSucc(I->second);
2966 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002967 }
John McCall9fbd3182011-06-15 23:37:01 +00002968
2969 // Visit all the instructions, bottom-up.
2970 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2971 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002972
2973 // Invoke instructions are visited as part of their successors (below).
2974 if (isa<InvokeInst>(Inst))
2975 continue;
2976
Michael Gottesmancf140052013-01-13 07:00:51 +00002977 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2978
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002979 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2980 }
2981
Dan Gohman447989c2012-04-27 18:56:31 +00002982 // If there's a predecessor with an invoke, visit the invoke as if it were
2983 // part of this block, since we can't insert code after an invoke in its own
2984 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002985 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2986 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002987 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002988 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2989 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002990 }
John McCall9fbd3182011-06-15 23:37:01 +00002991
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002992 return NestingDetected;
2993}
John McCall9fbd3182011-06-15 23:37:01 +00002994
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002995bool
2996ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2997 DenseMap<Value *, RRInfo> &Releases,
2998 BBState &MyStates) {
2999 bool NestingDetected = false;
3000 InstructionClass Class = GetInstructionClass(Inst);
3001 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003002
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003003 switch (Class) {
3004 case IC_RetainBlock:
3005 // An objc_retainBlock call with just a use may need to be kept,
3006 // because it may be copying a block from the stack to the heap.
3007 if (!IsRetainBlockOptimizable(Inst))
3008 break;
3009 // FALLTHROUGH
3010 case IC_Retain:
3011 case IC_RetainRV: {
3012 Arg = GetObjCArg(Inst);
3013
3014 PtrState &S = MyStates.getPtrTopDownState(Arg);
3015
3016 // Don't do retain+release tracking for IC_RetainRV, because it's
3017 // better to let it remain as the first instruction after a call.
3018 if (Class != IC_RetainRV) {
3019 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00003020 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003021 // hopefully eliminated the second retain, which may allow us to
3022 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00003023 // Theoretically we could implement removal of nested retain+release
3024 // pairs by making PtrState hold a stack of states, but this is
3025 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003026 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00003027 NestingDetected = true;
3028
Dan Gohman50ade652012-04-25 00:50:46 +00003029 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003030 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00003031 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00003032 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00003033 }
John McCall9fbd3182011-06-15 23:37:01 +00003034
Dan Gohman230768b2012-09-04 23:16:20 +00003035 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00003036
3037 // A retain can be a potential use; procede to the generic checking
3038 // code below.
3039 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003040 }
3041 case IC_Release: {
3042 Arg = GetObjCArg(Inst);
3043
3044 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00003045 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003046
3047 switch (S.GetSeq()) {
3048 case S_Retain:
3049 case S_CanRelease:
3050 S.RRI.ReverseInsertPts.clear();
3051 // FALL THROUGH
3052 case S_Use:
3053 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3054 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3055 Releases[Inst] = S.RRI;
3056 S.ClearSequenceProgress();
3057 break;
3058 case S_None:
3059 break;
3060 case S_Stop:
3061 case S_Release:
3062 case S_MovableRelease:
3063 llvm_unreachable("top-down pointer in release state!");
3064 }
3065 break;
3066 }
3067 case IC_AutoreleasepoolPop:
3068 // Conservatively, clear MyStates for all known pointers.
3069 MyStates.clearTopDownPointers();
3070 return NestingDetected;
3071 case IC_AutoreleasepoolPush:
3072 case IC_None:
3073 // These are irrelevant.
3074 return NestingDetected;
3075 default:
3076 break;
3077 }
3078
3079 // Consider any other possible effects of this instruction on each
3080 // pointer being tracked.
3081 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3082 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3083 const Value *Ptr = MI->first;
3084 if (Ptr == Arg)
3085 continue; // Handled above.
3086 PtrState &S = MI->second;
3087 Sequence Seq = S.GetSeq();
3088
3089 // Check for possible releases.
3090 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003091 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003092 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003093 case S_Retain:
3094 S.SetSeq(S_CanRelease);
3095 assert(S.RRI.ReverseInsertPts.empty());
3096 S.RRI.ReverseInsertPts.insert(Inst);
3097
3098 // One call can't cause a transition from S_Retain to S_CanRelease
3099 // and S_CanRelease to S_Use. If we've made the first transition,
3100 // we're done.
3101 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003102 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003103 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003104 case S_None:
3105 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003106 case S_Stop:
3107 case S_Release:
3108 case S_MovableRelease:
3109 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003110 }
3111 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003112
3113 // Check for possible direct uses.
3114 switch (Seq) {
3115 case S_CanRelease:
3116 if (CanUse(Inst, Ptr, PA, Class))
3117 S.SetSeq(S_Use);
3118 break;
3119 case S_Retain:
3120 case S_Use:
3121 case S_None:
3122 break;
3123 case S_Stop:
3124 case S_Release:
3125 case S_MovableRelease:
3126 llvm_unreachable("top-down pointer in release state!");
3127 }
John McCall9fbd3182011-06-15 23:37:01 +00003128 }
3129
3130 return NestingDetected;
3131}
3132
3133bool
3134ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3135 DenseMap<const BasicBlock *, BBState> &BBStates,
3136 DenseMap<Value *, RRInfo> &Releases) {
3137 bool NestingDetected = false;
3138 BBState &MyStates = BBStates[BB];
3139
3140 // Merge the states from each predecessor to compute the initial state
3141 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003142 BBState::edge_iterator PI(MyStates.pred_begin()),
3143 PE(MyStates.pred_end());
3144 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003145 const BasicBlock *Pred = *PI;
3146 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3147 assert(I != BBStates.end());
3148 MyStates.InitFromPred(I->second);
3149 ++PI;
3150 for (; PI != PE; ++PI) {
3151 Pred = *PI;
3152 I = BBStates.find(Pred);
3153 assert(I != BBStates.end());
3154 MyStates.MergePred(I->second);
3155 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003156 }
John McCall9fbd3182011-06-15 23:37:01 +00003157
3158 // Visit all the instructions, top-down.
3159 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3160 Instruction *Inst = I;
Michael Gottesmancf140052013-01-13 07:00:51 +00003161
3162 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3163
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003164 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003165 }
3166
3167 CheckForCFGHazards(BB, BBStates, MyStates);
3168 return NestingDetected;
3169}
3170
Dan Gohman59a1c932011-12-12 19:42:25 +00003171static void
3172ComputePostOrders(Function &F,
3173 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003174 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3175 unsigned NoObjCARCExceptionsMDKind,
3176 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman81c61212013-01-14 00:35:14 +00003177 /// The visited set, for doing DFS walks.
Dan Gohman59a1c932011-12-12 19:42:25 +00003178 SmallPtrSet<BasicBlock *, 16> Visited;
3179
3180 // Do DFS, computing the PostOrder.
3181 SmallPtrSet<BasicBlock *, 16> OnStack;
3182 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003183
3184 // Functions always have exactly one entry block, and we don't have
3185 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003186 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003187 BBState &MyStates = BBStates[EntryBB];
3188 MyStates.SetAsEntry();
3189 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3190 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003191 Visited.insert(EntryBB);
3192 OnStack.insert(EntryBB);
3193 do {
3194 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003195 BasicBlock *CurrBB = SuccStack.back().first;
3196 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3197 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003198
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003199 // If the terminator is an invoke marked with the
3200 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3201 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00003202 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3203 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3204 "terminator marked with "
3205 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3206 "edge.\n");
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003207 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00003208 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003209
3210 while (SuccStack.back().second != SE) {
3211 BasicBlock *SuccBB = *SuccStack.back().second++;
3212 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003213 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3214 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003215 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003216 BBState &SuccStates = BBStates[SuccBB];
3217 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003218 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003219 goto dfs_next_succ;
3220 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003221
3222 if (!OnStack.count(SuccBB)) {
3223 BBStates[CurrBB].addSucc(SuccBB);
3224 BBStates[SuccBB].addPred(CurrBB);
3225 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003226 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003227 OnStack.erase(CurrBB);
3228 PostOrder.push_back(CurrBB);
3229 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003230 } while (!SuccStack.empty());
3231
3232 Visited.clear();
3233
Dan Gohman59a1c932011-12-12 19:42:25 +00003234 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003235 // Functions may have many exits, and there also blocks which we treat
3236 // as exits due to ignored edges.
3237 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3238 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3239 BasicBlock *ExitBB = I;
3240 BBState &MyStates = BBStates[ExitBB];
3241 if (!MyStates.isExit())
3242 continue;
3243
Dan Gohman447989c2012-04-27 18:56:31 +00003244 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003245
3246 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003247 Visited.insert(ExitBB);
3248 while (!PredStack.empty()) {
3249 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003250 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3251 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003252 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003253 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003254 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003255 goto reverse_dfs_next_succ;
3256 }
3257 }
3258 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3259 }
3260 }
3261}
3262
Michael Gottesman81c61212013-01-14 00:35:14 +00003263// Visit the function both top-down and bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003264bool
3265ObjCARCOpt::Visit(Function &F,
3266 DenseMap<const BasicBlock *, BBState> &BBStates,
3267 MapVector<Value *, RRInfo> &Retains,
3268 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003269
3270 // Use reverse-postorder traversals, because we magically know that loops
3271 // will be well behaved, i.e. they won't repeatedly call retain on a single
3272 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3273 // class here because we want the reverse-CFG postorder to consider each
3274 // function exit point, and we want to ignore selected cycle edges.
3275 SmallVector<BasicBlock *, 16> PostOrder;
3276 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003277 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3278 NoObjCARCExceptionsMDKind,
3279 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003280
3281 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003282 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003283 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003284 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3285 I != E; ++I)
3286 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003287
Dan Gohman59a1c932011-12-12 19:42:25 +00003288 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003289 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003290 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3291 PostOrder.rbegin(), E = PostOrder.rend();
3292 I != E; ++I)
3293 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003294
3295 return TopDownNestingDetected && BottomUpNestingDetected;
3296}
3297
Michael Gottesman81c61212013-01-14 00:35:14 +00003298/// Move the calls in RetainsToMove and ReleasesToMove.
John McCall9fbd3182011-06-15 23:37:01 +00003299void ObjCARCOpt::MoveCalls(Value *Arg,
3300 RRInfo &RetainsToMove,
3301 RRInfo &ReleasesToMove,
3302 MapVector<Value *, RRInfo> &Retains,
3303 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003304 SmallVectorImpl<Instruction *> &DeadInsts,
3305 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003306 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003307 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003308
3309 // Insert the new retain and release calls.
3310 for (SmallPtrSet<Instruction *, 2>::const_iterator
3311 PI = ReleasesToMove.ReverseInsertPts.begin(),
3312 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3313 Instruction *InsertPt = *PI;
3314 Value *MyArg = ArgTy == ParamTy ? Arg :
3315 new BitCastInst(Arg, ParamTy, "", InsertPt);
3316 CallInst *Call =
3317 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003318 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003319 MyArg, "", InsertPt);
3320 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003321 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003322 Call->setMetadata(CopyOnEscapeMDKind,
3323 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003324 else
John McCall9fbd3182011-06-15 23:37:01 +00003325 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003326
3327 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3328 << "\n"
3329 " At insertion point: " << *InsertPt
3330 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003331 }
3332 for (SmallPtrSet<Instruction *, 2>::const_iterator
3333 PI = RetainsToMove.ReverseInsertPts.begin(),
3334 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003335 Instruction *InsertPt = *PI;
3336 Value *MyArg = ArgTy == ParamTy ? Arg :
3337 new BitCastInst(Arg, ParamTy, "", InsertPt);
3338 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3339 "", InsertPt);
3340 // Attach a clang.imprecise_release metadata tag, if appropriate.
3341 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3342 Call->setMetadata(ImpreciseReleaseMDKind, M);
3343 Call->setDoesNotThrow();
3344 if (ReleasesToMove.IsTailCallRelease)
3345 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003346
3347 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3348 << "\n"
3349 " At insertion point: " << *InsertPt
3350 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003351 }
3352
3353 // Delete the original retain and release calls.
3354 for (SmallPtrSet<Instruction *, 2>::const_iterator
3355 AI = RetainsToMove.Calls.begin(),
3356 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3357 Instruction *OrigRetain = *AI;
3358 Retains.blot(OrigRetain);
3359 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003360 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3361 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003362 }
3363 for (SmallPtrSet<Instruction *, 2>::const_iterator
3364 AI = ReleasesToMove.Calls.begin(),
3365 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3366 Instruction *OrigRelease = *AI;
3367 Releases.erase(OrigRelease);
3368 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003369 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3370 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003371 }
3372}
3373
Michael Gottesman81c61212013-01-14 00:35:14 +00003374/// Identify pairings between the retains and releases, and delete and/or move
3375/// them.
John McCall9fbd3182011-06-15 23:37:01 +00003376bool
3377ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3378 &BBStates,
3379 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003380 DenseMap<Value *, RRInfo> &Releases,
3381 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003382 bool AnyPairsCompletelyEliminated = false;
3383 RRInfo RetainsToMove;
3384 RRInfo ReleasesToMove;
3385 SmallVector<Instruction *, 4> NewRetains;
3386 SmallVector<Instruction *, 4> NewReleases;
3387 SmallVector<Instruction *, 8> DeadInsts;
3388
Dan Gohmand6bf2012012-04-13 18:57:48 +00003389 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003390 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003391 E = Retains.end(); I != E; ++I) {
3392 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003393 if (!V) continue; // blotted
3394
3395 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003396
3397 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3398 << "\n");
3399
John McCall9fbd3182011-06-15 23:37:01 +00003400 Value *Arg = GetObjCArg(Retain);
3401
Dan Gohman79522dc2012-01-13 00:39:07 +00003402 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003403 // not being managed by ObjC reference counting, so we can delete pairs
3404 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003405 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003406
Dan Gohman1b31ea82011-08-22 17:29:11 +00003407 // A constant pointer can't be pointing to an object on the heap. It may
3408 // be reference-counted, but it won't be deleted.
3409 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3410 if (const GlobalVariable *GV =
3411 dyn_cast<GlobalVariable>(
3412 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3413 if (GV->isConstant())
3414 KnownSafe = true;
3415
John McCall9fbd3182011-06-15 23:37:01 +00003416 // If a pair happens in a region where it is known that the reference count
3417 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003418 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003419
3420 // Connect the dots between the top-down-collected RetainsToMove and
3421 // bottom-up-collected ReleasesToMove to form sets of related calls.
3422 // This is an iterative process so that we connect multiple releases
3423 // to multiple retains if needed.
3424 unsigned OldDelta = 0;
3425 unsigned NewDelta = 0;
3426 unsigned OldCount = 0;
3427 unsigned NewCount = 0;
3428 bool FirstRelease = true;
3429 bool FirstRetain = true;
3430 NewRetains.push_back(Retain);
3431 for (;;) {
3432 for (SmallVectorImpl<Instruction *>::const_iterator
3433 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3434 Instruction *NewRetain = *NI;
3435 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3436 assert(It != Retains.end());
3437 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003438 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003439 for (SmallPtrSet<Instruction *, 2>::const_iterator
3440 LI = NewRetainRRI.Calls.begin(),
3441 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3442 Instruction *NewRetainRelease = *LI;
3443 DenseMap<Value *, RRInfo>::const_iterator Jt =
3444 Releases.find(NewRetainRelease);
3445 if (Jt == Releases.end())
3446 goto next_retain;
3447 const RRInfo &NewRetainReleaseRRI = Jt->second;
3448 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3449 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3450 OldDelta -=
3451 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3452
3453 // Merge the ReleaseMetadata and IsTailCallRelease values.
3454 if (FirstRelease) {
3455 ReleasesToMove.ReleaseMetadata =
3456 NewRetainReleaseRRI.ReleaseMetadata;
3457 ReleasesToMove.IsTailCallRelease =
3458 NewRetainReleaseRRI.IsTailCallRelease;
3459 FirstRelease = false;
3460 } else {
3461 if (ReleasesToMove.ReleaseMetadata !=
3462 NewRetainReleaseRRI.ReleaseMetadata)
3463 ReleasesToMove.ReleaseMetadata = 0;
3464 if (ReleasesToMove.IsTailCallRelease !=
3465 NewRetainReleaseRRI.IsTailCallRelease)
3466 ReleasesToMove.IsTailCallRelease = false;
3467 }
3468
3469 // Collect the optimal insertion points.
3470 if (!KnownSafe)
3471 for (SmallPtrSet<Instruction *, 2>::const_iterator
3472 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3473 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3474 RI != RE; ++RI) {
3475 Instruction *RIP = *RI;
3476 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3477 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3478 }
3479 NewReleases.push_back(NewRetainRelease);
3480 }
3481 }
3482 }
3483 NewRetains.clear();
3484 if (NewReleases.empty()) break;
3485
3486 // Back the other way.
3487 for (SmallVectorImpl<Instruction *>::const_iterator
3488 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3489 Instruction *NewRelease = *NI;
3490 DenseMap<Value *, RRInfo>::const_iterator It =
3491 Releases.find(NewRelease);
3492 assert(It != Releases.end());
3493 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003494 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003495 for (SmallPtrSet<Instruction *, 2>::const_iterator
3496 LI = NewReleaseRRI.Calls.begin(),
3497 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3498 Instruction *NewReleaseRetain = *LI;
3499 MapVector<Value *, RRInfo>::const_iterator Jt =
3500 Retains.find(NewReleaseRetain);
3501 if (Jt == Retains.end())
3502 goto next_retain;
3503 const RRInfo &NewReleaseRetainRRI = Jt->second;
3504 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3505 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3506 unsigned PathCount =
3507 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3508 OldDelta += PathCount;
3509 OldCount += PathCount;
3510
3511 // Merge the IsRetainBlock values.
3512 if (FirstRetain) {
3513 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3514 FirstRetain = false;
3515 } else if (ReleasesToMove.IsRetainBlock !=
3516 NewReleaseRetainRRI.IsRetainBlock)
3517 // It's not possible to merge the sequences if one uses
3518 // objc_retain and the other uses objc_retainBlock.
3519 goto next_retain;
3520
3521 // Collect the optimal insertion points.
3522 if (!KnownSafe)
3523 for (SmallPtrSet<Instruction *, 2>::const_iterator
3524 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3525 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3526 RI != RE; ++RI) {
3527 Instruction *RIP = *RI;
3528 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3529 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3530 NewDelta += PathCount;
3531 NewCount += PathCount;
3532 }
3533 }
3534 NewRetains.push_back(NewReleaseRetain);
3535 }
3536 }
3537 }
3538 NewReleases.clear();
3539 if (NewRetains.empty()) break;
3540 }
3541
Dan Gohmane6d5e882011-08-19 00:26:36 +00003542 // If the pointer is known incremented or nested, we can safely delete the
3543 // pair regardless of what's between them.
3544 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003545 RetainsToMove.ReverseInsertPts.clear();
3546 ReleasesToMove.ReverseInsertPts.clear();
3547 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003548 } else {
3549 // Determine whether the new insertion points we computed preserve the
3550 // balance of retain and release calls through the program.
3551 // TODO: If the fully aggressive solution isn't valid, try to find a
3552 // less aggressive solution which is.
3553 if (NewDelta != 0)
3554 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003555 }
3556
3557 // Determine whether the original call points are balanced in the retain and
3558 // release calls through the program. If not, conservatively don't touch
3559 // them.
3560 // TODO: It's theoretically possible to do code motion in this case, as
3561 // long as the existing imbalances are maintained.
3562 if (OldDelta != 0)
3563 goto next_retain;
3564
John McCall9fbd3182011-06-15 23:37:01 +00003565 // Ok, everything checks out and we're all set. Let's move some code!
3566 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003567 assert(OldCount != 0 && "Unreachable code?");
3568 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003569 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003570 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3571 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003572
3573 next_retain:
3574 NewReleases.clear();
3575 NewRetains.clear();
3576 RetainsToMove.clear();
3577 ReleasesToMove.clear();
3578 }
3579
3580 // Now that we're done moving everything, we can delete the newly dead
3581 // instructions, as we no longer need them as insert points.
3582 while (!DeadInsts.empty())
3583 EraseInstruction(DeadInsts.pop_back_val());
3584
3585 return AnyPairsCompletelyEliminated;
3586}
3587
Michael Gottesman81c61212013-01-14 00:35:14 +00003588/// Weak pointer optimizations.
John McCall9fbd3182011-06-15 23:37:01 +00003589void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3590 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3591 // itself because it uses AliasAnalysis and we need to do provenance
3592 // queries instead.
3593 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3594 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003595
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003596 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003597 "\n");
3598
John McCall9fbd3182011-06-15 23:37:01 +00003599 InstructionClass Class = GetBasicInstructionClass(Inst);
3600 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3601 continue;
3602
3603 // Delete objc_loadWeak calls with no users.
3604 if (Class == IC_LoadWeak && Inst->use_empty()) {
3605 Inst->eraseFromParent();
3606 continue;
3607 }
3608
3609 // TODO: For now, just look for an earlier available version of this value
3610 // within the same block. Theoretically, we could do memdep-style non-local
3611 // analysis too, but that would want caching. A better approach would be to
3612 // use the technique that EarlyCSE uses.
3613 inst_iterator Current = llvm::prior(I);
3614 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3615 for (BasicBlock::iterator B = CurrentBB->begin(),
3616 J = Current.getInstructionIterator();
3617 J != B; --J) {
3618 Instruction *EarlierInst = &*llvm::prior(J);
3619 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3620 switch (EarlierClass) {
3621 case IC_LoadWeak:
3622 case IC_LoadWeakRetained: {
3623 // If this is loading from the same pointer, replace this load's value
3624 // with that one.
3625 CallInst *Call = cast<CallInst>(Inst);
3626 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3627 Value *Arg = Call->getArgOperand(0);
3628 Value *EarlierArg = EarlierCall->getArgOperand(0);
3629 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3630 case AliasAnalysis::MustAlias:
3631 Changed = true;
3632 // If the load has a builtin retain, insert a plain retain for it.
3633 if (Class == IC_LoadWeakRetained) {
3634 CallInst *CI =
3635 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3636 "", Call);
3637 CI->setTailCall();
3638 }
3639 // Zap the fully redundant load.
3640 Call->replaceAllUsesWith(EarlierCall);
3641 Call->eraseFromParent();
3642 goto clobbered;
3643 case AliasAnalysis::MayAlias:
3644 case AliasAnalysis::PartialAlias:
3645 goto clobbered;
3646 case AliasAnalysis::NoAlias:
3647 break;
3648 }
3649 break;
3650 }
3651 case IC_StoreWeak:
3652 case IC_InitWeak: {
3653 // If this is storing to the same pointer and has the same size etc.
3654 // replace this load's value with the stored value.
3655 CallInst *Call = cast<CallInst>(Inst);
3656 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3657 Value *Arg = Call->getArgOperand(0);
3658 Value *EarlierArg = EarlierCall->getArgOperand(0);
3659 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3660 case AliasAnalysis::MustAlias:
3661 Changed = true;
3662 // If the load has a builtin retain, insert a plain retain for it.
3663 if (Class == IC_LoadWeakRetained) {
3664 CallInst *CI =
3665 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3666 "", Call);
3667 CI->setTailCall();
3668 }
3669 // Zap the fully redundant load.
3670 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3671 Call->eraseFromParent();
3672 goto clobbered;
3673 case AliasAnalysis::MayAlias:
3674 case AliasAnalysis::PartialAlias:
3675 goto clobbered;
3676 case AliasAnalysis::NoAlias:
3677 break;
3678 }
3679 break;
3680 }
3681 case IC_MoveWeak:
3682 case IC_CopyWeak:
3683 // TOOD: Grab the copied value.
3684 goto clobbered;
3685 case IC_AutoreleasepoolPush:
3686 case IC_None:
3687 case IC_User:
3688 // Weak pointers are only modified through the weak entry points
3689 // (and arbitrary calls, which could call the weak entry points).
3690 break;
3691 default:
3692 // Anything else could modify the weak pointer.
3693 goto clobbered;
3694 }
3695 }
3696 clobbered:;
3697 }
3698
3699 // Then, for each destroyWeak with an alloca operand, check to see if
3700 // the alloca and all its users can be zapped.
3701 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3702 Instruction *Inst = &*I++;
3703 InstructionClass Class = GetBasicInstructionClass(Inst);
3704 if (Class != IC_DestroyWeak)
3705 continue;
3706
3707 CallInst *Call = cast<CallInst>(Inst);
3708 Value *Arg = Call->getArgOperand(0);
3709 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3710 for (Value::use_iterator UI = Alloca->use_begin(),
3711 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003712 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003713 switch (GetBasicInstructionClass(UserInst)) {
3714 case IC_InitWeak:
3715 case IC_StoreWeak:
3716 case IC_DestroyWeak:
3717 continue;
3718 default:
3719 goto done;
3720 }
3721 }
3722 Changed = true;
3723 for (Value::use_iterator UI = Alloca->use_begin(),
3724 UE = Alloca->use_end(); UI != UE; ) {
3725 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003726 switch (GetBasicInstructionClass(UserInst)) {
3727 case IC_InitWeak:
3728 case IC_StoreWeak:
3729 // These functions return their second argument.
3730 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3731 break;
3732 case IC_DestroyWeak:
3733 // No return value.
3734 break;
3735 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003736 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003737 }
John McCall9fbd3182011-06-15 23:37:01 +00003738 UserInst->eraseFromParent();
3739 }
3740 Alloca->eraseFromParent();
3741 done:;
3742 }
3743 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003744
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003745 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003746
John McCall9fbd3182011-06-15 23:37:01 +00003747}
3748
Michael Gottesman81c61212013-01-14 00:35:14 +00003749/// Identify program paths which execute sequences of retains and releases which
3750/// can be eliminated.
John McCall9fbd3182011-06-15 23:37:01 +00003751bool ObjCARCOpt::OptimizeSequences(Function &F) {
3752 /// Releases, Retains - These are used to store the results of the main flow
3753 /// analysis. These use Value* as the key instead of Instruction* so that the
3754 /// map stays valid when we get around to rewriting code and calls get
3755 /// replaced by arguments.
3756 DenseMap<Value *, RRInfo> Releases;
3757 MapVector<Value *, RRInfo> Retains;
3758
Michael Gottesman81c61212013-01-14 00:35:14 +00003759 /// This is used during the traversal of the function to track the
John McCall9fbd3182011-06-15 23:37:01 +00003760 /// states for each identified object at each block.
3761 DenseMap<const BasicBlock *, BBState> BBStates;
3762
3763 // Analyze the CFG of the function, and all instructions.
3764 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3765
3766 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003767 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3768 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003769}
3770
Michael Gottesman81c61212013-01-14 00:35:14 +00003771/// Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003772/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003773/// %call = call i8* @something(...)
3774/// %2 = call i8* @objc_retain(i8* %call)
3775/// %3 = call i8* @objc_autorelease(i8* %2)
3776/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003777/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003778/// And delete the retain and autorelease.
3779///
3780/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003781/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003782/// %3 = call i8* @objc_autorelease(i8* %2)
3783/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003784/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003785/// convert the autorelease to autoreleaseRV.
3786void ObjCARCOpt::OptimizeReturns(Function &F) {
3787 if (!F.getReturnType()->isPointerTy())
3788 return;
3789
3790 SmallPtrSet<Instruction *, 4> DependingInstructions;
3791 SmallPtrSet<const BasicBlock *, 4> Visited;
3792 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3793 BasicBlock *BB = FI;
3794 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003795
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003796 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003797
John McCall9fbd3182011-06-15 23:37:01 +00003798 if (!Ret) continue;
3799
3800 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3801 FindDependencies(NeedsPositiveRetainCount, Arg,
3802 BB, Ret, DependingInstructions, Visited, PA);
3803 if (DependingInstructions.size() != 1)
3804 goto next_block;
3805
3806 {
3807 CallInst *Autorelease =
3808 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3809 if (!Autorelease)
3810 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003811 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003812 if (!IsAutorelease(AutoreleaseClass))
3813 goto next_block;
3814 if (GetObjCArg(Autorelease) != Arg)
3815 goto next_block;
3816
3817 DependingInstructions.clear();
3818 Visited.clear();
3819
3820 // Check that there is nothing that can affect the reference
3821 // count between the autorelease and the retain.
3822 FindDependencies(CanChangeRetainCount, Arg,
3823 BB, Autorelease, DependingInstructions, Visited, PA);
3824 if (DependingInstructions.size() != 1)
3825 goto next_block;
3826
3827 {
3828 CallInst *Retain =
3829 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3830
3831 // Check that we found a retain with the same argument.
3832 if (!Retain ||
3833 !IsRetain(GetBasicInstructionClass(Retain)) ||
3834 GetObjCArg(Retain) != Arg)
3835 goto next_block;
3836
3837 DependingInstructions.clear();
3838 Visited.clear();
3839
3840 // Convert the autorelease to an autoreleaseRV, since it's
3841 // returning the value.
3842 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003843 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3844 "=> autoreleaseRV since it's returning a value.\n"
3845 " In: " << *Autorelease
3846 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003847 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003848 DEBUG(dbgs() << " Out: " << *Autorelease
3849 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003850 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003851 AutoreleaseClass = IC_AutoreleaseRV;
3852 }
3853
3854 // Check that there is nothing that can affect the reference
3855 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003856 // Note that Retain need not be in BB.
3857 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003858 DependingInstructions, Visited, PA);
3859 if (DependingInstructions.size() != 1)
3860 goto next_block;
3861
3862 {
3863 CallInst *Call =
3864 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3865
3866 // Check that the pointer is the return value of the call.
3867 if (!Call || Arg != Call)
3868 goto next_block;
3869
3870 // Check that the call is a regular call.
3871 InstructionClass Class = GetBasicInstructionClass(Call);
3872 if (Class != IC_CallOrUser && Class != IC_Call)
3873 goto next_block;
3874
3875 // If so, we can zap the retain and autorelease.
3876 Changed = true;
3877 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003878 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3879 << "\n Erasing: "
3880 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003881 EraseInstruction(Retain);
3882 EraseInstruction(Autorelease);
3883 }
3884 }
3885 }
3886
3887 next_block:
3888 DependingInstructions.clear();
3889 Visited.clear();
3890 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003891
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003892 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003893
John McCall9fbd3182011-06-15 23:37:01 +00003894}
3895
3896bool ObjCARCOpt::doInitialization(Module &M) {
3897 if (!EnableARCOpts)
3898 return false;
3899
Dan Gohmand6bf2012012-04-13 18:57:48 +00003900 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003901 Run = ModuleHasARC(M);
3902 if (!Run)
3903 return false;
3904
John McCall9fbd3182011-06-15 23:37:01 +00003905 // Identify the imprecise release metadata kind.
3906 ImpreciseReleaseMDKind =
3907 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003908 CopyOnEscapeMDKind =
3909 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003910 NoObjCARCExceptionsMDKind =
3911 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003912
John McCall9fbd3182011-06-15 23:37:01 +00003913 // Intuitively, objc_retain and others are nocapture, however in practice
3914 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003915 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003916
3917 // These are initialized lazily.
3918 RetainRVCallee = 0;
3919 AutoreleaseRVCallee = 0;
3920 ReleaseCallee = 0;
3921 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003922 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003923 AutoreleaseCallee = 0;
3924
3925 return false;
3926}
3927
3928bool ObjCARCOpt::runOnFunction(Function &F) {
3929 if (!EnableARCOpts)
3930 return false;
3931
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003932 // If nothing in the Module uses ARC, don't do anything.
3933 if (!Run)
3934 return false;
3935
John McCall9fbd3182011-06-15 23:37:01 +00003936 Changed = false;
3937
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003938 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3939
John McCall9fbd3182011-06-15 23:37:01 +00003940 PA.setAA(&getAnalysis<AliasAnalysis>());
3941
3942 // This pass performs several distinct transformations. As a compile-time aid
3943 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3944 // library functions aren't declared.
3945
3946 // Preliminary optimizations. This also computs UsedInThisFunction.
3947 OptimizeIndividualCalls(F);
3948
3949 // Optimizations for weak pointers.
3950 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3951 (1 << IC_LoadWeakRetained) |
3952 (1 << IC_StoreWeak) |
3953 (1 << IC_InitWeak) |
3954 (1 << IC_CopyWeak) |
3955 (1 << IC_MoveWeak) |
3956 (1 << IC_DestroyWeak)))
3957 OptimizeWeakCalls(F);
3958
3959 // Optimizations for retain+release pairs.
3960 if (UsedInThisFunction & ((1 << IC_Retain) |
3961 (1 << IC_RetainRV) |
3962 (1 << IC_RetainBlock)))
3963 if (UsedInThisFunction & (1 << IC_Release))
3964 // Run OptimizeSequences until it either stops making changes or
3965 // no retain+release pair nesting is detected.
3966 while (OptimizeSequences(F)) {}
3967
3968 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003969 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3970 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003971 OptimizeReturns(F);
3972
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003973 DEBUG(dbgs() << "\n");
3974
John McCall9fbd3182011-06-15 23:37:01 +00003975 return Changed;
3976}
3977
3978void ObjCARCOpt::releaseMemory() {
3979 PA.clear();
3980}
3981
Michael Gottesman81c61212013-01-14 00:35:14 +00003982/// @}
3983///
3984/// \defgroup ARCContract ARC Contraction.
3985/// @{
John McCall9fbd3182011-06-15 23:37:01 +00003986
3987// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3988// dominated by single calls.
3989
John McCall9fbd3182011-06-15 23:37:01 +00003990#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003991#include "llvm/IR/InlineAsm.h"
3992#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003993
3994STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3995
3996namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00003997 /// \brief Late ARC optimizations
3998 ///
3999 /// These change the IR in a way that makes it difficult to be analyzed by
4000 /// ObjCARCOpt, so it's run late.
John McCall9fbd3182011-06-15 23:37:01 +00004001 class ObjCARCContract : public FunctionPass {
4002 bool Changed;
4003 AliasAnalysis *AA;
4004 DominatorTree *DT;
4005 ProvenanceAnalysis PA;
4006
Michael Gottesman81c61212013-01-14 00:35:14 +00004007 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004008 bool Run;
4009
Michael Gottesman81c61212013-01-14 00:35:14 +00004010 /// Declarations for ObjC runtime functions, for use in creating calls to
4011 /// them. These are initialized lazily to avoid cluttering up the Module
4012 /// with unused declarations.
John McCall9fbd3182011-06-15 23:37:01 +00004013
Michael Gottesman81c61212013-01-14 00:35:14 +00004014 /// Declaration for objc_storeStrong().
4015 Constant *StoreStrongCallee;
4016 /// Declaration for objc_retainAutorelease().
4017 Constant *RetainAutoreleaseCallee;
4018 /// Declaration for objc_retainAutoreleaseReturnValue().
4019 Constant *RetainAutoreleaseRVCallee;
4020
4021 /// The inline asm string to insert between calls and RetainRV calls to make
4022 /// the optimization work on targets which need it.
John McCall9fbd3182011-06-15 23:37:01 +00004023 const MDString *RetainRVMarker;
4024
Michael Gottesman81c61212013-01-14 00:35:14 +00004025 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4026 /// function we have found no alloca instructions, these calls can be marked
4027 /// "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00004028 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00004029
John McCall9fbd3182011-06-15 23:37:01 +00004030 Constant *getStoreStrongCallee(Module *M);
4031 Constant *getRetainAutoreleaseCallee(Module *M);
4032 Constant *getRetainAutoreleaseRVCallee(Module *M);
4033
4034 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4035 InstructionClass Class,
4036 SmallPtrSet<Instruction *, 4>
4037 &DependingInstructions,
4038 SmallPtrSet<const BasicBlock *, 4>
4039 &Visited);
4040
4041 void ContractRelease(Instruction *Release,
4042 inst_iterator &Iter);
4043
4044 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4045 virtual bool doInitialization(Module &M);
4046 virtual bool runOnFunction(Function &F);
4047
4048 public:
4049 static char ID;
4050 ObjCARCContract() : FunctionPass(ID) {
4051 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4052 }
4053 };
4054}
4055
4056char ObjCARCContract::ID = 0;
4057INITIALIZE_PASS_BEGIN(ObjCARCContract,
4058 "objc-arc-contract", "ObjC ARC contraction", false, false)
4059INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4060INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4061INITIALIZE_PASS_END(ObjCARCContract,
4062 "objc-arc-contract", "ObjC ARC contraction", false, false)
4063
4064Pass *llvm::createObjCARCContractPass() {
4065 return new ObjCARCContract();
4066}
4067
4068void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4069 AU.addRequired<AliasAnalysis>();
4070 AU.addRequired<DominatorTree>();
4071 AU.setPreservesCFG();
4072}
4073
4074Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4075 if (!StoreStrongCallee) {
4076 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004077 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4078 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004079 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004080
Bill Wendling034b94b2012-12-19 07:18:57 +00004081 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004082 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004083 Attribute::get(C, Attribute::NoUnwind))
4084 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004085
4086 StoreStrongCallee =
4087 M->getOrInsertFunction(
4088 "objc_storeStrong",
4089 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004090 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004091 }
4092 return StoreStrongCallee;
4093}
4094
4095Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4096 if (!RetainAutoreleaseCallee) {
4097 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004098 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004099 Type *Params[] = { I8X };
4100 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004101 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004102 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004103 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004104 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004105 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004106 }
4107 return RetainAutoreleaseCallee;
4108}
4109
4110Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4111 if (!RetainAutoreleaseRVCallee) {
4112 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004113 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004114 Type *Params[] = { I8X };
4115 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004116 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004117 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004118 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004119 RetainAutoreleaseRVCallee =
4120 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004121 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004122 }
4123 return RetainAutoreleaseRVCallee;
4124}
4125
Michael Gottesman81c61212013-01-14 00:35:14 +00004126/// Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004127bool
4128ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4129 InstructionClass Class,
4130 SmallPtrSet<Instruction *, 4>
4131 &DependingInstructions,
4132 SmallPtrSet<const BasicBlock *, 4>
4133 &Visited) {
4134 const Value *Arg = GetObjCArg(Autorelease);
4135
4136 // Check that there are no instructions between the retain and the autorelease
4137 // (such as an autorelease_pop) which may change the count.
4138 CallInst *Retain = 0;
4139 if (Class == IC_AutoreleaseRV)
4140 FindDependencies(RetainAutoreleaseRVDep, Arg,
4141 Autorelease->getParent(), Autorelease,
4142 DependingInstructions, Visited, PA);
4143 else
4144 FindDependencies(RetainAutoreleaseDep, Arg,
4145 Autorelease->getParent(), Autorelease,
4146 DependingInstructions, Visited, PA);
4147
4148 Visited.clear();
4149 if (DependingInstructions.size() != 1) {
4150 DependingInstructions.clear();
4151 return false;
4152 }
4153
4154 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4155 DependingInstructions.clear();
4156
4157 if (!Retain ||
4158 GetBasicInstructionClass(Retain) != IC_Retain ||
4159 GetObjCArg(Retain) != Arg)
4160 return false;
4161
4162 Changed = true;
4163 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004164
Michael Gottesman916d52a2013-01-07 00:31:26 +00004165 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4166 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4167 " Old Retain: "
4168 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004169
John McCall9fbd3182011-06-15 23:37:01 +00004170 if (Class == IC_AutoreleaseRV)
4171 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4172 else
4173 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004174
Michael Gottesman916d52a2013-01-07 00:31:26 +00004175 DEBUG(dbgs() << " New Retain: "
4176 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004177
John McCall9fbd3182011-06-15 23:37:01 +00004178 EraseInstruction(Autorelease);
4179 return true;
4180}
4181
Michael Gottesman81c61212013-01-14 00:35:14 +00004182/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4183/// an objc_storeStrong. This can be a little tricky because the instructions
4184/// don't always appear in order, and there may be unrelated intervening
4185/// instructions.
John McCall9fbd3182011-06-15 23:37:01 +00004186void ObjCARCContract::ContractRelease(Instruction *Release,
4187 inst_iterator &Iter) {
4188 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004189 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004190
4191 // For now, require everything to be in one basic block.
4192 BasicBlock *BB = Release->getParent();
4193 if (Load->getParent() != BB) return;
4194
Dan Gohman4670dac2012-05-08 23:34:08 +00004195 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004196 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004197 ++I;
4198 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004199 StoreInst *Store = 0;
4200 bool SawRelease = false;
4201 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004202 if (I == End)
4203 return;
4204
Dan Gohman4670dac2012-05-08 23:34:08 +00004205 Instruction *Inst = I;
4206 if (Inst == Release) {
4207 SawRelease = true;
4208 continue;
4209 }
4210
4211 InstructionClass Class = GetBasicInstructionClass(Inst);
4212
4213 // Unrelated retains are harmless.
4214 if (IsRetain(Class))
4215 continue;
4216
4217 if (Store) {
4218 // The store is the point where we're going to put the objc_storeStrong,
4219 // so make sure there are no uses after it.
4220 if (CanUse(Inst, Load, PA, Class))
4221 return;
4222 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4223 // We are moving the load down to the store, so check for anything
4224 // else which writes to the memory between the load and the store.
4225 Store = dyn_cast<StoreInst>(Inst);
4226 if (!Store || !Store->isSimple()) return;
4227 if (Store->getPointerOperand() != Loc.Ptr) return;
4228 }
4229 }
John McCall9fbd3182011-06-15 23:37:01 +00004230
4231 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4232
4233 // Walk up to find the retain.
4234 I = Store;
4235 BasicBlock::iterator Begin = BB->begin();
4236 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4237 --I;
4238 Instruction *Retain = I;
4239 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4240 if (GetObjCArg(Retain) != New) return;
4241
4242 Changed = true;
4243 ++NumStoreStrongs;
4244
4245 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004246 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4247 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004248
4249 Value *Args[] = { Load->getPointerOperand(), New };
4250 if (Args[0]->getType() != I8XX)
4251 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4252 if (Args[1]->getType() != I8X)
4253 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4254 CallInst *StoreStrong =
4255 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004256 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004257 StoreStrong->setDoesNotThrow();
4258 StoreStrong->setDebugLoc(Store->getDebugLoc());
4259
Dan Gohman0cdece42012-01-19 19:14:36 +00004260 // We can't set the tail flag yet, because we haven't yet determined
4261 // whether there are any escaping allocas. Remember this call, so that
4262 // we can set the tail flag once we know it's safe.
4263 StoreStrongCalls.insert(StoreStrong);
4264
John McCall9fbd3182011-06-15 23:37:01 +00004265 if (&*Iter == Store) ++Iter;
4266 Store->eraseFromParent();
4267 Release->eraseFromParent();
4268 EraseInstruction(Retain);
4269 if (Load->use_empty())
4270 Load->eraseFromParent();
4271}
4272
4273bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004274 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004275 Run = ModuleHasARC(M);
4276 if (!Run)
4277 return false;
4278
John McCall9fbd3182011-06-15 23:37:01 +00004279 // These are initialized lazily.
4280 StoreStrongCallee = 0;
4281 RetainAutoreleaseCallee = 0;
4282 RetainAutoreleaseRVCallee = 0;
4283
4284 // Initialize RetainRVMarker.
4285 RetainRVMarker = 0;
4286 if (NamedMDNode *NMD =
4287 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4288 if (NMD->getNumOperands() == 1) {
4289 const MDNode *N = NMD->getOperand(0);
4290 if (N->getNumOperands() == 1)
4291 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4292 RetainRVMarker = S;
4293 }
4294
4295 return false;
4296}
4297
4298bool ObjCARCContract::runOnFunction(Function &F) {
4299 if (!EnableARCOpts)
4300 return false;
4301
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004302 // If nothing in the Module uses ARC, don't do anything.
4303 if (!Run)
4304 return false;
4305
John McCall9fbd3182011-06-15 23:37:01 +00004306 Changed = false;
4307 AA = &getAnalysis<AliasAnalysis>();
4308 DT = &getAnalysis<DominatorTree>();
4309
4310 PA.setAA(&getAnalysis<AliasAnalysis>());
4311
Dan Gohman0cdece42012-01-19 19:14:36 +00004312 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4313 // keyword. Be conservative if the function has variadic arguments.
4314 // It seems that functions which "return twice" are also unsafe for the
4315 // "tail" argument, because they are setjmp, which could need to
4316 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004317 bool TailOkForStoreStrongs = !F.isVarArg() &&
4318 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004319
John McCall9fbd3182011-06-15 23:37:01 +00004320 // For ObjC library calls which return their argument, replace uses of the
4321 // argument with uses of the call return value, if it dominates the use. This
4322 // reduces register pressure.
4323 SmallPtrSet<Instruction *, 4> DependingInstructions;
4324 SmallPtrSet<const BasicBlock *, 4> Visited;
4325 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4326 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004327
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004328 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004329
John McCall9fbd3182011-06-15 23:37:01 +00004330 // Only these library routines return their argument. In particular,
4331 // objc_retainBlock does not necessarily return its argument.
4332 InstructionClass Class = GetBasicInstructionClass(Inst);
4333 switch (Class) {
4334 case IC_Retain:
4335 case IC_FusedRetainAutorelease:
4336 case IC_FusedRetainAutoreleaseRV:
4337 break;
4338 case IC_Autorelease:
4339 case IC_AutoreleaseRV:
4340 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4341 continue;
4342 break;
4343 case IC_RetainRV: {
4344 // If we're compiling for a target which needs a special inline-asm
4345 // marker to do the retainAutoreleasedReturnValue optimization,
4346 // insert it now.
4347 if (!RetainRVMarker)
4348 break;
4349 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004350 BasicBlock *InstParent = Inst->getParent();
4351
4352 // Step up to see if the call immediately precedes the RetainRV call.
4353 // If it's an invoke, we have to cross a block boundary. And we have
4354 // to carefully dodge no-op instructions.
4355 do {
4356 if (&*BBI == InstParent->begin()) {
4357 BasicBlock *Pred = InstParent->getSinglePredecessor();
4358 if (!Pred)
4359 goto decline_rv_optimization;
4360 BBI = Pred->getTerminator();
4361 break;
4362 }
4363 --BBI;
4364 } while (isNoopInstruction(BBI));
4365
John McCall9fbd3182011-06-15 23:37:01 +00004366 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004367 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004368 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004369 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004370 InlineAsm *IA =
4371 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4372 /*isVarArg=*/false),
4373 RetainRVMarker->getString(),
4374 /*Constraints=*/"", /*hasSideEffects=*/true);
4375 CallInst::Create(IA, "", Inst);
4376 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004377 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004378 break;
4379 }
4380 case IC_InitWeak: {
4381 // objc_initWeak(p, null) => *p = null
4382 CallInst *CI = cast<CallInst>(Inst);
4383 if (isNullOrUndef(CI->getArgOperand(1))) {
4384 Value *Null =
4385 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4386 Changed = true;
4387 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004388
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004389 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4390 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004391
John McCall9fbd3182011-06-15 23:37:01 +00004392 CI->replaceAllUsesWith(Null);
4393 CI->eraseFromParent();
4394 }
4395 continue;
4396 }
4397 case IC_Release:
4398 ContractRelease(Inst, I);
4399 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004400 case IC_User:
4401 // Be conservative if the function has any alloca instructions.
4402 // Technically we only care about escaping alloca instructions,
4403 // but this is sufficient to handle some interesting cases.
4404 if (isa<AllocaInst>(Inst))
4405 TailOkForStoreStrongs = false;
4406 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004407 default:
4408 continue;
4409 }
4410
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004411 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004412
John McCall9fbd3182011-06-15 23:37:01 +00004413 // Don't use GetObjCArg because we don't want to look through bitcasts
4414 // and such; to do the replacement, the argument must have type i8*.
4415 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4416 for (;;) {
4417 // If we're compiling bugpointed code, don't get in trouble.
4418 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4419 break;
4420 // Look through the uses of the pointer.
4421 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4422 UI != UE; ) {
4423 Use &U = UI.getUse();
4424 unsigned OperandNo = UI.getOperandNo();
4425 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004426
4427 // If the call's return value dominates a use of the call's argument
4428 // value, rewrite the use to use the return value. We check for
4429 // reachability here because an unreachable call is considered to
4430 // trivially dominate itself, which would lead us to rewriting its
4431 // argument in terms of its return value, which would lead to
4432 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004433 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004434 Changed = true;
4435 Instruction *Replacement = Inst;
4436 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004437 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004438 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004439 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4440 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004441 if (Replacement->getType() != UseTy)
4442 Replacement = new BitCastInst(Replacement, UseTy, "",
4443 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004444 // While we're here, rewrite all edges for this PHI, rather
4445 // than just one use at a time, to minimize the number of
4446 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004447 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004448 if (PHI->getIncomingBlock(i) == BB) {
4449 // Keep the UI iterator valid.
4450 if (&PHI->getOperandUse(
4451 PHINode::getOperandNumForIncomingValue(i)) ==
4452 &UI.getUse())
4453 ++UI;
4454 PHI->setIncomingValue(i, Replacement);
4455 }
4456 } else {
4457 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004458 Replacement = new BitCastInst(Replacement, UseTy, "",
4459 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004460 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004461 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004462 }
John McCall9fbd3182011-06-15 23:37:01 +00004463 }
4464
Dan Gohman447989c2012-04-27 18:56:31 +00004465 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004466 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4467 Arg = BI->getOperand(0);
4468 else if (isa<GEPOperator>(Arg) &&
4469 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4470 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4471 else if (isa<GlobalAlias>(Arg) &&
4472 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4473 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4474 else
4475 break;
4476 }
4477 }
4478
Dan Gohman0cdece42012-01-19 19:14:36 +00004479 // If this function has no escaping allocas or suspicious vararg usage,
4480 // objc_storeStrong calls can be marked with the "tail" keyword.
4481 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004482 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004483 E = StoreStrongCalls.end(); I != E; ++I)
4484 (*I)->setTailCall();
4485 StoreStrongCalls.clear();
4486
John McCall9fbd3182011-06-15 23:37:01 +00004487 return Changed;
4488}
Michael Gottesman81c61212013-01-14 00:35:14 +00004489
4490/// @}
4491///