blob: e7c51780411a0559a7293cbb80701d70118eb8e9 [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 Gottesman7899e472013-01-14 01:47:53 +0000195/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
196/// is.
John McCall9fbd3182011-06-15 23:37:01 +0000197static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
198 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199 I != E; ++I)
200 if (IsPotentialUse(*I))
201 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202
203 return CS.onlyReadsMemory() ? IC_None : IC_Call;
204}
205
Michael Gottesman81c61212013-01-14 00:35:14 +0000206/// \brief Determine if F is one of the special known Functions. If it isn't,
207/// return IC_CallOrUser.
John McCall9fbd3182011-06-15 23:37:01 +0000208static InstructionClass GetFunctionClass(const Function *F) {
209 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
210
211 // No arguments.
212 if (AI == AE)
213 return StringSwitch<InstructionClass>(F->getName())
214 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
215 .Default(IC_CallOrUser);
216
217 // One argument.
218 const Argument *A0 = AI++;
219 if (AI == AE)
220 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000221 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
222 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000223 // Argument is i8*.
224 if (ETy->isIntegerTy(8))
225 return StringSwitch<InstructionClass>(F->getName())
226 .Case("objc_retain", IC_Retain)
227 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
228 .Case("objc_retainBlock", IC_RetainBlock)
229 .Case("objc_release", IC_Release)
230 .Case("objc_autorelease", IC_Autorelease)
231 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
232 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
233 .Case("objc_retainedObject", IC_NoopCast)
234 .Case("objc_unretainedObject", IC_NoopCast)
235 .Case("objc_unretainedPointer", IC_NoopCast)
236 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
239 .Default(IC_CallOrUser);
240
241 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000242 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000243 if (Pte->getElementType()->isIntegerTy(8))
244 return StringSwitch<InstructionClass>(F->getName())
245 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
246 .Case("objc_loadWeak", IC_LoadWeak)
247 .Case("objc_destroyWeak", IC_DestroyWeak)
248 .Default(IC_CallOrUser);
249 }
250
251 // Two arguments, first is i8**.
252 const Argument *A1 = AI++;
253 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000254 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
255 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000256 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000257 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
258 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000259 // Second argument is i8*
260 if (ETy1->isIntegerTy(8))
261 return StringSwitch<InstructionClass>(F->getName())
262 .Case("objc_storeWeak", IC_StoreWeak)
263 .Case("objc_initWeak", IC_InitWeak)
Dan Gohman44234772012-04-13 18:28:58 +0000264 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000265 .Default(IC_CallOrUser);
266 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000267 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000268 if (Pte1->getElementType()->isIntegerTy(8))
269 return StringSwitch<InstructionClass>(F->getName())
270 .Case("objc_moveWeak", IC_MoveWeak)
271 .Case("objc_copyWeak", IC_CopyWeak)
272 .Default(IC_CallOrUser);
273 }
274
275 // Anything else.
276 return IC_CallOrUser;
277}
278
Michael Gottesman81c61212013-01-14 00:35:14 +0000279/// \brief Determine what kind of construct V is.
John McCall9fbd3182011-06-15 23:37:01 +0000280static InstructionClass GetInstructionClass(const Value *V) {
281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
282 // Any instruction other than bitcast and gep with a pointer operand have a
283 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284 // to a subsequent use, rather than using it themselves, in this sense.
285 // As a short cut, several other opcodes are known to have no pointer
286 // operands of interest. And ret is never followed by a release, so it's
287 // not interesting to examine.
288 switch (I->getOpcode()) {
289 case Instruction::Call: {
290 const CallInst *CI = cast<CallInst>(I);
291 // Check for calls to special functions.
292 if (const Function *F = CI->getCalledFunction()) {
293 InstructionClass Class = GetFunctionClass(F);
294 if (Class != IC_CallOrUser)
295 return Class;
296
297 // None of the intrinsic functions do objc_release. For intrinsics, the
298 // only question is whether or not they may be users.
299 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000300 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
301 case Intrinsic::stacksave: case Intrinsic::stackrestore:
302 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000303 case Intrinsic::objectsize: case Intrinsic::prefetch:
304 case Intrinsic::stackprotector:
305 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
306 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
307 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
308 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
309 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
310 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000311 // Don't let dbg info affect our results.
312 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
313 // Short cut: Some intrinsics obviously don't use ObjC pointers.
314 return IC_None;
315 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000316 break;
John McCall9fbd3182011-06-15 23:37:01 +0000317 }
318 }
319 return GetCallSiteClass(CI);
320 }
321 case Instruction::Invoke:
322 return GetCallSiteClass(cast<InvokeInst>(I));
323 case Instruction::BitCast:
324 case Instruction::GetElementPtr:
325 case Instruction::Select: case Instruction::PHI:
326 case Instruction::Ret: case Instruction::Br:
327 case Instruction::Switch: case Instruction::IndirectBr:
328 case Instruction::Alloca: case Instruction::VAArg:
329 case Instruction::Add: case Instruction::FAdd:
330 case Instruction::Sub: case Instruction::FSub:
331 case Instruction::Mul: case Instruction::FMul:
332 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
333 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
334 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
335 case Instruction::And: case Instruction::Or: case Instruction::Xor:
336 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
337 case Instruction::IntToPtr: case Instruction::FCmp:
338 case Instruction::FPTrunc: case Instruction::FPExt:
339 case Instruction::FPToUI: case Instruction::FPToSI:
340 case Instruction::UIToFP: case Instruction::SIToFP:
341 case Instruction::InsertElement: case Instruction::ExtractElement:
342 case Instruction::ShuffleVector:
343 case Instruction::ExtractValue:
344 break;
345 case Instruction::ICmp:
346 // Comparing a pointer with null, or any other constant, isn't an
347 // interesting use, because we don't care what the pointer points to, or
348 // about the values of any other dynamic reference-counted pointers.
349 if (IsPotentialUse(I->getOperand(1)))
350 return IC_User;
351 break;
352 default:
353 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000354 // Note that this includes both operands of a Store: while the first
355 // operand isn't actually being dereferenced, it is being stored to
356 // memory where we can no longer track who might read it and dereference
357 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000358 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
359 OI != OE; ++OI)
360 if (IsPotentialUse(*OI))
361 return IC_User;
362 }
363 }
364
365 // Otherwise, it's totally inert for ARC purposes.
366 return IC_None;
367}
368
Michael Gottesman81c61212013-01-14 00:35:14 +0000369/// \brief Determine which objc runtime call instruction class V belongs to.
370///
371/// This is similar to GetInstructionClass except that it only detects objc
372/// runtime calls. This allows it to be faster.
373///
John McCall9fbd3182011-06-15 23:37:01 +0000374static InstructionClass GetBasicInstructionClass(const Value *V) {
375 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
376 if (const Function *F = CI->getCalledFunction())
377 return GetFunctionClass(F);
378 // Otherwise, be conservative.
379 return IC_CallOrUser;
380 }
381
382 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000383 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000384}
385
Michael Gottesman81c61212013-01-14 00:35:14 +0000386/// \brief Test if the given class is objc_retain or equivalent.
John McCall9fbd3182011-06-15 23:37:01 +0000387static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
390}
391
Michael Gottesman81c61212013-01-14 00:35:14 +0000392/// \brief Test if the given class is objc_autorelease or equivalent.
John McCall9fbd3182011-06-15 23:37:01 +0000393static bool IsAutorelease(InstructionClass Class) {
394 return Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV;
396}
397
Michael Gottesman81c61212013-01-14 00:35:14 +0000398/// \brief Test if the given class represents instructions which return their
399/// argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000400static bool IsForwarding(InstructionClass Class) {
401 // objc_retainBlock technically doesn't always return its argument
402 // verbatim, but it doesn't matter for our purposes here.
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Autorelease ||
406 Class == IC_AutoreleaseRV ||
407 Class == IC_RetainBlock ||
408 Class == IC_NoopCast;
409}
410
Michael Gottesman81c61212013-01-14 00:35:14 +0000411/// \brief Test if the given class represents instructions which do nothing if
412/// passed a null pointer.
John McCall9fbd3182011-06-15 23:37:01 +0000413static bool IsNoopOnNull(InstructionClass Class) {
414 return Class == IC_Retain ||
415 Class == IC_RetainRV ||
416 Class == IC_Release ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV ||
419 Class == IC_RetainBlock;
420}
421
Michael Gottesman7899e472013-01-14 01:47:53 +0000422/// \brief Test if the given class represents instructions which are always safe
423/// to mark with the "tail" keyword.
John McCall9fbd3182011-06-15 23:37:01 +0000424static bool IsAlwaysTail(InstructionClass Class) {
425 // IC_RetainBlock may be given a stack argument.
426 return Class == IC_Retain ||
427 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000428 Class == IC_AutoreleaseRV;
429}
430
Michael Gottesmane8c161a2013-01-12 01:25:15 +0000431/// \brief Test if the given class represents instructions which are never safe
432/// to mark with the "tail" keyword.
433static bool IsNeverTail(InstructionClass Class) {
434 /// It is never safe to tail call objc_autorelease since by tail calling
435 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
436 /// fast autoreleasing causing our object to be potentially reclaimed from the
437 /// autorelease pool which violates the semantics of __autoreleasing types in
438 /// ARC.
439 return Class == IC_Autorelease;
440}
441
Michael Gottesman81c61212013-01-14 00:35:14 +0000442/// \brief Test if the given class represents instructions which are always safe
443/// to mark with the nounwind attribute.
John McCall9fbd3182011-06-15 23:37:01 +0000444static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000445 // objc_retainBlock is not nounwind because it calls user copy constructors
446 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000447 return Class == IC_Retain ||
448 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000449 Class == IC_Release ||
450 Class == IC_Autorelease ||
451 Class == IC_AutoreleaseRV ||
452 Class == IC_AutoreleasepoolPush ||
453 Class == IC_AutoreleasepoolPop;
454}
455
Michael Gottesman81c61212013-01-14 00:35:14 +0000456/// \brief Erase the given instruction.
457///
458/// Many ObjC calls return their argument verbatim,
459/// so if it's such a call and the return value has users, replace them with the
460/// argument value.
461///
John McCall9fbd3182011-06-15 23:37:01 +0000462static void EraseInstruction(Instruction *CI) {
463 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
464
465 bool Unused = CI->use_empty();
466
467 if (!Unused) {
468 // Replace the return value with the argument.
469 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
470 "Can't delete non-forwarding instruction with users!");
471 CI->replaceAllUsesWith(OldArg);
472 }
473
474 CI->eraseFromParent();
475
476 if (Unused)
477 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
478}
479
Michael Gottesman81c61212013-01-14 00:35:14 +0000480/// \brief This is a wrapper around getUnderlyingObject which also knows how to
481/// look through objc_retain and objc_autorelease calls, which we know to return
482/// their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000483static const Value *GetUnderlyingObjCPtr(const Value *V) {
484 for (;;) {
485 V = GetUnderlyingObject(V);
486 if (!IsForwarding(GetBasicInstructionClass(V)))
487 break;
488 V = cast<CallInst>(V)->getArgOperand(0);
489 }
490
491 return V;
492}
493
Michael Gottesman81c61212013-01-14 00:35:14 +0000494/// \brief This is a wrapper around Value::stripPointerCasts which also knows
495/// how to look through objc_retain and objc_autorelease calls, which we know to
496/// return their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000497static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
498 for (;;) {
499 V = V->stripPointerCasts();
500 if (!IsForwarding(GetBasicInstructionClass(V)))
501 break;
502 V = cast<CallInst>(V)->getArgOperand(0);
503 }
504 return V;
505}
506
Michael Gottesman81c61212013-01-14 00:35:14 +0000507/// \brief This is a wrapper around Value::stripPointerCasts which also knows
508/// how to look through objc_retain and objc_autorelease calls, which we know to
509/// return their argument verbatim.
John McCall9fbd3182011-06-15 23:37:01 +0000510static Value *StripPointerCastsAndObjCCalls(Value *V) {
511 for (;;) {
512 V = V->stripPointerCasts();
513 if (!IsForwarding(GetBasicInstructionClass(V)))
514 break;
515 V = cast<CallInst>(V)->getArgOperand(0);
516 }
517 return V;
518}
519
Michael Gottesman81c61212013-01-14 00:35:14 +0000520/// \brief Assuming the given instruction is one of the special calls such as
521/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCall9fbd3182011-06-15 23:37:01 +0000522/// casts and forwarding calls.
523static Value *GetObjCArg(Value *Inst) {
524 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
525}
526
Michael Gottesman81c61212013-01-14 00:35:14 +0000527/// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
528/// that it uses special knowledge of ObjC conventions.
John McCall9fbd3182011-06-15 23:37:01 +0000529static bool IsObjCIdentifiedObject(const Value *V) {
530 // Assume that call results and arguments have their own "provenance".
531 // Constants (including GlobalVariables) and Allocas are never
532 // reference-counted.
533 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
534 isa<Argument>(V) || isa<Constant>(V) ||
535 isa<AllocaInst>(V))
536 return true;
537
538 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
539 const Value *Pointer =
540 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
541 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000542 // A constant pointer can't be pointing to an object on the heap. It may
543 // be reference-counted, but it won't be deleted.
544 if (GV->isConstant())
545 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000546 StringRef Name = GV->getName();
547 // These special variables are known to hold values which are not
548 // reference-counted pointers.
549 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
551 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
552 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
553 Name.startswith("\01l_objc_msgSend_fixup_"))
554 return true;
555 }
556 }
557
558 return false;
559}
560
Michael Gottesman81c61212013-01-14 00:35:14 +0000561/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
562/// as it finds a value with multiple uses.
John McCall9fbd3182011-06-15 23:37:01 +0000563static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564 if (Arg->hasOneUse()) {
565 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566 return FindSingleUseIdentifiedObject(BC->getOperand(0));
567 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568 if (GEP->hasAllZeroIndices())
569 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570 if (IsForwarding(GetBasicInstructionClass(Arg)))
571 return FindSingleUseIdentifiedObject(
572 cast<CallInst>(Arg)->getArgOperand(0));
573 if (!IsObjCIdentifiedObject(Arg))
574 return 0;
575 return Arg;
576 }
577
Dan Gohman0daef3d2012-05-08 23:39:44 +0000578 // If we found an identifiable object but it has multiple uses, but they are
579 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000580 if (IsObjCIdentifiedObject(Arg)) {
581 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
582 UI != UE; ++UI) {
583 const User *U = *UI;
584 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585 return 0;
586 }
587
588 return Arg;
589 }
590
591 return 0;
592}
593
Michael Gottesman81c61212013-01-14 00:35:14 +0000594/// \brief Test if the given module looks interesting to run ARC optimization
595/// on.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000596static bool ModuleHasARC(const Module &M) {
597 return
598 M.getNamedValue("objc_retain") ||
599 M.getNamedValue("objc_release") ||
600 M.getNamedValue("objc_autorelease") ||
601 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602 M.getNamedValue("objc_retainBlock") ||
603 M.getNamedValue("objc_autoreleaseReturnValue") ||
604 M.getNamedValue("objc_autoreleasePoolPush") ||
605 M.getNamedValue("objc_loadWeakRetained") ||
606 M.getNamedValue("objc_loadWeak") ||
607 M.getNamedValue("objc_destroyWeak") ||
608 M.getNamedValue("objc_storeWeak") ||
609 M.getNamedValue("objc_initWeak") ||
610 M.getNamedValue("objc_moveWeak") ||
611 M.getNamedValue("objc_copyWeak") ||
612 M.getNamedValue("objc_retainedObject") ||
613 M.getNamedValue("objc_unretainedObject") ||
614 M.getNamedValue("objc_unretainedPointer");
615}
616
Michael Gottesman7899e472013-01-14 01:47:53 +0000617/// \brief Test whether the given pointer, which is an Objective C block
618/// pointer, does not "escape".
Michael Gottesman81c61212013-01-14 00:35:14 +0000619///
620/// This differs from regular escape analysis in that a use as an
621/// argument to a call is not considered an escape.
622///
Dan Gohman79522dc2012-01-13 00:39:07 +0000623static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman981308c2013-01-13 07:47:32 +0000624
625 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
626
Dan Gohman79522dc2012-01-13 00:39:07 +0000627 // Walk the def-use chains.
628 SmallVector<const Value *, 4> Worklist;
629 Worklist.push_back(BlockPtr);
Michael Gottesman6056b852013-01-13 22:12:06 +0000630
631 // Ensure we do not visit any value twice.
632 SmallPtrSet<const Value *, 4> VisitedSet;
633
Dan Gohman79522dc2012-01-13 00:39:07 +0000634 do {
635 const Value *V = Worklist.pop_back_val();
Michael Gottesman981308c2013-01-13 07:47:32 +0000636
637 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
638
Dan Gohman79522dc2012-01-13 00:39:07 +0000639 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
640 UI != UE; ++UI) {
641 const User *UUser = *UI;
Michael Gottesman981308c2013-01-13 07:47:32 +0000642
643 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
644
Dan Gohman79522dc2012-01-13 00:39:07 +0000645 // Special - Use by a call (callee or argument) is not considered
646 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000647 switch (GetBasicInstructionClass(UUser)) {
648 case IC_StoreWeak:
649 case IC_InitWeak:
650 case IC_StoreStrong:
651 case IC_Autorelease:
Michael Gottesman981308c2013-01-13 07:47:32 +0000652 case IC_AutoreleaseRV: {
653 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
654 "Block Escapes!\n");
Dan Gohman44234772012-04-13 18:28:58 +0000655 // These special functions make copies of their pointer arguments.
656 return true;
Michael Gottesman981308c2013-01-13 07:47:32 +0000657 }
Dan Gohman44234772012-04-13 18:28:58 +0000658 case IC_User:
659 case IC_None:
660 // Use by an instruction which copies the value is an escape if the
661 // result is an escape.
662 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
663 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesman6056b852013-01-13 22:12:06 +0000664
665 if (!VisitedSet.count(UUser)) {
Michael Gottesman7899e472013-01-14 01:47:53 +0000666 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
667 "if result escapes. Adding to list.\n");
Michael Gottesman6056b852013-01-13 22:12:06 +0000668 VisitedSet.insert(V);
669 Worklist.push_back(UUser);
670 } else {
671 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
672 }
Dan Gohman44234772012-04-13 18:28:58 +0000673 continue;
674 }
675 // Use by a load is not an escape.
676 if (isa<LoadInst>(UUser))
677 continue;
678 // Use by a store is not an escape if the use is the address.
679 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
680 if (V != SI->getValueOperand())
681 continue;
682 break;
683 default:
684 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000685 continue;
686 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000687 // Otherwise, conservatively assume an escape.
Michael Gottesman981308c2013-01-13 07:47:32 +0000688 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000689 return true;
690 }
691 } while (!Worklist.empty());
692
693 // No escapes found.
Michael Gottesman981308c2013-01-13 07:47:32 +0000694 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman79522dc2012-01-13 00:39:07 +0000695 return false;
696}
697
Michael Gottesman81c61212013-01-14 00:35:14 +0000698/// @}
699///
Michael Gottesman7899e472013-01-14 01:47:53 +0000700/// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
Michael Gottesman81c61212013-01-14 00:35:14 +0000701/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000702
John McCall9fbd3182011-06-15 23:37:01 +0000703#include "llvm/Analysis/AliasAnalysis.h"
704#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000705#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000706
707namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000708 /// \brief This is a simple alias analysis implementation that uses knowledge
709 /// of ARC constructs to answer queries.
John McCall9fbd3182011-06-15 23:37:01 +0000710 ///
711 /// TODO: This class could be generalized to know about other ObjC-specific
712 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
713 /// even though their offsets are dynamic.
714 class ObjCARCAliasAnalysis : public ImmutablePass,
715 public AliasAnalysis {
716 public:
717 static char ID; // Class identification, replacement for typeinfo
718 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
719 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
720 }
721
722 private:
723 virtual void initializePass() {
724 InitializeAliasAnalysis(this);
725 }
726
Michael Gottesman81c61212013-01-14 00:35:14 +0000727 /// This method is used when a pass implements an analysis interface through
728 /// multiple inheritance. If needed, it should override this to adjust the
729 /// this pointer as needed for the specified pass info.
John McCall9fbd3182011-06-15 23:37:01 +0000730 virtual void *getAdjustedAnalysisPointer(const void *PI) {
731 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000732 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000733 return this;
734 }
735
736 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
737 virtual AliasResult alias(const Location &LocA, const Location &LocB);
738 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
739 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
740 virtual ModRefBehavior getModRefBehavior(const Function *F);
741 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
742 const Location &Loc);
743 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
744 ImmutableCallSite CS2);
745 };
746} // End of anonymous namespace
747
748// Register this pass...
749char ObjCARCAliasAnalysis::ID = 0;
750INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
751 "ObjC-ARC-Based Alias Analysis", false, true, false)
752
753ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
754 return new ObjCARCAliasAnalysis();
755}
756
757void
758ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
759 AU.setPreservesAll();
760 AliasAnalysis::getAnalysisUsage(AU);
761}
762
763AliasAnalysis::AliasResult
764ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
765 if (!EnableARCOpts)
766 return AliasAnalysis::alias(LocA, LocB);
767
768 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
769 // precise alias query.
770 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
771 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
772 AliasResult Result =
773 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
774 Location(SB, LocB.Size, LocB.TBAATag));
775 if (Result != MayAlias)
776 return Result;
777
778 // If that failed, climb to the underlying object, including climbing through
779 // ObjC-specific no-ops, and try making an imprecise alias query.
780 const Value *UA = GetUnderlyingObjCPtr(SA);
781 const Value *UB = GetUnderlyingObjCPtr(SB);
782 if (UA != SA || UB != SB) {
783 Result = AliasAnalysis::alias(Location(UA), Location(UB));
784 // We can't use MustAlias or PartialAlias results here because
785 // GetUnderlyingObjCPtr may return an offsetted pointer value.
786 if (Result == NoAlias)
787 return NoAlias;
788 }
789
790 // If that failed, fail. We don't need to chain here, since that's covered
791 // by the earlier precise query.
792 return MayAlias;
793}
794
795bool
796ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
797 bool OrLocal) {
798 if (!EnableARCOpts)
799 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
800
801 // First, strip off no-ops, including ObjC-specific no-ops, and try making
802 // a precise alias query.
803 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
804 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
805 OrLocal))
806 return true;
807
808 // If that failed, climb to the underlying object, including climbing through
809 // ObjC-specific no-ops, and try making an imprecise alias query.
810 const Value *U = GetUnderlyingObjCPtr(S);
811 if (U != S)
812 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
813
814 // If that failed, fail. We don't need to chain here, since that's covered
815 // by the earlier precise query.
816 return false;
817}
818
819AliasAnalysis::ModRefBehavior
820ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
821 // We have nothing to do. Just chain to the next AliasAnalysis.
822 return AliasAnalysis::getModRefBehavior(CS);
823}
824
825AliasAnalysis::ModRefBehavior
826ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
827 if (!EnableARCOpts)
828 return AliasAnalysis::getModRefBehavior(F);
829
830 switch (GetFunctionClass(F)) {
831 case IC_NoopCast:
832 return DoesNotAccessMemory;
833 default:
834 break;
835 }
836
837 return AliasAnalysis::getModRefBehavior(F);
838}
839
840AliasAnalysis::ModRefResult
841ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
842 if (!EnableARCOpts)
843 return AliasAnalysis::getModRefInfo(CS, Loc);
844
845 switch (GetBasicInstructionClass(CS.getInstruction())) {
846 case IC_Retain:
847 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000848 case IC_Autorelease:
849 case IC_AutoreleaseRV:
850 case IC_NoopCast:
851 case IC_AutoreleasepoolPush:
852 case IC_FusedRetainAutorelease:
853 case IC_FusedRetainAutoreleaseRV:
854 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000855 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000856 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000857 return NoModRef;
858 default:
859 break;
860 }
861
862 return AliasAnalysis::getModRefInfo(CS, Loc);
863}
864
865AliasAnalysis::ModRefResult
866ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
867 ImmutableCallSite CS2) {
868 // TODO: Theoretically we could check for dependencies between objc_* calls
869 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
870 return AliasAnalysis::getModRefInfo(CS1, CS2);
871}
872
Michael Gottesman81c61212013-01-14 00:35:14 +0000873/// @}
874///
875/// \defgroup ARCExpansion Early ARC Optimizations.
876/// @{
John McCall9fbd3182011-06-15 23:37:01 +0000877
878#include "llvm/Support/InstIterator.h"
879#include "llvm/Transforms/Scalar.h"
880
881namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000882 /// \brief Early ARC transformations.
John McCall9fbd3182011-06-15 23:37:01 +0000883 class ObjCARCExpand : public FunctionPass {
884 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000885 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000886 virtual bool runOnFunction(Function &F);
887
Michael Gottesman81c61212013-01-14 00:35:14 +0000888 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000889 bool Run;
890
John McCall9fbd3182011-06-15 23:37:01 +0000891 public:
892 static char ID;
893 ObjCARCExpand() : FunctionPass(ID) {
894 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
895 }
896 };
897}
898
899char ObjCARCExpand::ID = 0;
900INITIALIZE_PASS(ObjCARCExpand,
901 "objc-arc-expand", "ObjC ARC expansion", false, false)
902
903Pass *llvm::createObjCARCExpandPass() {
904 return new ObjCARCExpand();
905}
906
907void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
908 AU.setPreservesCFG();
909}
910
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000911bool ObjCARCExpand::doInitialization(Module &M) {
912 Run = ModuleHasARC(M);
913 return false;
914}
915
John McCall9fbd3182011-06-15 23:37:01 +0000916bool ObjCARCExpand::runOnFunction(Function &F) {
917 if (!EnableARCOpts)
918 return false;
919
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000920 // If nothing in the Module uses ARC, don't do anything.
921 if (!Run)
922 return false;
923
John McCall9fbd3182011-06-15 23:37:01 +0000924 bool Changed = false;
925
Michael Gottesmancf140052013-01-13 07:00:51 +0000926 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
927
John McCall9fbd3182011-06-15 23:37:01 +0000928 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
929 Instruction *Inst = &*I;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000930
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000931 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000932
John McCall9fbd3182011-06-15 23:37:01 +0000933 switch (GetBasicInstructionClass(Inst)) {
934 case IC_Retain:
935 case IC_RetainRV:
936 case IC_Autorelease:
937 case IC_AutoreleaseRV:
938 case IC_FusedRetainAutorelease:
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000939 case IC_FusedRetainAutoreleaseRV: {
John McCall9fbd3182011-06-15 23:37:01 +0000940 // These calls return their argument verbatim, as a low-level
941 // optimization. However, this makes high-level optimizations
942 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000943 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000944 Changed = true;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000945 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
946 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
947 " New = " << *Value << "\n");
948 Inst->replaceAllUsesWith(Value);
John McCall9fbd3182011-06-15 23:37:01 +0000949 break;
Michael Gottesmana6e23cc2013-01-01 16:05:54 +0000950 }
John McCall9fbd3182011-06-15 23:37:01 +0000951 default:
952 break;
953 }
954 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000955
Michael Gottesmanec21e2a2013-01-03 08:09:27 +0000956 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +0000957
John McCall9fbd3182011-06-15 23:37:01 +0000958 return Changed;
959}
960
Michael Gottesman81c61212013-01-14 00:35:14 +0000961/// @}
962///
963/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
964/// @{
Dan Gohman2f6263c2012-01-17 20:52:24 +0000965
Dan Gohman0daef3d2012-05-08 23:39:44 +0000966#include "llvm/ADT/STLExtras.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +0000967#include "llvm/IR/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000968
Dan Gohman2f6263c2012-01-17 20:52:24 +0000969namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +0000970 /// \brief Autorelease pool elimination.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000971 class ObjCARCAPElim : public ModulePass {
972 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
973 virtual bool runOnModule(Module &M);
974
Dan Gohman447989c2012-04-27 18:56:31 +0000975 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
976 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000977
978 public:
979 static char ID;
980 ObjCARCAPElim() : ModulePass(ID) {
981 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
982 }
983 };
984}
985
986char ObjCARCAPElim::ID = 0;
987INITIALIZE_PASS(ObjCARCAPElim,
988 "objc-arc-apelim",
989 "ObjC ARC autorelease pool elimination",
990 false, false)
991
992Pass *llvm::createObjCARCAPElimPass() {
993 return new ObjCARCAPElim();
994}
995
996void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
997 AU.setPreservesCFG();
998}
999
Michael Gottesman81c61212013-01-14 00:35:14 +00001000/// Interprocedurally determine if calls made by the given call site can
1001/// possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +00001002bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1003 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +00001004 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1005 return true;
Dan Gohman447989c2012-04-27 18:56:31 +00001006 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +00001007 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +00001008 const BasicBlock *BB = I;
1009 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1010 J != F; ++J)
1011 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +00001012 // This recursion depth limit is arbitrary. It's just great
1013 // enough to cover known interesting testcases.
1014 if (Depth < 3 &&
1015 !JCS.onlyReadsMemory() &&
1016 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001017 return true;
1018 }
1019 return false;
1020 }
1021
1022 return true;
1023}
1024
1025bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1026 bool Changed = false;
1027
1028 Instruction *Push = 0;
1029 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1030 Instruction *Inst = I++;
1031 switch (GetBasicInstructionClass(Inst)) {
1032 case IC_AutoreleasepoolPush:
1033 Push = Inst;
1034 break;
1035 case IC_AutoreleasepoolPop:
1036 // If this pop matches a push and nothing in between can autorelease,
1037 // zap the pair.
1038 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1039 Changed = true;
Michael Gottesman7899e472013-01-14 01:47:53 +00001040 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1041 "autorelease pair:\n"
1042 " Pop: " << *Inst << "\n"
Michael Gottesmandf379f42013-01-03 08:09:17 +00001043 << " Push: " << *Push << "\n");
Dan Gohman2f6263c2012-01-17 20:52:24 +00001044 Inst->eraseFromParent();
1045 Push->eraseFromParent();
1046 }
1047 Push = 0;
1048 break;
1049 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001050 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001051 Push = 0;
1052 break;
1053 default:
1054 break;
1055 }
1056 }
1057
1058 return Changed;
1059}
1060
1061bool ObjCARCAPElim::runOnModule(Module &M) {
1062 if (!EnableARCOpts)
1063 return false;
1064
1065 // If nothing in the Module uses ARC, don't do anything.
1066 if (!ModuleHasARC(M))
1067 return false;
1068
Dan Gohman1dae3e92012-01-18 21:19:38 +00001069 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001070 // identifying the global constructors. In theory, unnecessary autorelease
1071 // pools could occur anywhere, but in practice it's pretty rare. Global
1072 // ctors are a place where autorelease pools get inserted automatically,
1073 // so it's pretty common for them to be unnecessary, and it's pretty
1074 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001075 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1076 if (!GV)
1077 return false;
1078
1079 assert(GV->hasDefinitiveInitializer() &&
1080 "llvm.global_ctors is uncooperative!");
1081
Dan Gohman2f6263c2012-01-17 20:52:24 +00001082 bool Changed = false;
1083
Dan Gohman1dae3e92012-01-18 21:19:38 +00001084 // Dig the constructor functions out of GV's initializer.
1085 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1086 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1087 OI != OE; ++OI) {
1088 Value *Op = *OI;
1089 // llvm.global_ctors is an array of pairs where the second members
1090 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001091 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1092 // If the user used a constructor function with the wrong signature and
1093 // it got bitcasted or whatever, look the other way.
1094 if (!F)
1095 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001096 // Only look at function definitions.
1097 if (F->isDeclaration())
1098 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001099 // Only look at functions with one basic block.
1100 if (llvm::next(F->begin()) != F->end())
1101 continue;
1102 // Ok, a single-block constructor function definition. Try to optimize it.
1103 Changed |= OptimizeBB(F->begin());
1104 }
1105
1106 return Changed;
1107}
1108
Michael Gottesman81c61212013-01-14 00:35:14 +00001109/// @}
1110///
1111/// \defgroup ARCOpt ARC Optimization.
1112/// @{
John McCall9fbd3182011-06-15 23:37:01 +00001113
1114// TODO: On code like this:
1115//
1116// objc_retain(%x)
1117// stuff_that_cannot_release()
1118// objc_autorelease(%x)
1119// stuff_that_cannot_release()
1120// objc_retain(%x)
1121// stuff_that_cannot_release()
1122// objc_autorelease(%x)
1123//
1124// The second retain and autorelease can be deleted.
1125
1126// TODO: It should be possible to delete
1127// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1128// pairs if nothing is actually autoreleased between them. Also, autorelease
1129// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1130// after inlining) can be turned into plain release calls.
1131
1132// TODO: Critical-edge splitting. If the optimial insertion point is
1133// a critical edge, the current algorithm has to fail, because it doesn't
1134// know how to split edges. It should be possible to make the optimizer
1135// think in terms of edges, rather than blocks, and then split critical
1136// edges on demand.
1137
1138// TODO: OptimizeSequences could generalized to be Interprocedural.
1139
1140// TODO: Recognize that a bunch of other objc runtime calls have
1141// non-escaping arguments and non-releasing arguments, and may be
1142// non-autoreleasing.
1143
1144// TODO: Sink autorelease calls as far as possible. Unfortunately we
1145// usually can't sink them past other calls, which would be the main
1146// case where it would be useful.
1147
Dan Gohmane6d5e882011-08-19 00:26:36 +00001148// TODO: The pointer returned from objc_loadWeakRetained is retained.
1149
1150// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001151
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001152#include "llvm/ADT/SmallPtrSet.h"
1153#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00001154#include "llvm/IR/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001155#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001156
1157STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1158STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1159STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1160STATISTIC(NumRets, "Number of return value forwarding "
1161 "retain+autoreleaes eliminated");
1162STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1163STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1164
1165namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001166 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1167 /// techniques, except it uses special ObjC-specific reasoning about pointer
1168 /// relationships.
John McCall9fbd3182011-06-15 23:37:01 +00001169 class ProvenanceAnalysis {
1170 AliasAnalysis *AA;
1171
1172 typedef std::pair<const Value *, const Value *> ValuePairTy;
1173 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1174 CachedResultsTy CachedResults;
1175
1176 bool relatedCheck(const Value *A, const Value *B);
1177 bool relatedSelect(const SelectInst *A, const Value *B);
1178 bool relatedPHI(const PHINode *A, const Value *B);
1179
Craig Topperc2945e42012-09-18 02:01:41 +00001180 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1181 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001182
1183 public:
1184 ProvenanceAnalysis() {}
1185
1186 void setAA(AliasAnalysis *aa) { AA = aa; }
1187
1188 AliasAnalysis *getAA() const { return AA; }
1189
1190 bool related(const Value *A, const Value *B);
1191
1192 void clear() {
1193 CachedResults.clear();
1194 }
1195 };
1196}
1197
1198bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1199 // If the values are Selects with the same condition, we can do a more precise
1200 // check: just check for relations between the values on corresponding arms.
1201 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001202 if (A->getCondition() == SB->getCondition())
1203 return related(A->getTrueValue(), SB->getTrueValue()) ||
1204 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001205
1206 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001207 return related(A->getTrueValue(), B) ||
1208 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001209}
1210
1211bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1212 // If the values are PHIs in the same block, we can do a more precise as well
1213 // as efficient check: just check for relations between the values on
1214 // corresponding edges.
1215 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1216 if (PNB->getParent() == A->getParent()) {
1217 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1218 if (related(A->getIncomingValue(i),
1219 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1220 return true;
1221 return false;
1222 }
1223
1224 // Check each unique source of the PHI node against B.
1225 SmallPtrSet<const Value *, 4> UniqueSrc;
1226 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1227 const Value *PV1 = A->getIncomingValue(i);
1228 if (UniqueSrc.insert(PV1) && related(PV1, B))
1229 return true;
1230 }
1231
1232 // All of the arms checked out.
1233 return false;
1234}
1235
Michael Gottesman81c61212013-01-14 00:35:14 +00001236/// Test if the value of P, or any value covered by its provenance, is ever
1237/// stored within the function (not counting callees).
John McCall9fbd3182011-06-15 23:37:01 +00001238static bool isStoredObjCPointer(const Value *P) {
1239 SmallPtrSet<const Value *, 8> Visited;
1240 SmallVector<const Value *, 8> Worklist;
1241 Worklist.push_back(P);
1242 Visited.insert(P);
1243 do {
1244 P = Worklist.pop_back_val();
1245 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1246 UI != UE; ++UI) {
1247 const User *Ur = *UI;
1248 if (isa<StoreInst>(Ur)) {
1249 if (UI.getOperandNo() == 0)
1250 // The pointer is stored.
1251 return true;
1252 // The pointed is stored through.
1253 continue;
1254 }
1255 if (isa<CallInst>(Ur))
1256 // The pointer is passed as an argument, ignore this.
1257 continue;
1258 if (isa<PtrToIntInst>(P))
1259 // Assume the worst.
1260 return true;
1261 if (Visited.insert(Ur))
1262 Worklist.push_back(Ur);
1263 }
1264 } while (!Worklist.empty());
1265
1266 // Everything checked out.
1267 return false;
1268}
1269
1270bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1271 // Skip past provenance pass-throughs.
1272 A = GetUnderlyingObjCPtr(A);
1273 B = GetUnderlyingObjCPtr(B);
1274
1275 // Quick check.
1276 if (A == B)
1277 return true;
1278
1279 // Ask regular AliasAnalysis, for a first approximation.
1280 switch (AA->alias(A, B)) {
1281 case AliasAnalysis::NoAlias:
1282 return false;
1283 case AliasAnalysis::MustAlias:
1284 case AliasAnalysis::PartialAlias:
1285 return true;
1286 case AliasAnalysis::MayAlias:
1287 break;
1288 }
1289
1290 bool AIsIdentified = IsObjCIdentifiedObject(A);
1291 bool BIsIdentified = IsObjCIdentifiedObject(B);
1292
1293 // An ObjC-Identified object can't alias a load if it is never locally stored.
1294 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001295 // Check for an obvious escape.
1296 if (isa<LoadInst>(B))
1297 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001298 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001299 // Check for an obvious escape.
1300 if (isa<LoadInst>(A))
1301 return isStoredObjCPointer(B);
1302 // Both pointers are identified and escapes aren't an evident problem.
1303 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001304 }
Dan Gohman230768b2012-09-04 23:16:20 +00001305 } else if (BIsIdentified) {
1306 // Check for an obvious escape.
1307 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001308 return isStoredObjCPointer(B);
1309 }
1310
1311 // Special handling for PHI and Select.
1312 if (const PHINode *PN = dyn_cast<PHINode>(A))
1313 return relatedPHI(PN, B);
1314 if (const PHINode *PN = dyn_cast<PHINode>(B))
1315 return relatedPHI(PN, A);
1316 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1317 return relatedSelect(S, B);
1318 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1319 return relatedSelect(S, A);
1320
1321 // Conservative.
1322 return true;
1323}
1324
1325bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1326 // Begin by inserting a conservative value into the map. If the insertion
1327 // fails, we have the answer already. If it succeeds, leave it there until we
1328 // compute the real answer to guard against recursive queries.
1329 if (A > B) std::swap(A, B);
1330 std::pair<CachedResultsTy::iterator, bool> Pair =
1331 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1332 if (!Pair.second)
1333 return Pair.first->second;
1334
1335 bool Result = relatedCheck(A, B);
1336 CachedResults[ValuePairTy(A, B)] = Result;
1337 return Result;
1338}
1339
1340namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001341 /// \enum Sequence
1342 ///
1343 /// \brief A sequence of states that a pointer may go through in which an
1344 /// objc_retain and objc_release are actually needed.
John McCall9fbd3182011-06-15 23:37:01 +00001345 enum Sequence {
1346 S_None,
1347 S_Retain, ///< objc_retain(x)
1348 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1349 S_Use, ///< any use of x
1350 S_Stop, ///< like S_Release, but code motion is stopped
1351 S_Release, ///< objc_release(x)
1352 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1353 };
1354}
1355
1356static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1357 // The easy cases.
1358 if (A == B)
1359 return A;
1360 if (A == S_None || B == S_None)
1361 return S_None;
1362
John McCall9fbd3182011-06-15 23:37:01 +00001363 if (A > B) std::swap(A, B);
1364 if (TopDown) {
1365 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001366 if ((A == S_Retain || A == S_CanRelease) &&
1367 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001368 return B;
1369 } else {
1370 // Choose the side which is further along in the sequence.
1371 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001372 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001373 return A;
1374 // If both sides are releases, choose the more conservative one.
1375 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1376 return A;
1377 if (A == S_Release && B == S_MovableRelease)
1378 return A;
1379 }
1380
1381 return S_None;
1382}
1383
1384namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001385 /// \brief Unidirectional information about either a
John McCall9fbd3182011-06-15 23:37:01 +00001386 /// retain-decrement-use-release sequence or release-use-decrement-retain
1387 /// reverese sequence.
1388 struct RRInfo {
Michael Gottesman81c61212013-01-14 00:35:14 +00001389 /// After an objc_retain, the reference count of the referenced
Dan Gohmane6d5e882011-08-19 00:26:36 +00001390 /// object is known to be positive. Similarly, before an objc_release, the
1391 /// reference count of the referenced object is known to be positive. If
1392 /// there are retain-release pairs in code regions where the retain count
1393 /// is known to be positive, they can be eliminated, regardless of any side
1394 /// effects between them.
1395 ///
1396 /// Also, a retain+release pair nested within another retain+release
1397 /// pair all on the known same pointer value can be eliminated, regardless
1398 /// of any intervening side effects.
1399 ///
1400 /// KnownSafe is true when either of these conditions is satisfied.
1401 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001402
Michael Gottesman81c61212013-01-14 00:35:14 +00001403 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1404 /// calls).
John McCall9fbd3182011-06-15 23:37:01 +00001405 bool IsRetainBlock;
1406
Michael Gottesman81c61212013-01-14 00:35:14 +00001407 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCall9fbd3182011-06-15 23:37:01 +00001408 bool IsTailCallRelease;
1409
Michael Gottesman81c61212013-01-14 00:35:14 +00001410 /// If the Calls are objc_release calls and they all have a
1411 /// clang.imprecise_release tag, this is the metadata tag.
John McCall9fbd3182011-06-15 23:37:01 +00001412 MDNode *ReleaseMetadata;
1413
Michael Gottesman81c61212013-01-14 00:35:14 +00001414 /// For a top-down sequence, the set of objc_retains or
John McCall9fbd3182011-06-15 23:37:01 +00001415 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1416 SmallPtrSet<Instruction *, 2> Calls;
1417
Michael Gottesman81c61212013-01-14 00:35:14 +00001418 /// The set of optimal insert positions for moving calls in the opposite
1419 /// sequence.
John McCall9fbd3182011-06-15 23:37:01 +00001420 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1421
1422 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001423 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001424 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001425 ReleaseMetadata(0) {}
1426
1427 void clear();
1428 };
1429}
1430
1431void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001432 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001433 IsRetainBlock = false;
1434 IsTailCallRelease = false;
1435 ReleaseMetadata = 0;
1436 Calls.clear();
1437 ReverseInsertPts.clear();
1438}
1439
1440namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001441 /// \brief This class summarizes several per-pointer runtime properties which
1442 /// are propogated through the flow graph.
John McCall9fbd3182011-06-15 23:37:01 +00001443 class PtrState {
Michael Gottesman81c61212013-01-14 00:35:14 +00001444 /// True if the reference count is known to be incremented.
Dan Gohman50ade652012-04-25 00:50:46 +00001445 bool KnownPositiveRefCount;
1446
Michael Gottesman81c61212013-01-14 00:35:14 +00001447 /// True of we've seen an opportunity for partial RR elimination, such as
1448 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman50ade652012-04-25 00:50:46 +00001449 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001450
Michael Gottesman81c61212013-01-14 00:35:14 +00001451 /// The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001452 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001453
1454 public:
Michael Gottesman81c61212013-01-14 00:35:14 +00001455 /// Unidirectional information about the current sequence.
1456 ///
John McCall9fbd3182011-06-15 23:37:01 +00001457 /// TODO: Encapsulate this better.
1458 RRInfo RRI;
1459
Dan Gohman230768b2012-09-04 23:16:20 +00001460 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001461 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001462
Dan Gohman50ade652012-04-25 00:50:46 +00001463 void SetKnownPositiveRefCount() {
1464 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001465 }
1466
Dan Gohman50ade652012-04-25 00:50:46 +00001467 void ClearRefCount() {
1468 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001469 }
1470
John McCall9fbd3182011-06-15 23:37:01 +00001471 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001472 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001473 }
1474
1475 void SetSeq(Sequence NewSeq) {
1476 Seq = NewSeq;
1477 }
1478
John McCall9fbd3182011-06-15 23:37:01 +00001479 Sequence GetSeq() const {
1480 return Seq;
1481 }
1482
1483 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001484 ResetSequenceProgress(S_None);
1485 }
1486
1487 void ResetSequenceProgress(Sequence NewSeq) {
1488 Seq = NewSeq;
1489 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001490 RRI.clear();
1491 }
1492
1493 void Merge(const PtrState &Other, bool TopDown);
1494 };
1495}
1496
1497void
1498PtrState::Merge(const PtrState &Other, bool TopDown) {
1499 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001500 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001501
1502 // We can't merge a plain objc_retain with an objc_retainBlock.
1503 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1504 Seq = S_None;
1505
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001506 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001507 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001508 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001509 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001510 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001511 // If we're doing a merge on a path that's previously seen a partial
1512 // merge, conservatively drop the sequence, to avoid doing partial
1513 // RR elimination. If the branch predicates for the two merge differ,
1514 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001515 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001516 } else {
1517 // Conservatively merge the ReleaseMetadata information.
1518 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1519 RRI.ReleaseMetadata = 0;
1520
Dan Gohmane6d5e882011-08-19 00:26:36 +00001521 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001522 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1523 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001524 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001525
1526 // Merge the insert point sets. If there are any differences,
1527 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001528 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001529 for (SmallPtrSet<Instruction *, 2>::const_iterator
1530 I = Other.RRI.ReverseInsertPts.begin(),
1531 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001532 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001533 }
1534}
1535
1536namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001537 /// \brief Per-BasicBlock state.
John McCall9fbd3182011-06-15 23:37:01 +00001538 class BBState {
Michael Gottesman81c61212013-01-14 00:35:14 +00001539 /// The number of unique control paths from the entry which can reach this
1540 /// block.
John McCall9fbd3182011-06-15 23:37:01 +00001541 unsigned TopDownPathCount;
1542
Michael Gottesman81c61212013-01-14 00:35:14 +00001543 /// The number of unique control paths to exits from this block.
John McCall9fbd3182011-06-15 23:37:01 +00001544 unsigned BottomUpPathCount;
1545
Michael Gottesman81c61212013-01-14 00:35:14 +00001546 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCall9fbd3182011-06-15 23:37:01 +00001547 typedef MapVector<const Value *, PtrState> MapTy;
1548
Michael Gottesman81c61212013-01-14 00:35:14 +00001549 /// The top-down traversal uses this to record information known about a
1550 /// pointer at the bottom of each block.
John McCall9fbd3182011-06-15 23:37:01 +00001551 MapTy PerPtrTopDown;
1552
Michael Gottesman81c61212013-01-14 00:35:14 +00001553 /// The bottom-up traversal uses this to record information known about a
1554 /// pointer at the top of each block.
John McCall9fbd3182011-06-15 23:37:01 +00001555 MapTy PerPtrBottomUp;
1556
Michael Gottesman81c61212013-01-14 00:35:14 +00001557 /// Effective predecessors of the current block ignoring ignorable edges and
1558 /// ignored backedges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001559 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman81c61212013-01-14 00:35:14 +00001560 /// Effective successors of the current block ignoring ignorable edges and
1561 /// ignored backedges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001562 SmallVector<BasicBlock *, 2> Succs;
1563
John McCall9fbd3182011-06-15 23:37:01 +00001564 public:
1565 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1566
1567 typedef MapTy::iterator ptr_iterator;
1568 typedef MapTy::const_iterator ptr_const_iterator;
1569
1570 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1571 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1572 ptr_const_iterator top_down_ptr_begin() const {
1573 return PerPtrTopDown.begin();
1574 }
1575 ptr_const_iterator top_down_ptr_end() const {
1576 return PerPtrTopDown.end();
1577 }
1578
1579 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1580 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1581 ptr_const_iterator bottom_up_ptr_begin() const {
1582 return PerPtrBottomUp.begin();
1583 }
1584 ptr_const_iterator bottom_up_ptr_end() const {
1585 return PerPtrBottomUp.end();
1586 }
1587
Michael Gottesman81c61212013-01-14 00:35:14 +00001588 /// Mark this block as being an entry block, which has one path from the
1589 /// entry by definition.
John McCall9fbd3182011-06-15 23:37:01 +00001590 void SetAsEntry() { TopDownPathCount = 1; }
1591
Michael Gottesman81c61212013-01-14 00:35:14 +00001592 /// Mark this block as being an exit block, which has one path to an exit by
1593 /// definition.
John McCall9fbd3182011-06-15 23:37:01 +00001594 void SetAsExit() { BottomUpPathCount = 1; }
1595
1596 PtrState &getPtrTopDownState(const Value *Arg) {
1597 return PerPtrTopDown[Arg];
1598 }
1599
1600 PtrState &getPtrBottomUpState(const Value *Arg) {
1601 return PerPtrBottomUp[Arg];
1602 }
1603
1604 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001605 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001606 }
1607
1608 void clearTopDownPointers() {
1609 PerPtrTopDown.clear();
1610 }
1611
1612 void InitFromPred(const BBState &Other);
1613 void InitFromSucc(const BBState &Other);
1614 void MergePred(const BBState &Other);
1615 void MergeSucc(const BBState &Other);
1616
Michael Gottesman81c61212013-01-14 00:35:14 +00001617 /// Return the number of possible unique paths from an entry to an exit
1618 /// which pass through this block. This is only valid after both the
1619 /// top-down and bottom-up traversals are complete.
John McCall9fbd3182011-06-15 23:37:01 +00001620 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001621 assert(TopDownPathCount != 0);
1622 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001623 return TopDownPathCount * BottomUpPathCount;
1624 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001625
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001626 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001627 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001628 edge_iterator pred_begin() { return Preds.begin(); }
1629 edge_iterator pred_end() { return Preds.end(); }
1630 edge_iterator succ_begin() { return Succs.begin(); }
1631 edge_iterator succ_end() { return Succs.end(); }
1632
1633 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1634 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1635
1636 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001637 };
1638}
1639
1640void BBState::InitFromPred(const BBState &Other) {
1641 PerPtrTopDown = Other.PerPtrTopDown;
1642 TopDownPathCount = Other.TopDownPathCount;
1643}
1644
1645void BBState::InitFromSucc(const BBState &Other) {
1646 PerPtrBottomUp = Other.PerPtrBottomUp;
1647 BottomUpPathCount = Other.BottomUpPathCount;
1648}
1649
Michael Gottesman81c61212013-01-14 00:35:14 +00001650/// The top-down traversal uses this to merge information about predecessors to
1651/// form the initial state for a new block.
John McCall9fbd3182011-06-15 23:37:01 +00001652void BBState::MergePred(const BBState &Other) {
1653 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1654 // loop backedge. Loop backedges are special.
1655 TopDownPathCount += Other.TopDownPathCount;
1656
Michael Gottesman7899e472013-01-14 01:47:53 +00001657 // Check for overflow. If we have overflow, fall back to conservative
1658 // behavior.
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001659 if (TopDownPathCount < Other.TopDownPathCount) {
1660 clearTopDownPointers();
1661 return;
1662 }
1663
John McCall9fbd3182011-06-15 23:37:01 +00001664 // For each entry in the other set, if our set has an entry with the same key,
1665 // merge the entries. Otherwise, copy the entry and merge it with an empty
1666 // entry.
1667 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1668 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1669 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1670 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1671 /*TopDown=*/true);
1672 }
1673
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001674 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001675 // same key, force it to merge with an empty entry.
1676 for (ptr_iterator MI = top_down_ptr_begin(),
1677 ME = top_down_ptr_end(); MI != ME; ++MI)
1678 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1679 MI->second.Merge(PtrState(), /*TopDown=*/true);
1680}
1681
Michael Gottesman81c61212013-01-14 00:35:14 +00001682/// The bottom-up traversal uses this to merge information about successors to
1683/// form the initial state for a new block.
John McCall9fbd3182011-06-15 23:37:01 +00001684void BBState::MergeSucc(const BBState &Other) {
1685 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1686 // loop backedge. Loop backedges are special.
1687 BottomUpPathCount += Other.BottomUpPathCount;
1688
Michael Gottesman7899e472013-01-14 01:47:53 +00001689 // Check for overflow. If we have overflow, fall back to conservative
1690 // behavior.
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001691 if (BottomUpPathCount < Other.BottomUpPathCount) {
1692 clearBottomUpPointers();
1693 return;
1694 }
1695
John McCall9fbd3182011-06-15 23:37:01 +00001696 // For each entry in the other set, if our set has an entry with the
1697 // same key, merge the entries. Otherwise, copy the entry and merge
1698 // it with an empty entry.
1699 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1700 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1701 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1702 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1703 /*TopDown=*/false);
1704 }
1705
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001706 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001707 // with the same key, force it to merge with an empty entry.
1708 for (ptr_iterator MI = bottom_up_ptr_begin(),
1709 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1710 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1711 MI->second.Merge(PtrState(), /*TopDown=*/false);
1712}
1713
1714namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00001715 /// \brief The main ARC optimization pass.
John McCall9fbd3182011-06-15 23:37:01 +00001716 class ObjCARCOpt : public FunctionPass {
1717 bool Changed;
1718 ProvenanceAnalysis PA;
1719
Michael Gottesman81c61212013-01-14 00:35:14 +00001720 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001721 bool Run;
1722
Michael Gottesman81c61212013-01-14 00:35:14 +00001723 /// Declarations for ObjC runtime functions, for use in creating calls to
1724 /// them. These are initialized lazily to avoid cluttering up the Module
1725 /// with unused declarations.
John McCall9fbd3182011-06-15 23:37:01 +00001726
Michael Gottesman81c61212013-01-14 00:35:14 +00001727 /// Declaration for ObjC runtime function
1728 /// objc_retainAutoreleasedReturnValue.
1729 Constant *RetainRVCallee;
1730 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1731 Constant *AutoreleaseRVCallee;
1732 /// Declaration for ObjC runtime function objc_release.
1733 Constant *ReleaseCallee;
1734 /// Declaration for ObjC runtime function objc_retain.
1735 Constant *RetainCallee;
1736 /// Declaration for ObjC runtime function objc_retainBlock.
1737 Constant *RetainBlockCallee;
1738 /// Declaration for ObjC runtime function objc_autorelease.
1739 Constant *AutoreleaseCallee;
1740
1741 /// Flags which determine whether each of the interesting runtine functions
1742 /// is in fact used in the current function.
John McCall9fbd3182011-06-15 23:37:01 +00001743 unsigned UsedInThisFunction;
1744
Michael Gottesman81c61212013-01-14 00:35:14 +00001745 /// The Metadata Kind for clang.imprecise_release metadata.
John McCall9fbd3182011-06-15 23:37:01 +00001746 unsigned ImpreciseReleaseMDKind;
1747
Michael Gottesman81c61212013-01-14 00:35:14 +00001748 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana974bea2011-10-17 22:53:25 +00001749 unsigned CopyOnEscapeMDKind;
1750
Michael Gottesman81c61212013-01-14 00:35:14 +00001751 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohmandbe266b2012-02-17 18:59:53 +00001752 unsigned NoObjCARCExceptionsMDKind;
1753
John McCall9fbd3182011-06-15 23:37:01 +00001754 Constant *getRetainRVCallee(Module *M);
1755 Constant *getAutoreleaseRVCallee(Module *M);
1756 Constant *getReleaseCallee(Module *M);
1757 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001758 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001759 Constant *getAutoreleaseCallee(Module *M);
1760
Dan Gohman79522dc2012-01-13 00:39:07 +00001761 bool IsRetainBlockOptimizable(const Instruction *Inst);
1762
John McCall9fbd3182011-06-15 23:37:01 +00001763 void OptimizeRetainCall(Function &F, Instruction *Retain);
1764 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman0e385452013-01-12 01:25:19 +00001765 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1766 InstructionClass &Class);
John McCall9fbd3182011-06-15 23:37:01 +00001767 void OptimizeIndividualCalls(Function &F);
1768
1769 void CheckForCFGHazards(const BasicBlock *BB,
1770 DenseMap<const BasicBlock *, BBState> &BBStates,
1771 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001772 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001773 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001774 MapVector<Value *, RRInfo> &Retains,
1775 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001776 bool VisitBottomUp(BasicBlock *BB,
1777 DenseMap<const BasicBlock *, BBState> &BBStates,
1778 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001779 bool VisitInstructionTopDown(Instruction *Inst,
1780 DenseMap<Value *, RRInfo> &Releases,
1781 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001782 bool VisitTopDown(BasicBlock *BB,
1783 DenseMap<const BasicBlock *, BBState> &BBStates,
1784 DenseMap<Value *, RRInfo> &Releases);
1785 bool Visit(Function &F,
1786 DenseMap<const BasicBlock *, BBState> &BBStates,
1787 MapVector<Value *, RRInfo> &Retains,
1788 DenseMap<Value *, RRInfo> &Releases);
1789
1790 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1791 MapVector<Value *, RRInfo> &Retains,
1792 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001793 SmallVectorImpl<Instruction *> &DeadInsts,
1794 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001795
1796 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1797 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001798 DenseMap<Value *, RRInfo> &Releases,
1799 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001800
1801 void OptimizeWeakCalls(Function &F);
1802
1803 bool OptimizeSequences(Function &F);
1804
1805 void OptimizeReturns(Function &F);
1806
1807 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1808 virtual bool doInitialization(Module &M);
1809 virtual bool runOnFunction(Function &F);
1810 virtual void releaseMemory();
1811
1812 public:
1813 static char ID;
1814 ObjCARCOpt() : FunctionPass(ID) {
1815 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1816 }
1817 };
1818}
1819
1820char ObjCARCOpt::ID = 0;
1821INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1822 "objc-arc", "ObjC ARC optimization", false, false)
1823INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1824INITIALIZE_PASS_END(ObjCARCOpt,
1825 "objc-arc", "ObjC ARC optimization", false, false)
1826
1827Pass *llvm::createObjCARCOptPass() {
1828 return new ObjCARCOpt();
1829}
1830
1831void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1832 AU.addRequired<ObjCARCAliasAnalysis>();
1833 AU.addRequired<AliasAnalysis>();
1834 // ARC optimization doesn't currently split critical edges.
1835 AU.setPreservesCFG();
1836}
1837
Dan Gohman79522dc2012-01-13 00:39:07 +00001838bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1839 // Without the magic metadata tag, we have to assume this might be an
1840 // objc_retainBlock call inserted to convert a block pointer to an id,
1841 // in which case it really is needed.
1842 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1843 return false;
1844
1845 // If the pointer "escapes" (not including being used in a call),
1846 // the copy may be needed.
1847 if (DoesObjCBlockEscape(Inst))
1848 return false;
1849
1850 // Otherwise, it's not needed.
1851 return true;
1852}
1853
John McCall9fbd3182011-06-15 23:37:01 +00001854Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1855 if (!RetainRVCallee) {
1856 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001857 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001858 Type *Params[] = { I8X };
1859 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001860 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001861 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001862 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001863 RetainRVCallee =
1864 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001865 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001866 }
1867 return RetainRVCallee;
1868}
1869
1870Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1871 if (!AutoreleaseRVCallee) {
1872 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001873 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001874 Type *Params[] = { I8X };
1875 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001876 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001877 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001878 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001879 AutoreleaseRVCallee =
1880 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001881 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001882 }
1883 return AutoreleaseRVCallee;
1884}
1885
1886Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1887 if (!ReleaseCallee) {
1888 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001889 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001890 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001891 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001892 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001893 ReleaseCallee =
1894 M->getOrInsertFunction(
1895 "objc_release",
1896 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001897 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001898 }
1899 return ReleaseCallee;
1900}
1901
1902Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1903 if (!RetainCallee) {
1904 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001905 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001906 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001907 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001908 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001909 RetainCallee =
1910 M->getOrInsertFunction(
1911 "objc_retain",
1912 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001913 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001914 }
1915 return RetainCallee;
1916}
1917
Dan Gohman44280692011-07-22 22:29:21 +00001918Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1919 if (!RetainBlockCallee) {
1920 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001921 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001922 // objc_retainBlock is not nounwind because it calls user copy constructors
1923 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001924 RetainBlockCallee =
1925 M->getOrInsertFunction(
1926 "objc_retainBlock",
1927 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001928 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001929 }
1930 return RetainBlockCallee;
1931}
1932
John McCall9fbd3182011-06-15 23:37:01 +00001933Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1934 if (!AutoreleaseCallee) {
1935 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001936 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001937 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001938 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001939 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001940 AutoreleaseCallee =
1941 M->getOrInsertFunction(
1942 "objc_autorelease",
1943 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001944 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001945 }
1946 return AutoreleaseCallee;
1947}
1948
Michael Gottesman81c61212013-01-14 00:35:14 +00001949/// Test whether the given value is possible a reference-counted pointer,
1950/// including tests which utilize AliasAnalysis.
Dan Gohman230768b2012-09-04 23:16:20 +00001951static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1952 // First make the rudimentary check.
1953 if (!IsPotentialUse(Op))
1954 return false;
1955
1956 // Objects in constant memory are not reference-counted.
1957 if (AA.pointsToConstantMemory(Op))
1958 return false;
1959
1960 // Pointers in constant memory are not pointing to reference-counted objects.
1961 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1962 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1963 return false;
1964
1965 // Otherwise assume the worst.
1966 return true;
1967}
1968
Michael Gottesman81c61212013-01-14 00:35:14 +00001969/// Test whether the given instruction can result in a reference count
1970/// modification (positive or negative) for the pointer's object.
John McCall9fbd3182011-06-15 23:37:01 +00001971static bool
1972CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1973 ProvenanceAnalysis &PA, InstructionClass Class) {
1974 switch (Class) {
1975 case IC_Autorelease:
1976 case IC_AutoreleaseRV:
1977 case IC_User:
1978 // These operations never directly modify a reference count.
1979 return false;
1980 default: break;
1981 }
1982
1983 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1984 assert(CS && "Only calls can alter reference counts!");
1985
1986 // See if AliasAnalysis can help us with the call.
1987 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1988 if (AliasAnalysis::onlyReadsMemory(MRB))
1989 return false;
1990 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1991 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1992 I != E; ++I) {
1993 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001994 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001995 return true;
1996 }
1997 return false;
1998 }
1999
2000 // Assume the worst.
2001 return true;
2002}
2003
Michael Gottesman81c61212013-01-14 00:35:14 +00002004/// Test whether the given instruction can "use" the given pointer's object in a
2005/// way that requires the reference count to be positive.
John McCall9fbd3182011-06-15 23:37:01 +00002006static bool
2007CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2008 InstructionClass Class) {
2009 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2010 if (Class == IC_Call)
2011 return false;
2012
2013 // Consider various instructions which may have pointer arguments which are
2014 // not "uses".
2015 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2016 // Comparing a pointer with null, or any other constant, isn't really a use,
2017 // because we don't care what the pointer points to, or about the values
2018 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00002019 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00002020 return false;
2021 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2022 // For calls, just check the arguments (and not the callee operand).
2023 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2024 OE = CS.arg_end(); OI != OE; ++OI) {
2025 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002026 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002027 return true;
2028 }
2029 return false;
2030 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2031 // Special-case stores, because we don't care about the stored value, just
2032 // the store address.
2033 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2034 // If we can't tell what the underlying object was, assume there is a
2035 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00002036 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00002037 }
2038
2039 // Check each operand for a match.
2040 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2041 OI != OE; ++OI) {
2042 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00002043 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00002044 return true;
2045 }
2046 return false;
2047}
2048
Michael Gottesman81c61212013-01-14 00:35:14 +00002049/// Test whether the given instruction can autorelease any pointer or cause an
2050/// autoreleasepool pop.
John McCall9fbd3182011-06-15 23:37:01 +00002051static bool
2052CanInterruptRV(InstructionClass Class) {
2053 switch (Class) {
2054 case IC_AutoreleasepoolPop:
2055 case IC_CallOrUser:
2056 case IC_Call:
2057 case IC_Autorelease:
2058 case IC_AutoreleaseRV:
2059 case IC_FusedRetainAutorelease:
2060 case IC_FusedRetainAutoreleaseRV:
2061 return true;
2062 default:
2063 return false;
2064 }
2065}
2066
2067namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00002068 /// \enum DependenceKind
2069 /// \brief Defines different dependence kinds among various ARC constructs.
2070 ///
2071 /// There are several kinds of dependence-like concepts in use here.
2072 ///
John McCall9fbd3182011-06-15 23:37:01 +00002073 enum DependenceKind {
2074 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002075 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002076 CanChangeRetainCount,
2077 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2078 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2079 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2080 };
2081}
2082
Michael Gottesman81c61212013-01-14 00:35:14 +00002083/// Test if there can be dependencies on Inst through Arg. This function only
2084/// tests dependencies relevant for removing pairs of calls.
John McCall9fbd3182011-06-15 23:37:01 +00002085static bool
2086Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2087 ProvenanceAnalysis &PA) {
2088 // If we've reached the definition of Arg, stop.
2089 if (Inst == Arg)
2090 return true;
2091
2092 switch (Flavor) {
2093 case NeedsPositiveRetainCount: {
2094 InstructionClass Class = GetInstructionClass(Inst);
2095 switch (Class) {
2096 case IC_AutoreleasepoolPop:
2097 case IC_AutoreleasepoolPush:
2098 case IC_None:
2099 return false;
2100 default:
2101 return CanUse(Inst, Arg, PA, Class);
2102 }
2103 }
2104
Dan Gohman511568d2012-04-13 00:59:57 +00002105 case AutoreleasePoolBoundary: {
2106 InstructionClass Class = GetInstructionClass(Inst);
2107 switch (Class) {
2108 case IC_AutoreleasepoolPop:
2109 case IC_AutoreleasepoolPush:
2110 // These mark the end and begin of an autorelease pool scope.
2111 return true;
2112 default:
2113 // Nothing else does this.
2114 return false;
2115 }
2116 }
2117
John McCall9fbd3182011-06-15 23:37:01 +00002118 case CanChangeRetainCount: {
2119 InstructionClass Class = GetInstructionClass(Inst);
2120 switch (Class) {
2121 case IC_AutoreleasepoolPop:
2122 // Conservatively assume this can decrement any count.
2123 return true;
2124 case IC_AutoreleasepoolPush:
2125 case IC_None:
2126 return false;
2127 default:
2128 return CanAlterRefCount(Inst, Arg, PA, Class);
2129 }
2130 }
2131
2132 case RetainAutoreleaseDep:
2133 switch (GetBasicInstructionClass(Inst)) {
2134 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002135 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002136 // Don't merge an objc_autorelease with an objc_retain inside a different
2137 // autoreleasepool scope.
2138 return true;
2139 case IC_Retain:
2140 case IC_RetainRV:
2141 // Check for a retain of the same pointer for merging.
2142 return GetObjCArg(Inst) == Arg;
2143 default:
2144 // Nothing else matters for objc_retainAutorelease formation.
2145 return false;
2146 }
John McCall9fbd3182011-06-15 23:37:01 +00002147
2148 case RetainAutoreleaseRVDep: {
2149 InstructionClass Class = GetBasicInstructionClass(Inst);
2150 switch (Class) {
2151 case IC_Retain:
2152 case IC_RetainRV:
2153 // Check for a retain of the same pointer for merging.
2154 return GetObjCArg(Inst) == Arg;
2155 default:
2156 // Anything that can autorelease interrupts
2157 // retainAutoreleaseReturnValue formation.
2158 return CanInterruptRV(Class);
2159 }
John McCall9fbd3182011-06-15 23:37:01 +00002160 }
2161
2162 case RetainRVDep:
2163 return CanInterruptRV(GetBasicInstructionClass(Inst));
2164 }
2165
2166 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002167}
2168
Michael Gottesman81c61212013-01-14 00:35:14 +00002169/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2170/// non-local dependencies on Arg.
2171///
John McCall9fbd3182011-06-15 23:37:01 +00002172/// TODO: Cache results?
2173static void
2174FindDependencies(DependenceKind Flavor,
2175 const Value *Arg,
2176 BasicBlock *StartBB, Instruction *StartInst,
2177 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2178 SmallPtrSet<const BasicBlock *, 4> &Visited,
2179 ProvenanceAnalysis &PA) {
2180 BasicBlock::iterator StartPos = StartInst;
2181
2182 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2183 Worklist.push_back(std::make_pair(StartBB, StartPos));
2184 do {
2185 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2186 Worklist.pop_back_val();
2187 BasicBlock *LocalStartBB = Pair.first;
2188 BasicBlock::iterator LocalStartPos = Pair.second;
2189 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2190 for (;;) {
2191 if (LocalStartPos == StartBBBegin) {
2192 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2193 if (PI == PE)
2194 // If we've reached the function entry, produce a null dependence.
2195 DependingInstructions.insert(0);
2196 else
2197 // Add the predecessors to the worklist.
2198 do {
2199 BasicBlock *PredBB = *PI;
2200 if (Visited.insert(PredBB))
2201 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2202 } while (++PI != PE);
2203 break;
2204 }
2205
2206 Instruction *Inst = --LocalStartPos;
2207 if (Depends(Flavor, Inst, Arg, PA)) {
2208 DependingInstructions.insert(Inst);
2209 break;
2210 }
2211 }
2212 } while (!Worklist.empty());
2213
2214 // Determine whether the original StartBB post-dominates all of the blocks we
2215 // visited. If not, insert a sentinal indicating that most optimizations are
2216 // not safe.
2217 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2218 E = Visited.end(); I != E; ++I) {
2219 const BasicBlock *BB = *I;
2220 if (BB == StartBB)
2221 continue;
2222 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2223 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2224 const BasicBlock *Succ = *SI;
2225 if (Succ != StartBB && !Visited.count(Succ)) {
2226 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2227 return;
2228 }
2229 }
2230 }
2231}
2232
2233static bool isNullOrUndef(const Value *V) {
2234 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2235}
2236
2237static bool isNoopInstruction(const Instruction *I) {
2238 return isa<BitCastInst>(I) ||
2239 (isa<GetElementPtrInst>(I) &&
2240 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2241}
2242
Michael Gottesman81c61212013-01-14 00:35:14 +00002243/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2244/// return value.
John McCall9fbd3182011-06-15 23:37:01 +00002245void
2246ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002247 ImmutableCallSite CS(GetObjCArg(Retain));
2248 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002249 if (!Call) return;
2250 if (Call->getParent() != Retain->getParent()) return;
2251
2252 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002253 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002254 ++I;
2255 while (isNoopInstruction(I)) ++I;
2256 if (&*I != Retain)
2257 return;
2258
2259 // Turn it to an objc_retainAutoreleasedReturnValue..
2260 Changed = true;
2261 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002262
Michael Gottesman715f6a62013-01-04 21:30:38 +00002263 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesmane7a715f2013-01-12 03:45:49 +00002264 "objc_retain => objc_retainAutoreleasedReturnValue"
2265 " since the operand is a return value.\n"
Michael Gottesman715f6a62013-01-04 21:30:38 +00002266 " Old: "
2267 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002268
John McCall9fbd3182011-06-15 23:37:01 +00002269 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman715f6a62013-01-04 21:30:38 +00002270
2271 DEBUG(dbgs() << " New: "
2272 << *Retain << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002273}
2274
Michael Gottesman81c61212013-01-14 00:35:14 +00002275/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2276/// not a return value. Or, if it can be paired with an
2277/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002278bool
2279ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002280 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002281 const Value *Arg = GetObjCArg(RetainRV);
2282 ImmutableCallSite CS(Arg);
2283 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002284 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002285 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002286 ++I;
2287 while (isNoopInstruction(I)) ++I;
2288 if (&*I == RetainRV)
2289 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002290 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002291 BasicBlock *RetainRVParent = RetainRV->getParent();
2292 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002293 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002294 while (isNoopInstruction(I)) ++I;
2295 if (&*I == RetainRV)
2296 return false;
2297 }
John McCall9fbd3182011-06-15 23:37:01 +00002298 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002299 }
John McCall9fbd3182011-06-15 23:37:01 +00002300
2301 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2302 // pointer. In this case, we can delete the pair.
2303 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2304 if (I != Begin) {
2305 do --I; while (I != Begin && isNoopInstruction(I));
2306 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2307 GetObjCArg(I) == Arg) {
2308 Changed = true;
2309 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002310
Michael Gottesman87a0f022013-01-05 17:55:35 +00002311 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2312 << " Erasing " << *RetainRV
2313 << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002314
John McCall9fbd3182011-06-15 23:37:01 +00002315 EraseInstruction(I);
2316 EraseInstruction(RetainRV);
2317 return true;
2318 }
2319 }
2320
2321 // Turn it to a plain objc_retain.
2322 Changed = true;
2323 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002324
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002325 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2326 "objc_retainAutoreleasedReturnValue => "
2327 "objc_retain since the operand is not a return value.\n"
2328 " Old: "
2329 << *RetainRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002330
John McCall9fbd3182011-06-15 23:37:01 +00002331 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesman36e4bc42013-01-05 17:55:42 +00002332
2333 DEBUG(dbgs() << " New: "
2334 << *RetainRV << "\n");
2335
John McCall9fbd3182011-06-15 23:37:01 +00002336 return false;
2337}
2338
Michael Gottesman81c61212013-01-14 00:35:14 +00002339/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2340/// used as a return value.
John McCall9fbd3182011-06-15 23:37:01 +00002341void
Michael Gottesman0e385452013-01-12 01:25:19 +00002342ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2343 InstructionClass &Class) {
John McCall9fbd3182011-06-15 23:37:01 +00002344 // Check for a return of the pointer value.
2345 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002346 SmallVector<const Value *, 2> Users;
2347 Users.push_back(Ptr);
2348 do {
2349 Ptr = Users.pop_back_val();
2350 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2351 UI != UE; ++UI) {
2352 const User *I = *UI;
2353 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2354 return;
2355 if (isa<BitCastInst>(I))
2356 Users.push_back(I);
2357 }
2358 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002359
2360 Changed = true;
2361 ++NumPeeps;
Michael Gottesman48239c72013-01-06 21:07:11 +00002362
2363 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2364 "objc_autoreleaseReturnValue => "
2365 "objc_autorelease since its operand is not used as a return "
2366 "value.\n"
2367 " Old: "
2368 << *AutoreleaseRV << "\n");
2369
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002370 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2371 AutoreleaseRVCI->
John McCall9fbd3182011-06-15 23:37:01 +00002372 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002373 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman0e385452013-01-12 01:25:19 +00002374 Class = IC_Autorelease;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002375
Michael Gottesman48239c72013-01-06 21:07:11 +00002376 DEBUG(dbgs() << " New: "
2377 << *AutoreleaseRV << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002378
John McCall9fbd3182011-06-15 23:37:01 +00002379}
2380
Michael Gottesman81c61212013-01-14 00:35:14 +00002381/// Visit each call, one at a time, and make simplifications without doing any
2382/// additional analysis.
John McCall9fbd3182011-06-15 23:37:01 +00002383void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2384 // Reset all the flags in preparation for recomputing them.
2385 UsedInThisFunction = 0;
2386
2387 // Visit all objc_* calls in F.
2388 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2389 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002390
Michael Gottesman5c0ae472013-01-04 21:29:57 +00002391 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002392 *Inst << "\n");
2393
John McCall9fbd3182011-06-15 23:37:01 +00002394 InstructionClass Class = GetBasicInstructionClass(Inst);
2395
2396 switch (Class) {
2397 default: break;
2398
2399 // Delete no-op casts. These function calls have special semantics, but
2400 // the semantics are entirely implemented via lowering in the front-end,
2401 // so by the time they reach the optimizer, they are just no-op calls
2402 // which return their argument.
2403 //
2404 // There are gray areas here, as the ability to cast reference-counted
2405 // pointers to raw void* and back allows code to break ARC assumptions,
2406 // however these are currently considered to be unimportant.
2407 case IC_NoopCast:
2408 Changed = true;
2409 ++NumNoops;
Michael Gottesman4680abe2013-01-06 21:07:15 +00002410 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2411 " " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002412 EraseInstruction(Inst);
2413 continue;
2414
2415 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2416 case IC_StoreWeak:
2417 case IC_LoadWeak:
2418 case IC_LoadWeakRetained:
2419 case IC_InitWeak:
2420 case IC_DestroyWeak: {
2421 CallInst *CI = cast<CallInst>(Inst);
2422 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002423 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002424 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002425 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2426 Constant::getNullValue(Ty),
2427 CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002428 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmane5494922013-01-06 21:54:30 +00002429 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2430 "pointer-to-weak-pointer is undefined behavior.\n"
2431 " Old = " << *CI <<
2432 "\n New = " <<
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002433 *NewValue << "\n");
Michael Gottesmane5494922013-01-06 21:54:30 +00002434 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002435 CI->eraseFromParent();
2436 continue;
2437 }
2438 break;
2439 }
2440 case IC_CopyWeak:
2441 case IC_MoveWeak: {
2442 CallInst *CI = cast<CallInst>(Inst);
2443 if (isNullOrUndef(CI->getArgOperand(0)) ||
2444 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002445 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002446 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002447 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2448 Constant::getNullValue(Ty),
2449 CI);
Michael Gottesmane5494922013-01-06 21:54:30 +00002450
2451 llvm::Value *NewValue = UndefValue::get(CI->getType());
2452 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2453 "pointer-to-weak-pointer is undefined behavior.\n"
2454 " Old = " << *CI <<
2455 "\n New = " <<
2456 *NewValue << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002457
Michael Gottesmane5494922013-01-06 21:54:30 +00002458 CI->replaceAllUsesWith(NewValue);
John McCall9fbd3182011-06-15 23:37:01 +00002459 CI->eraseFromParent();
2460 continue;
2461 }
2462 break;
2463 }
2464 case IC_Retain:
2465 OptimizeRetainCall(F, Inst);
2466 break;
2467 case IC_RetainRV:
2468 if (OptimizeRetainRVCall(F, Inst))
2469 continue;
2470 break;
2471 case IC_AutoreleaseRV:
Michael Gottesman0e385452013-01-12 01:25:19 +00002472 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCall9fbd3182011-06-15 23:37:01 +00002473 break;
2474 }
2475
2476 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2477 if (IsAutorelease(Class) && Inst->use_empty()) {
2478 CallInst *Call = cast<CallInst>(Inst);
2479 const Value *Arg = Call->getArgOperand(0);
2480 Arg = FindSingleUseIdentifiedObject(Arg);
2481 if (Arg) {
2482 Changed = true;
2483 ++NumAutoreleases;
2484
2485 // Create the declaration lazily.
2486 LLVMContext &C = Inst->getContext();
2487 CallInst *NewCall =
2488 CallInst::Create(getReleaseCallee(F.getParent()),
2489 Call->getArgOperand(0), "", Call);
2490 NewCall->setMetadata(ImpreciseReleaseMDKind,
2491 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002492
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002493 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2494 "objc_autorelease(x) with objc_release(x) since x is "
2495 "otherwise unused.\n"
Michael Gottesman79561272013-01-06 22:56:54 +00002496 " Old: " << *Call <<
Michael Gottesman20d9fff2013-01-06 22:56:50 +00002497 "\n New: " <<
2498 *NewCall << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00002499
John McCall9fbd3182011-06-15 23:37:01 +00002500 EraseInstruction(Call);
2501 Inst = NewCall;
2502 Class = IC_Release;
2503 }
2504 }
2505
2506 // For functions which can never be passed stack arguments, add
2507 // a tail keyword.
2508 if (IsAlwaysTail(Class)) {
2509 Changed = true;
Michael Gottesman817d4e92013-01-06 23:39:09 +00002510 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2511 " to function since it can never be passed stack args: " << *Inst <<
2512 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002513 cast<CallInst>(Inst)->setTailCall();
2514 }
2515
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002516 // Ensure that functions that can never have a "tail" keyword due to the
2517 // semantics of ARC truly do not do so.
2518 if (IsNeverTail(Class)) {
2519 Changed = true;
Michael Gottesman7899e472013-01-14 01:47:53 +00002520 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2521 "keyword from function: " << *Inst <<
Michael Gottesmane8c161a2013-01-12 01:25:15 +00002522 "\n");
2523 cast<CallInst>(Inst)->setTailCall(false);
2524 }
2525
John McCall9fbd3182011-06-15 23:37:01 +00002526 // Set nounwind as needed.
2527 if (IsNoThrow(Class)) {
2528 Changed = true;
Michael Gottesman38bc25a2013-01-06 23:39:13 +00002529 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2530 " class. Setting nounwind on: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002531 cast<CallInst>(Inst)->setDoesNotThrow();
2532 }
2533
2534 if (!IsNoopOnNull(Class)) {
2535 UsedInThisFunction |= 1 << Class;
2536 continue;
2537 }
2538
2539 const Value *Arg = GetObjCArg(Inst);
2540
2541 // ARC calls with null are no-ops. Delete them.
2542 if (isNullOrUndef(Arg)) {
2543 Changed = true;
2544 ++NumNoops;
Michael Gottesmanfbe4d6b2013-01-07 00:04:52 +00002545 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2546 " null are no-ops. Erasing: " << *Inst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002547 EraseInstruction(Inst);
2548 continue;
2549 }
2550
2551 // Keep track of which of retain, release, autorelease, and retain_block
2552 // are actually present in this function.
2553 UsedInThisFunction |= 1 << Class;
2554
2555 // If Arg is a PHI, and one or more incoming values to the
2556 // PHI are null, and the call is control-equivalent to the PHI, and there
2557 // are no relevant side effects between the PHI and the call, the call
2558 // could be pushed up to just those paths with non-null incoming values.
2559 // For now, don't bother splitting critical edges for this.
2560 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2561 Worklist.push_back(std::make_pair(Inst, Arg));
2562 do {
2563 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2564 Inst = Pair.first;
2565 Arg = Pair.second;
2566
2567 const PHINode *PN = dyn_cast<PHINode>(Arg);
2568 if (!PN) continue;
2569
2570 // Determine if the PHI has any null operands, or any incoming
2571 // critical edges.
2572 bool HasNull = false;
2573 bool HasCriticalEdges = false;
2574 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2575 Value *Incoming =
2576 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2577 if (isNullOrUndef(Incoming))
2578 HasNull = true;
2579 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2580 .getNumSuccessors() != 1) {
2581 HasCriticalEdges = true;
2582 break;
2583 }
2584 }
2585 // If we have null operands and no critical edges, optimize.
2586 if (!HasCriticalEdges && HasNull) {
2587 SmallPtrSet<Instruction *, 4> DependingInstructions;
2588 SmallPtrSet<const BasicBlock *, 4> Visited;
2589
2590 // Check that there is nothing that cares about the reference
2591 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002592 switch (Class) {
2593 case IC_Retain:
2594 case IC_RetainBlock:
2595 // These can always be moved up.
2596 break;
2597 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002598 // These can't be moved across things that care about the retain
2599 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002600 FindDependencies(NeedsPositiveRetainCount, Arg,
2601 Inst->getParent(), Inst,
2602 DependingInstructions, Visited, PA);
2603 break;
2604 case IC_Autorelease:
2605 // These can't be moved across autorelease pool scope boundaries.
2606 FindDependencies(AutoreleasePoolBoundary, Arg,
2607 Inst->getParent(), Inst,
2608 DependingInstructions, Visited, PA);
2609 break;
2610 case IC_RetainRV:
2611 case IC_AutoreleaseRV:
2612 // Don't move these; the RV optimization depends on the autoreleaseRV
2613 // being tail called, and the retainRV being immediately after a call
2614 // (which might still happen if we get lucky with codegen layout, but
2615 // it's not worth taking the chance).
2616 continue;
2617 default:
2618 llvm_unreachable("Invalid dependence flavor");
2619 }
2620
John McCall9fbd3182011-06-15 23:37:01 +00002621 if (DependingInstructions.size() == 1 &&
2622 *DependingInstructions.begin() == PN) {
2623 Changed = true;
2624 ++NumPartialNoops;
2625 // Clone the call into each predecessor that has a non-null value.
2626 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002627 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002628 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2629 Value *Incoming =
2630 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2631 if (!isNullOrUndef(Incoming)) {
2632 CallInst *Clone = cast<CallInst>(CInst->clone());
2633 Value *Op = PN->getIncomingValue(i);
2634 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2635 if (Op->getType() != ParamTy)
2636 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2637 Clone->setArgOperand(0, Op);
2638 Clone->insertBefore(InsertPos);
Michael Gottesman55811152013-01-09 19:23:24 +00002639
2640 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2641 << *CInst << "\n"
2642 " And inserting "
2643 "clone at " << *InsertPos << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002644 Worklist.push_back(std::make_pair(Clone, Incoming));
2645 }
2646 }
2647 // Erase the original call.
Michael Gottesman55811152013-01-09 19:23:24 +00002648 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00002649 EraseInstruction(CInst);
2650 continue;
2651 }
2652 }
2653 } while (!Worklist.empty());
2654 }
Michael Gottesman0d3582b2013-01-12 02:57:16 +00002655 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCall9fbd3182011-06-15 23:37:01 +00002656}
2657
Michael Gottesman81c61212013-01-14 00:35:14 +00002658/// Check for critical edges, loop boundaries, irreducible control flow, or
2659/// other CFG structures where moving code across the edge would result in it
2660/// being executed more.
John McCall9fbd3182011-06-15 23:37:01 +00002661void
2662ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2663 DenseMap<const BasicBlock *, BBState> &BBStates,
2664 BBState &MyStates) const {
2665 // If any top-down local-use or possible-dec has a succ which is earlier in
2666 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002667 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002668 E = MyStates.top_down_ptr_end(); I != E; ++I)
2669 switch (I->second.GetSeq()) {
2670 default: break;
2671 case S_Use: {
2672 const Value *Arg = I->first;
2673 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2674 bool SomeSuccHasSame = false;
2675 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002676 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002677 succ_const_iterator SI(TI), SE(TI, false);
2678
2679 // If the terminator is an invoke marked with the
2680 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2681 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002682 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2683 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2684 "terminator marked with "
2685 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2686 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002687 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002688 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002689
2690 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002691 Sequence SuccSSeq = S_None;
2692 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002693 // If VisitBottomUp has pointer information for this successor, take
2694 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002695 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2696 BBStates.find(*SI);
2697 assert(BBI != BBStates.end());
2698 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2699 SuccSSeq = SuccS.GetSeq();
2700 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002701 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002702 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002703 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002704 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002705 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002706 break;
2707 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002708 continue;
2709 }
John McCall9fbd3182011-06-15 23:37:01 +00002710 case S_Use:
2711 SomeSuccHasSame = true;
2712 break;
2713 case S_Stop:
2714 case S_Release:
2715 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002716 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002717 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002718 break;
2719 case S_Retain:
2720 llvm_unreachable("bottom-up pointer in retain state!");
2721 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002722 }
John McCall9fbd3182011-06-15 23:37:01 +00002723 // If the state at the other end of any of the successor edges
2724 // matches the current state, require all edges to match. This
2725 // guards against loops in the middle of a sequence.
2726 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002727 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002728 break;
John McCall9fbd3182011-06-15 23:37:01 +00002729 }
2730 case S_CanRelease: {
2731 const Value *Arg = I->first;
2732 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2733 bool SomeSuccHasSame = false;
2734 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002735 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002736 succ_const_iterator SI(TI), SE(TI, false);
2737
2738 // If the terminator is an invoke marked with the
2739 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2740 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00002741 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2742 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2743 "terminator marked with "
2744 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2745 "edge.\n");
Dan Gohmandbe266b2012-02-17 18:59:53 +00002746 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00002747 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002748
2749 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002750 Sequence SuccSSeq = S_None;
2751 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002752 // If VisitBottomUp has pointer information for this successor, take
2753 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002754 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2755 BBStates.find(*SI);
2756 assert(BBI != BBStates.end());
2757 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2758 SuccSSeq = SuccS.GetSeq();
2759 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002760 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002761 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002762 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002763 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002764 break;
2765 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002766 continue;
2767 }
John McCall9fbd3182011-06-15 23:37:01 +00002768 case S_CanRelease:
2769 SomeSuccHasSame = true;
2770 break;
2771 case S_Stop:
2772 case S_Release:
2773 case S_MovableRelease:
2774 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002775 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002776 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002777 break;
2778 case S_Retain:
2779 llvm_unreachable("bottom-up pointer in retain state!");
2780 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002781 }
John McCall9fbd3182011-06-15 23:37:01 +00002782 // If the state at the other end of any of the successor edges
2783 // matches the current state, require all edges to match. This
2784 // guards against loops in the middle of a sequence.
2785 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002786 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002787 break;
John McCall9fbd3182011-06-15 23:37:01 +00002788 }
2789 }
2790}
2791
2792bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002793ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002794 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002795 MapVector<Value *, RRInfo> &Retains,
2796 BBState &MyStates) {
2797 bool NestingDetected = false;
2798 InstructionClass Class = GetInstructionClass(Inst);
2799 const Value *Arg = 0;
2800
2801 switch (Class) {
2802 case IC_Release: {
2803 Arg = GetObjCArg(Inst);
2804
2805 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2806
2807 // If we see two releases in a row on the same pointer. If so, make
2808 // a note, and we'll cicle back to revisit it after we've
2809 // hopefully eliminated the second release, which may allow us to
2810 // eliminate the first release too.
2811 // Theoretically we could implement removal of nested retain+release
2812 // pairs by making PtrState hold a stack of states, but this is
2813 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmancf140052013-01-13 07:00:51 +00002814 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2815 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2816 "releases (i.e. a release pair)\n");
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002817 NestingDetected = true;
Michael Gottesmancf140052013-01-13 07:00:51 +00002818 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002819
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002820 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002821 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002822 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002823 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002824 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2825 S.RRI.Calls.insert(Inst);
2826
Dan Gohman230768b2012-09-04 23:16:20 +00002827 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002828 break;
2829 }
2830 case IC_RetainBlock:
2831 // An objc_retainBlock call with just a use may need to be kept,
2832 // because it may be copying a block from the stack to the heap.
2833 if (!IsRetainBlockOptimizable(Inst))
2834 break;
2835 // FALLTHROUGH
2836 case IC_Retain:
2837 case IC_RetainRV: {
2838 Arg = GetObjCArg(Inst);
2839
2840 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002841 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002842
2843 switch (S.GetSeq()) {
2844 case S_Stop:
2845 case S_Release:
2846 case S_MovableRelease:
2847 case S_Use:
2848 S.RRI.ReverseInsertPts.clear();
2849 // FALL THROUGH
2850 case S_CanRelease:
2851 // Don't do retain+release tracking for IC_RetainRV, because it's
2852 // better to let it remain as the first instruction after a call.
2853 if (Class != IC_RetainRV) {
2854 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2855 Retains[Inst] = S.RRI;
2856 }
2857 S.ClearSequenceProgress();
2858 break;
2859 case S_None:
2860 break;
2861 case S_Retain:
2862 llvm_unreachable("bottom-up pointer in retain state!");
2863 }
2864 return NestingDetected;
2865 }
2866 case IC_AutoreleasepoolPop:
2867 // Conservatively, clear MyStates for all known pointers.
2868 MyStates.clearBottomUpPointers();
2869 return NestingDetected;
2870 case IC_AutoreleasepoolPush:
2871 case IC_None:
2872 // These are irrelevant.
2873 return NestingDetected;
2874 default:
2875 break;
2876 }
2877
2878 // Consider any other possible effects of this instruction on each
2879 // pointer being tracked.
2880 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2881 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2882 const Value *Ptr = MI->first;
2883 if (Ptr == Arg)
2884 continue; // Handled above.
2885 PtrState &S = MI->second;
2886 Sequence Seq = S.GetSeq();
2887
2888 // Check for possible releases.
2889 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002890 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002891 switch (Seq) {
2892 case S_Use:
2893 S.SetSeq(S_CanRelease);
2894 continue;
2895 case S_CanRelease:
2896 case S_Release:
2897 case S_MovableRelease:
2898 case S_Stop:
2899 case S_None:
2900 break;
2901 case S_Retain:
2902 llvm_unreachable("bottom-up pointer in retain state!");
2903 }
2904 }
2905
2906 // Check for possible direct uses.
2907 switch (Seq) {
2908 case S_Release:
2909 case S_MovableRelease:
2910 if (CanUse(Inst, Ptr, PA, Class)) {
2911 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002912 // If this is an invoke instruction, we're scanning it as part of
2913 // one of its successor blocks, since we can't insert code after it
2914 // in its own block, and we don't want to split critical edges.
2915 if (isa<InvokeInst>(Inst))
2916 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2917 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002918 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002919 S.SetSeq(S_Use);
2920 } else if (Seq == S_Release &&
2921 (Class == IC_User || Class == IC_CallOrUser)) {
2922 // Non-movable releases depend on any possible objc pointer use.
2923 S.SetSeq(S_Stop);
2924 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002925 // As above; handle invoke specially.
2926 if (isa<InvokeInst>(Inst))
2927 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2928 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002929 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002930 }
2931 break;
2932 case S_Stop:
2933 if (CanUse(Inst, Ptr, PA, Class))
2934 S.SetSeq(S_Use);
2935 break;
2936 case S_CanRelease:
2937 case S_Use:
2938 case S_None:
2939 break;
2940 case S_Retain:
2941 llvm_unreachable("bottom-up pointer in retain state!");
2942 }
2943 }
2944
2945 return NestingDetected;
2946}
2947
2948bool
John McCall9fbd3182011-06-15 23:37:01 +00002949ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2950 DenseMap<const BasicBlock *, BBState> &BBStates,
2951 MapVector<Value *, RRInfo> &Retains) {
2952 bool NestingDetected = false;
2953 BBState &MyStates = BBStates[BB];
2954
2955 // Merge the states from each successor to compute the initial state
2956 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002957 BBState::edge_iterator SI(MyStates.succ_begin()),
2958 SE(MyStates.succ_end());
2959 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002960 const BasicBlock *Succ = *SI;
2961 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2962 assert(I != BBStates.end());
2963 MyStates.InitFromSucc(I->second);
2964 ++SI;
2965 for (; SI != SE; ++SI) {
2966 Succ = *SI;
2967 I = BBStates.find(Succ);
2968 assert(I != BBStates.end());
2969 MyStates.MergeSucc(I->second);
2970 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002971 }
John McCall9fbd3182011-06-15 23:37:01 +00002972
2973 // Visit all the instructions, bottom-up.
2974 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2975 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002976
2977 // Invoke instructions are visited as part of their successors (below).
2978 if (isa<InvokeInst>(Inst))
2979 continue;
2980
Michael Gottesmancf140052013-01-13 07:00:51 +00002981 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2982
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002983 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2984 }
2985
Dan Gohman447989c2012-04-27 18:56:31 +00002986 // If there's a predecessor with an invoke, visit the invoke as if it were
2987 // part of this block, since we can't insert code after an invoke in its own
2988 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002989 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2990 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002991 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002992 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2993 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002994 }
John McCall9fbd3182011-06-15 23:37:01 +00002995
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002996 return NestingDetected;
2997}
John McCall9fbd3182011-06-15 23:37:01 +00002998
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002999bool
3000ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3001 DenseMap<Value *, RRInfo> &Releases,
3002 BBState &MyStates) {
3003 bool NestingDetected = false;
3004 InstructionClass Class = GetInstructionClass(Inst);
3005 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003006
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003007 switch (Class) {
3008 case IC_RetainBlock:
3009 // An objc_retainBlock call with just a use may need to be kept,
3010 // because it may be copying a block from the stack to the heap.
3011 if (!IsRetainBlockOptimizable(Inst))
3012 break;
3013 // FALLTHROUGH
3014 case IC_Retain:
3015 case IC_RetainRV: {
3016 Arg = GetObjCArg(Inst);
3017
3018 PtrState &S = MyStates.getPtrTopDownState(Arg);
3019
3020 // Don't do retain+release tracking for IC_RetainRV, because it's
3021 // better to let it remain as the first instruction after a call.
3022 if (Class != IC_RetainRV) {
3023 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00003024 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003025 // hopefully eliminated the second retain, which may allow us to
3026 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00003027 // Theoretically we could implement removal of nested retain+release
3028 // pairs by making PtrState hold a stack of states, but this is
3029 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003030 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00003031 NestingDetected = true;
3032
Dan Gohman50ade652012-04-25 00:50:46 +00003033 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003034 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00003035 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00003036 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00003037 }
John McCall9fbd3182011-06-15 23:37:01 +00003038
Dan Gohman230768b2012-09-04 23:16:20 +00003039 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00003040
3041 // A retain can be a potential use; procede to the generic checking
3042 // code below.
3043 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003044 }
3045 case IC_Release: {
3046 Arg = GetObjCArg(Inst);
3047
3048 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00003049 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003050
3051 switch (S.GetSeq()) {
3052 case S_Retain:
3053 case S_CanRelease:
3054 S.RRI.ReverseInsertPts.clear();
3055 // FALL THROUGH
3056 case S_Use:
3057 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3058 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3059 Releases[Inst] = S.RRI;
3060 S.ClearSequenceProgress();
3061 break;
3062 case S_None:
3063 break;
3064 case S_Stop:
3065 case S_Release:
3066 case S_MovableRelease:
3067 llvm_unreachable("top-down pointer in release state!");
3068 }
3069 break;
3070 }
3071 case IC_AutoreleasepoolPop:
3072 // Conservatively, clear MyStates for all known pointers.
3073 MyStates.clearTopDownPointers();
3074 return NestingDetected;
3075 case IC_AutoreleasepoolPush:
3076 case IC_None:
3077 // These are irrelevant.
3078 return NestingDetected;
3079 default:
3080 break;
3081 }
3082
3083 // Consider any other possible effects of this instruction on each
3084 // pointer being tracked.
3085 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3086 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3087 const Value *Ptr = MI->first;
3088 if (Ptr == Arg)
3089 continue; // Handled above.
3090 PtrState &S = MI->second;
3091 Sequence Seq = S.GetSeq();
3092
3093 // Check for possible releases.
3094 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00003095 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00003096 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003097 case S_Retain:
3098 S.SetSeq(S_CanRelease);
3099 assert(S.RRI.ReverseInsertPts.empty());
3100 S.RRI.ReverseInsertPts.insert(Inst);
3101
3102 // One call can't cause a transition from S_Retain to S_CanRelease
3103 // and S_CanRelease to S_Use. If we've made the first transition,
3104 // we're done.
3105 continue;
John McCall9fbd3182011-06-15 23:37:01 +00003106 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003107 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00003108 case S_None:
3109 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003110 case S_Stop:
3111 case S_Release:
3112 case S_MovableRelease:
3113 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00003114 }
3115 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003116
3117 // Check for possible direct uses.
3118 switch (Seq) {
3119 case S_CanRelease:
3120 if (CanUse(Inst, Ptr, PA, Class))
3121 S.SetSeq(S_Use);
3122 break;
3123 case S_Retain:
3124 case S_Use:
3125 case S_None:
3126 break;
3127 case S_Stop:
3128 case S_Release:
3129 case S_MovableRelease:
3130 llvm_unreachable("top-down pointer in release state!");
3131 }
John McCall9fbd3182011-06-15 23:37:01 +00003132 }
3133
3134 return NestingDetected;
3135}
3136
3137bool
3138ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3139 DenseMap<const BasicBlock *, BBState> &BBStates,
3140 DenseMap<Value *, RRInfo> &Releases) {
3141 bool NestingDetected = false;
3142 BBState &MyStates = BBStates[BB];
3143
3144 // Merge the states from each predecessor to compute the initial state
3145 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00003146 BBState::edge_iterator PI(MyStates.pred_begin()),
3147 PE(MyStates.pred_end());
3148 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003149 const BasicBlock *Pred = *PI;
3150 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3151 assert(I != BBStates.end());
3152 MyStates.InitFromPred(I->second);
3153 ++PI;
3154 for (; PI != PE; ++PI) {
3155 Pred = *PI;
3156 I = BBStates.find(Pred);
3157 assert(I != BBStates.end());
3158 MyStates.MergePred(I->second);
3159 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003160 }
John McCall9fbd3182011-06-15 23:37:01 +00003161
3162 // Visit all the instructions, top-down.
3163 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3164 Instruction *Inst = I;
Michael Gottesmancf140052013-01-13 07:00:51 +00003165
3166 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3167
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00003168 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00003169 }
3170
3171 CheckForCFGHazards(BB, BBStates, MyStates);
3172 return NestingDetected;
3173}
3174
Dan Gohman59a1c932011-12-12 19:42:25 +00003175static void
3176ComputePostOrders(Function &F,
3177 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003178 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3179 unsigned NoObjCARCExceptionsMDKind,
3180 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman81c61212013-01-14 00:35:14 +00003181 /// The visited set, for doing DFS walks.
Dan Gohman59a1c932011-12-12 19:42:25 +00003182 SmallPtrSet<BasicBlock *, 16> Visited;
3183
3184 // Do DFS, computing the PostOrder.
3185 SmallPtrSet<BasicBlock *, 16> OnStack;
3186 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003187
3188 // Functions always have exactly one entry block, and we don't have
3189 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003190 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003191 BBState &MyStates = BBStates[EntryBB];
3192 MyStates.SetAsEntry();
3193 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3194 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003195 Visited.insert(EntryBB);
3196 OnStack.insert(EntryBB);
3197 do {
3198 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003199 BasicBlock *CurrBB = SuccStack.back().first;
3200 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3201 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003202
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003203 // If the terminator is an invoke marked with the
3204 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3205 // ignored, for ARC purposes.
Michael Gottesmancf140052013-01-13 07:00:51 +00003206 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3207 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3208 "terminator marked with "
3209 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3210 "edge.\n");
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003211 --SE;
Michael Gottesmancf140052013-01-13 07:00:51 +00003212 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003213
3214 while (SuccStack.back().second != SE) {
3215 BasicBlock *SuccBB = *SuccStack.back().second++;
3216 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003217 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3218 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003219 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003220 BBState &SuccStates = BBStates[SuccBB];
3221 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003222 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003223 goto dfs_next_succ;
3224 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003225
3226 if (!OnStack.count(SuccBB)) {
3227 BBStates[CurrBB].addSucc(SuccBB);
3228 BBStates[SuccBB].addPred(CurrBB);
3229 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003230 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003231 OnStack.erase(CurrBB);
3232 PostOrder.push_back(CurrBB);
3233 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003234 } while (!SuccStack.empty());
3235
3236 Visited.clear();
3237
Dan Gohman59a1c932011-12-12 19:42:25 +00003238 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003239 // Functions may have many exits, and there also blocks which we treat
3240 // as exits due to ignored edges.
3241 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3242 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3243 BasicBlock *ExitBB = I;
3244 BBState &MyStates = BBStates[ExitBB];
3245 if (!MyStates.isExit())
3246 continue;
3247
Dan Gohman447989c2012-04-27 18:56:31 +00003248 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003249
3250 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003251 Visited.insert(ExitBB);
3252 while (!PredStack.empty()) {
3253 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003254 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3255 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003256 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003257 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003258 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003259 goto reverse_dfs_next_succ;
3260 }
3261 }
3262 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3263 }
3264 }
3265}
3266
Michael Gottesman81c61212013-01-14 00:35:14 +00003267// Visit the function both top-down and bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003268bool
3269ObjCARCOpt::Visit(Function &F,
3270 DenseMap<const BasicBlock *, BBState> &BBStates,
3271 MapVector<Value *, RRInfo> &Retains,
3272 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003273
3274 // Use reverse-postorder traversals, because we magically know that loops
3275 // will be well behaved, i.e. they won't repeatedly call retain on a single
3276 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3277 // class here because we want the reverse-CFG postorder to consider each
3278 // function exit point, and we want to ignore selected cycle edges.
3279 SmallVector<BasicBlock *, 16> PostOrder;
3280 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003281 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3282 NoObjCARCExceptionsMDKind,
3283 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003284
3285 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003286 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003287 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003288 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3289 I != E; ++I)
3290 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003291
Dan Gohman59a1c932011-12-12 19:42:25 +00003292 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003293 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003294 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3295 PostOrder.rbegin(), E = PostOrder.rend();
3296 I != E; ++I)
3297 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003298
3299 return TopDownNestingDetected && BottomUpNestingDetected;
3300}
3301
Michael Gottesman81c61212013-01-14 00:35:14 +00003302/// Move the calls in RetainsToMove and ReleasesToMove.
John McCall9fbd3182011-06-15 23:37:01 +00003303void ObjCARCOpt::MoveCalls(Value *Arg,
3304 RRInfo &RetainsToMove,
3305 RRInfo &ReleasesToMove,
3306 MapVector<Value *, RRInfo> &Retains,
3307 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003308 SmallVectorImpl<Instruction *> &DeadInsts,
3309 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003310 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003311 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003312
3313 // Insert the new retain and release calls.
3314 for (SmallPtrSet<Instruction *, 2>::const_iterator
3315 PI = ReleasesToMove.ReverseInsertPts.begin(),
3316 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3317 Instruction *InsertPt = *PI;
3318 Value *MyArg = ArgTy == ParamTy ? Arg :
3319 new BitCastInst(Arg, ParamTy, "", InsertPt);
3320 CallInst *Call =
3321 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003322 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003323 MyArg, "", InsertPt);
3324 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003325 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003326 Call->setMetadata(CopyOnEscapeMDKind,
3327 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003328 else
John McCall9fbd3182011-06-15 23:37:01 +00003329 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003330
3331 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3332 << "\n"
3333 " At insertion point: " << *InsertPt
3334 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003335 }
3336 for (SmallPtrSet<Instruction *, 2>::const_iterator
3337 PI = RetainsToMove.ReverseInsertPts.begin(),
3338 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003339 Instruction *InsertPt = *PI;
3340 Value *MyArg = ArgTy == ParamTy ? Arg :
3341 new BitCastInst(Arg, ParamTy, "", InsertPt);
3342 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3343 "", InsertPt);
3344 // Attach a clang.imprecise_release metadata tag, if appropriate.
3345 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3346 Call->setMetadata(ImpreciseReleaseMDKind, M);
3347 Call->setDoesNotThrow();
3348 if (ReleasesToMove.IsTailCallRelease)
3349 Call->setTailCall();
Michael Gottesman55811152013-01-09 19:23:24 +00003350
3351 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3352 << "\n"
3353 " At insertion point: " << *InsertPt
3354 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003355 }
3356
3357 // Delete the original retain and release calls.
3358 for (SmallPtrSet<Instruction *, 2>::const_iterator
3359 AI = RetainsToMove.Calls.begin(),
3360 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3361 Instruction *OrigRetain = *AI;
3362 Retains.blot(OrigRetain);
3363 DeadInsts.push_back(OrigRetain);
Michael Gottesman55811152013-01-09 19:23:24 +00003364 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3365 "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003366 }
3367 for (SmallPtrSet<Instruction *, 2>::const_iterator
3368 AI = ReleasesToMove.Calls.begin(),
3369 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3370 Instruction *OrigRelease = *AI;
3371 Releases.erase(OrigRelease);
3372 DeadInsts.push_back(OrigRelease);
Michael Gottesman55811152013-01-09 19:23:24 +00003373 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3374 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003375 }
3376}
3377
Michael Gottesman81c61212013-01-14 00:35:14 +00003378/// Identify pairings between the retains and releases, and delete and/or move
3379/// them.
John McCall9fbd3182011-06-15 23:37:01 +00003380bool
3381ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3382 &BBStates,
3383 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003384 DenseMap<Value *, RRInfo> &Releases,
3385 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003386 bool AnyPairsCompletelyEliminated = false;
3387 RRInfo RetainsToMove;
3388 RRInfo ReleasesToMove;
3389 SmallVector<Instruction *, 4> NewRetains;
3390 SmallVector<Instruction *, 4> NewReleases;
3391 SmallVector<Instruction *, 8> DeadInsts;
3392
Dan Gohmand6bf2012012-04-13 18:57:48 +00003393 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003394 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003395 E = Retains.end(); I != E; ++I) {
3396 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003397 if (!V) continue; // blotted
3398
3399 Instruction *Retain = cast<Instruction>(V);
Michael Gottesman55811152013-01-09 19:23:24 +00003400
3401 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3402 << "\n");
3403
John McCall9fbd3182011-06-15 23:37:01 +00003404 Value *Arg = GetObjCArg(Retain);
3405
Dan Gohman79522dc2012-01-13 00:39:07 +00003406 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003407 // not being managed by ObjC reference counting, so we can delete pairs
3408 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003409 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003410
Dan Gohman1b31ea82011-08-22 17:29:11 +00003411 // A constant pointer can't be pointing to an object on the heap. It may
3412 // be reference-counted, but it won't be deleted.
3413 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3414 if (const GlobalVariable *GV =
3415 dyn_cast<GlobalVariable>(
3416 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3417 if (GV->isConstant())
3418 KnownSafe = true;
3419
John McCall9fbd3182011-06-15 23:37:01 +00003420 // If a pair happens in a region where it is known that the reference count
3421 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003422 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003423
3424 // Connect the dots between the top-down-collected RetainsToMove and
3425 // bottom-up-collected ReleasesToMove to form sets of related calls.
3426 // This is an iterative process so that we connect multiple releases
3427 // to multiple retains if needed.
3428 unsigned OldDelta = 0;
3429 unsigned NewDelta = 0;
3430 unsigned OldCount = 0;
3431 unsigned NewCount = 0;
3432 bool FirstRelease = true;
3433 bool FirstRetain = true;
3434 NewRetains.push_back(Retain);
3435 for (;;) {
3436 for (SmallVectorImpl<Instruction *>::const_iterator
3437 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3438 Instruction *NewRetain = *NI;
3439 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3440 assert(It != Retains.end());
3441 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003442 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003443 for (SmallPtrSet<Instruction *, 2>::const_iterator
3444 LI = NewRetainRRI.Calls.begin(),
3445 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3446 Instruction *NewRetainRelease = *LI;
3447 DenseMap<Value *, RRInfo>::const_iterator Jt =
3448 Releases.find(NewRetainRelease);
3449 if (Jt == Releases.end())
3450 goto next_retain;
3451 const RRInfo &NewRetainReleaseRRI = Jt->second;
3452 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3453 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3454 OldDelta -=
3455 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3456
3457 // Merge the ReleaseMetadata and IsTailCallRelease values.
3458 if (FirstRelease) {
3459 ReleasesToMove.ReleaseMetadata =
3460 NewRetainReleaseRRI.ReleaseMetadata;
3461 ReleasesToMove.IsTailCallRelease =
3462 NewRetainReleaseRRI.IsTailCallRelease;
3463 FirstRelease = false;
3464 } else {
3465 if (ReleasesToMove.ReleaseMetadata !=
3466 NewRetainReleaseRRI.ReleaseMetadata)
3467 ReleasesToMove.ReleaseMetadata = 0;
3468 if (ReleasesToMove.IsTailCallRelease !=
3469 NewRetainReleaseRRI.IsTailCallRelease)
3470 ReleasesToMove.IsTailCallRelease = false;
3471 }
3472
3473 // Collect the optimal insertion points.
3474 if (!KnownSafe)
3475 for (SmallPtrSet<Instruction *, 2>::const_iterator
3476 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3477 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3478 RI != RE; ++RI) {
3479 Instruction *RIP = *RI;
3480 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3481 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3482 }
3483 NewReleases.push_back(NewRetainRelease);
3484 }
3485 }
3486 }
3487 NewRetains.clear();
3488 if (NewReleases.empty()) break;
3489
3490 // Back the other way.
3491 for (SmallVectorImpl<Instruction *>::const_iterator
3492 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3493 Instruction *NewRelease = *NI;
3494 DenseMap<Value *, RRInfo>::const_iterator It =
3495 Releases.find(NewRelease);
3496 assert(It != Releases.end());
3497 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003498 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003499 for (SmallPtrSet<Instruction *, 2>::const_iterator
3500 LI = NewReleaseRRI.Calls.begin(),
3501 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3502 Instruction *NewReleaseRetain = *LI;
3503 MapVector<Value *, RRInfo>::const_iterator Jt =
3504 Retains.find(NewReleaseRetain);
3505 if (Jt == Retains.end())
3506 goto next_retain;
3507 const RRInfo &NewReleaseRetainRRI = Jt->second;
3508 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3509 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3510 unsigned PathCount =
3511 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3512 OldDelta += PathCount;
3513 OldCount += PathCount;
3514
3515 // Merge the IsRetainBlock values.
3516 if (FirstRetain) {
3517 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3518 FirstRetain = false;
3519 } else if (ReleasesToMove.IsRetainBlock !=
3520 NewReleaseRetainRRI.IsRetainBlock)
3521 // It's not possible to merge the sequences if one uses
3522 // objc_retain and the other uses objc_retainBlock.
3523 goto next_retain;
3524
3525 // Collect the optimal insertion points.
3526 if (!KnownSafe)
3527 for (SmallPtrSet<Instruction *, 2>::const_iterator
3528 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3529 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3530 RI != RE; ++RI) {
3531 Instruction *RIP = *RI;
3532 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3533 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3534 NewDelta += PathCount;
3535 NewCount += PathCount;
3536 }
3537 }
3538 NewRetains.push_back(NewReleaseRetain);
3539 }
3540 }
3541 }
3542 NewReleases.clear();
3543 if (NewRetains.empty()) break;
3544 }
3545
Dan Gohmane6d5e882011-08-19 00:26:36 +00003546 // If the pointer is known incremented or nested, we can safely delete the
3547 // pair regardless of what's between them.
3548 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003549 RetainsToMove.ReverseInsertPts.clear();
3550 ReleasesToMove.ReverseInsertPts.clear();
3551 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003552 } else {
3553 // Determine whether the new insertion points we computed preserve the
3554 // balance of retain and release calls through the program.
3555 // TODO: If the fully aggressive solution isn't valid, try to find a
3556 // less aggressive solution which is.
3557 if (NewDelta != 0)
3558 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003559 }
3560
3561 // Determine whether the original call points are balanced in the retain and
3562 // release calls through the program. If not, conservatively don't touch
3563 // them.
3564 // TODO: It's theoretically possible to do code motion in this case, as
3565 // long as the existing imbalances are maintained.
3566 if (OldDelta != 0)
3567 goto next_retain;
3568
John McCall9fbd3182011-06-15 23:37:01 +00003569 // Ok, everything checks out and we're all set. Let's move some code!
3570 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003571 assert(OldCount != 0 && "Unreachable code?");
3572 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003573 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003574 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3575 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003576
3577 next_retain:
3578 NewReleases.clear();
3579 NewRetains.clear();
3580 RetainsToMove.clear();
3581 ReleasesToMove.clear();
3582 }
3583
3584 // Now that we're done moving everything, we can delete the newly dead
3585 // instructions, as we no longer need them as insert points.
3586 while (!DeadInsts.empty())
3587 EraseInstruction(DeadInsts.pop_back_val());
3588
3589 return AnyPairsCompletelyEliminated;
3590}
3591
Michael Gottesman81c61212013-01-14 00:35:14 +00003592/// Weak pointer optimizations.
John McCall9fbd3182011-06-15 23:37:01 +00003593void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3594 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3595 // itself because it uses AliasAnalysis and we need to do provenance
3596 // queries instead.
3597 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3598 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003599
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003600 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003601 "\n");
3602
John McCall9fbd3182011-06-15 23:37:01 +00003603 InstructionClass Class = GetBasicInstructionClass(Inst);
3604 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3605 continue;
3606
3607 // Delete objc_loadWeak calls with no users.
3608 if (Class == IC_LoadWeak && Inst->use_empty()) {
3609 Inst->eraseFromParent();
3610 continue;
3611 }
3612
3613 // TODO: For now, just look for an earlier available version of this value
3614 // within the same block. Theoretically, we could do memdep-style non-local
3615 // analysis too, but that would want caching. A better approach would be to
3616 // use the technique that EarlyCSE uses.
3617 inst_iterator Current = llvm::prior(I);
3618 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3619 for (BasicBlock::iterator B = CurrentBB->begin(),
3620 J = Current.getInstructionIterator();
3621 J != B; --J) {
3622 Instruction *EarlierInst = &*llvm::prior(J);
3623 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3624 switch (EarlierClass) {
3625 case IC_LoadWeak:
3626 case IC_LoadWeakRetained: {
3627 // If this is loading from the same pointer, replace this load's value
3628 // with that one.
3629 CallInst *Call = cast<CallInst>(Inst);
3630 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3631 Value *Arg = Call->getArgOperand(0);
3632 Value *EarlierArg = EarlierCall->getArgOperand(0);
3633 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3634 case AliasAnalysis::MustAlias:
3635 Changed = true;
3636 // If the load has a builtin retain, insert a plain retain for it.
3637 if (Class == IC_LoadWeakRetained) {
3638 CallInst *CI =
3639 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3640 "", Call);
3641 CI->setTailCall();
3642 }
3643 // Zap the fully redundant load.
3644 Call->replaceAllUsesWith(EarlierCall);
3645 Call->eraseFromParent();
3646 goto clobbered;
3647 case AliasAnalysis::MayAlias:
3648 case AliasAnalysis::PartialAlias:
3649 goto clobbered;
3650 case AliasAnalysis::NoAlias:
3651 break;
3652 }
3653 break;
3654 }
3655 case IC_StoreWeak:
3656 case IC_InitWeak: {
3657 // If this is storing to the same pointer and has the same size etc.
3658 // replace this load's value with the stored value.
3659 CallInst *Call = cast<CallInst>(Inst);
3660 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3661 Value *Arg = Call->getArgOperand(0);
3662 Value *EarlierArg = EarlierCall->getArgOperand(0);
3663 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3664 case AliasAnalysis::MustAlias:
3665 Changed = true;
3666 // If the load has a builtin retain, insert a plain retain for it.
3667 if (Class == IC_LoadWeakRetained) {
3668 CallInst *CI =
3669 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3670 "", Call);
3671 CI->setTailCall();
3672 }
3673 // Zap the fully redundant load.
3674 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3675 Call->eraseFromParent();
3676 goto clobbered;
3677 case AliasAnalysis::MayAlias:
3678 case AliasAnalysis::PartialAlias:
3679 goto clobbered;
3680 case AliasAnalysis::NoAlias:
3681 break;
3682 }
3683 break;
3684 }
3685 case IC_MoveWeak:
3686 case IC_CopyWeak:
3687 // TOOD: Grab the copied value.
3688 goto clobbered;
3689 case IC_AutoreleasepoolPush:
3690 case IC_None:
3691 case IC_User:
3692 // Weak pointers are only modified through the weak entry points
3693 // (and arbitrary calls, which could call the weak entry points).
3694 break;
3695 default:
3696 // Anything else could modify the weak pointer.
3697 goto clobbered;
3698 }
3699 }
3700 clobbered:;
3701 }
3702
3703 // Then, for each destroyWeak with an alloca operand, check to see if
3704 // the alloca and all its users can be zapped.
3705 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3706 Instruction *Inst = &*I++;
3707 InstructionClass Class = GetBasicInstructionClass(Inst);
3708 if (Class != IC_DestroyWeak)
3709 continue;
3710
3711 CallInst *Call = cast<CallInst>(Inst);
3712 Value *Arg = Call->getArgOperand(0);
3713 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3714 for (Value::use_iterator UI = Alloca->use_begin(),
3715 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003716 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003717 switch (GetBasicInstructionClass(UserInst)) {
3718 case IC_InitWeak:
3719 case IC_StoreWeak:
3720 case IC_DestroyWeak:
3721 continue;
3722 default:
3723 goto done;
3724 }
3725 }
3726 Changed = true;
3727 for (Value::use_iterator UI = Alloca->use_begin(),
3728 UE = Alloca->use_end(); UI != UE; ) {
3729 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003730 switch (GetBasicInstructionClass(UserInst)) {
3731 case IC_InitWeak:
3732 case IC_StoreWeak:
3733 // These functions return their second argument.
3734 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3735 break;
3736 case IC_DestroyWeak:
3737 // No return value.
3738 break;
3739 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003740 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003741 }
John McCall9fbd3182011-06-15 23:37:01 +00003742 UserInst->eraseFromParent();
3743 }
3744 Alloca->eraseFromParent();
3745 done:;
3746 }
3747 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003748
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003749 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003750
John McCall9fbd3182011-06-15 23:37:01 +00003751}
3752
Michael Gottesman81c61212013-01-14 00:35:14 +00003753/// Identify program paths which execute sequences of retains and releases which
3754/// can be eliminated.
John McCall9fbd3182011-06-15 23:37:01 +00003755bool ObjCARCOpt::OptimizeSequences(Function &F) {
3756 /// Releases, Retains - These are used to store the results of the main flow
3757 /// analysis. These use Value* as the key instead of Instruction* so that the
3758 /// map stays valid when we get around to rewriting code and calls get
3759 /// replaced by arguments.
3760 DenseMap<Value *, RRInfo> Releases;
3761 MapVector<Value *, RRInfo> Retains;
3762
Michael Gottesman81c61212013-01-14 00:35:14 +00003763 /// This is used during the traversal of the function to track the
John McCall9fbd3182011-06-15 23:37:01 +00003764 /// states for each identified object at each block.
3765 DenseMap<const BasicBlock *, BBState> BBStates;
3766
3767 // Analyze the CFG of the function, and all instructions.
3768 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3769
3770 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003771 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3772 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003773}
3774
Michael Gottesman81c61212013-01-14 00:35:14 +00003775/// Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003776/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003777/// %call = call i8* @something(...)
3778/// %2 = call i8* @objc_retain(i8* %call)
3779/// %3 = call i8* @objc_autorelease(i8* %2)
3780/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003781/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003782/// And delete the retain and autorelease.
3783///
3784/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003785/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003786/// %3 = call i8* @objc_autorelease(i8* %2)
3787/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003788/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003789/// convert the autorelease to autoreleaseRV.
3790void ObjCARCOpt::OptimizeReturns(Function &F) {
3791 if (!F.getReturnType()->isPointerTy())
3792 return;
3793
3794 SmallPtrSet<Instruction *, 4> DependingInstructions;
3795 SmallPtrSet<const BasicBlock *, 4> Visited;
3796 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3797 BasicBlock *BB = FI;
3798 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003799
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003800 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003801
John McCall9fbd3182011-06-15 23:37:01 +00003802 if (!Ret) continue;
3803
3804 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3805 FindDependencies(NeedsPositiveRetainCount, Arg,
3806 BB, Ret, DependingInstructions, Visited, PA);
3807 if (DependingInstructions.size() != 1)
3808 goto next_block;
3809
3810 {
3811 CallInst *Autorelease =
3812 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3813 if (!Autorelease)
3814 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003815 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003816 if (!IsAutorelease(AutoreleaseClass))
3817 goto next_block;
3818 if (GetObjCArg(Autorelease) != Arg)
3819 goto next_block;
3820
3821 DependingInstructions.clear();
3822 Visited.clear();
3823
3824 // Check that there is nothing that can affect the reference
3825 // count between the autorelease and the retain.
3826 FindDependencies(CanChangeRetainCount, Arg,
3827 BB, Autorelease, DependingInstructions, Visited, PA);
3828 if (DependingInstructions.size() != 1)
3829 goto next_block;
3830
3831 {
3832 CallInst *Retain =
3833 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3834
3835 // Check that we found a retain with the same argument.
3836 if (!Retain ||
3837 !IsRetain(GetBasicInstructionClass(Retain)) ||
3838 GetObjCArg(Retain) != Arg)
3839 goto next_block;
3840
3841 DependingInstructions.clear();
3842 Visited.clear();
3843
3844 // Convert the autorelease to an autoreleaseRV, since it's
3845 // returning the value.
3846 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesman5dc30012013-01-10 02:03:50 +00003847 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3848 "=> autoreleaseRV since it's returning a value.\n"
3849 " In: " << *Autorelease
3850 << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003851 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesman5dc30012013-01-10 02:03:50 +00003852 DEBUG(dbgs() << " Out: " << *Autorelease
3853 << "\n");
Michael Gottesmane8c161a2013-01-12 01:25:15 +00003854 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCall9fbd3182011-06-15 23:37:01 +00003855 AutoreleaseClass = IC_AutoreleaseRV;
3856 }
3857
3858 // Check that there is nothing that can affect the reference
3859 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003860 // Note that Retain need not be in BB.
3861 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003862 DependingInstructions, Visited, PA);
3863 if (DependingInstructions.size() != 1)
3864 goto next_block;
3865
3866 {
3867 CallInst *Call =
3868 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3869
3870 // Check that the pointer is the return value of the call.
3871 if (!Call || Arg != Call)
3872 goto next_block;
3873
3874 // Check that the call is a regular call.
3875 InstructionClass Class = GetBasicInstructionClass(Call);
3876 if (Class != IC_CallOrUser && Class != IC_Call)
3877 goto next_block;
3878
3879 // If so, we can zap the retain and autorelease.
3880 Changed = true;
3881 ++NumRets;
Michael Gottesmanf93109a2013-01-07 00:04:56 +00003882 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3883 << "\n Erasing: "
3884 << *Autorelease << "\n");
John McCall9fbd3182011-06-15 23:37:01 +00003885 EraseInstruction(Retain);
3886 EraseInstruction(Autorelease);
3887 }
3888 }
3889 }
3890
3891 next_block:
3892 DependingInstructions.clear();
3893 Visited.clear();
3894 }
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003895
Michael Gottesman5c0ae472013-01-04 21:29:57 +00003896 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00003897
John McCall9fbd3182011-06-15 23:37:01 +00003898}
3899
3900bool ObjCARCOpt::doInitialization(Module &M) {
3901 if (!EnableARCOpts)
3902 return false;
3903
Dan Gohmand6bf2012012-04-13 18:57:48 +00003904 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003905 Run = ModuleHasARC(M);
3906 if (!Run)
3907 return false;
3908
John McCall9fbd3182011-06-15 23:37:01 +00003909 // Identify the imprecise release metadata kind.
3910 ImpreciseReleaseMDKind =
3911 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003912 CopyOnEscapeMDKind =
3913 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003914 NoObjCARCExceptionsMDKind =
3915 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003916
John McCall9fbd3182011-06-15 23:37:01 +00003917 // Intuitively, objc_retain and others are nocapture, however in practice
3918 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003919 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003920
3921 // These are initialized lazily.
3922 RetainRVCallee = 0;
3923 AutoreleaseRVCallee = 0;
3924 ReleaseCallee = 0;
3925 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003926 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003927 AutoreleaseCallee = 0;
3928
3929 return false;
3930}
3931
3932bool ObjCARCOpt::runOnFunction(Function &F) {
3933 if (!EnableARCOpts)
3934 return false;
3935
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003936 // If nothing in the Module uses ARC, don't do anything.
3937 if (!Run)
3938 return false;
3939
John McCall9fbd3182011-06-15 23:37:01 +00003940 Changed = false;
3941
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003942 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3943
John McCall9fbd3182011-06-15 23:37:01 +00003944 PA.setAA(&getAnalysis<AliasAnalysis>());
3945
3946 // This pass performs several distinct transformations. As a compile-time aid
3947 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3948 // library functions aren't declared.
3949
3950 // Preliminary optimizations. This also computs UsedInThisFunction.
3951 OptimizeIndividualCalls(F);
3952
3953 // Optimizations for weak pointers.
3954 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3955 (1 << IC_LoadWeakRetained) |
3956 (1 << IC_StoreWeak) |
3957 (1 << IC_InitWeak) |
3958 (1 << IC_CopyWeak) |
3959 (1 << IC_MoveWeak) |
3960 (1 << IC_DestroyWeak)))
3961 OptimizeWeakCalls(F);
3962
3963 // Optimizations for retain+release pairs.
3964 if (UsedInThisFunction & ((1 << IC_Retain) |
3965 (1 << IC_RetainRV) |
3966 (1 << IC_RetainBlock)))
3967 if (UsedInThisFunction & (1 << IC_Release))
3968 // Run OptimizeSequences until it either stops making changes or
3969 // no retain+release pair nesting is detected.
3970 while (OptimizeSequences(F)) {}
3971
3972 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003973 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3974 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003975 OptimizeReturns(F);
3976
Michael Gottesman0d3582b2013-01-12 02:57:16 +00003977 DEBUG(dbgs() << "\n");
3978
John McCall9fbd3182011-06-15 23:37:01 +00003979 return Changed;
3980}
3981
3982void ObjCARCOpt::releaseMemory() {
3983 PA.clear();
3984}
3985
Michael Gottesman81c61212013-01-14 00:35:14 +00003986/// @}
3987///
3988/// \defgroup ARCContract ARC Contraction.
3989/// @{
John McCall9fbd3182011-06-15 23:37:01 +00003990
3991// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3992// dominated by single calls.
3993
John McCall9fbd3182011-06-15 23:37:01 +00003994#include "llvm/Analysis/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +00003995#include "llvm/IR/InlineAsm.h"
3996#include "llvm/IR/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003997
3998STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3999
4000namespace {
Michael Gottesman81c61212013-01-14 00:35:14 +00004001 /// \brief Late ARC optimizations
4002 ///
4003 /// These change the IR in a way that makes it difficult to be analyzed by
4004 /// ObjCARCOpt, so it's run late.
John McCall9fbd3182011-06-15 23:37:01 +00004005 class ObjCARCContract : public FunctionPass {
4006 bool Changed;
4007 AliasAnalysis *AA;
4008 DominatorTree *DT;
4009 ProvenanceAnalysis PA;
4010
Michael Gottesman81c61212013-01-14 00:35:14 +00004011 /// A flag indicating whether this optimization pass should run.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004012 bool Run;
4013
Michael Gottesman81c61212013-01-14 00:35:14 +00004014 /// Declarations for ObjC runtime functions, for use in creating calls to
4015 /// them. These are initialized lazily to avoid cluttering up the Module
4016 /// with unused declarations.
John McCall9fbd3182011-06-15 23:37:01 +00004017
Michael Gottesman81c61212013-01-14 00:35:14 +00004018 /// Declaration for objc_storeStrong().
4019 Constant *StoreStrongCallee;
4020 /// Declaration for objc_retainAutorelease().
4021 Constant *RetainAutoreleaseCallee;
4022 /// Declaration for objc_retainAutoreleaseReturnValue().
4023 Constant *RetainAutoreleaseRVCallee;
4024
4025 /// The inline asm string to insert between calls and RetainRV calls to make
4026 /// the optimization work on targets which need it.
John McCall9fbd3182011-06-15 23:37:01 +00004027 const MDString *RetainRVMarker;
4028
Michael Gottesman81c61212013-01-14 00:35:14 +00004029 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4030 /// function we have found no alloca instructions, these calls can be marked
4031 /// "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00004032 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00004033
John McCall9fbd3182011-06-15 23:37:01 +00004034 Constant *getStoreStrongCallee(Module *M);
4035 Constant *getRetainAutoreleaseCallee(Module *M);
4036 Constant *getRetainAutoreleaseRVCallee(Module *M);
4037
4038 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4039 InstructionClass Class,
4040 SmallPtrSet<Instruction *, 4>
4041 &DependingInstructions,
4042 SmallPtrSet<const BasicBlock *, 4>
4043 &Visited);
4044
4045 void ContractRelease(Instruction *Release,
4046 inst_iterator &Iter);
4047
4048 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4049 virtual bool doInitialization(Module &M);
4050 virtual bool runOnFunction(Function &F);
4051
4052 public:
4053 static char ID;
4054 ObjCARCContract() : FunctionPass(ID) {
4055 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4056 }
4057 };
4058}
4059
4060char ObjCARCContract::ID = 0;
4061INITIALIZE_PASS_BEGIN(ObjCARCContract,
4062 "objc-arc-contract", "ObjC ARC contraction", false, false)
4063INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4064INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4065INITIALIZE_PASS_END(ObjCARCContract,
4066 "objc-arc-contract", "ObjC ARC contraction", false, false)
4067
4068Pass *llvm::createObjCARCContractPass() {
4069 return new ObjCARCContract();
4070}
4071
4072void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4073 AU.addRequired<AliasAnalysis>();
4074 AU.addRequired<DominatorTree>();
4075 AU.setPreservesCFG();
4076}
4077
4078Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4079 if (!StoreStrongCallee) {
4080 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004081 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4082 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00004083 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00004084
Bill Wendling034b94b2012-12-19 07:18:57 +00004085 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00004086 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004087 Attribute::get(C, Attribute::NoUnwind))
4088 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00004089
4090 StoreStrongCallee =
4091 M->getOrInsertFunction(
4092 "objc_storeStrong",
4093 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00004094 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004095 }
4096 return StoreStrongCallee;
4097}
4098
4099Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4100 if (!RetainAutoreleaseCallee) {
4101 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004102 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004103 Type *Params[] = { I8X };
4104 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004105 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004106 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004107 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004108 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00004109 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004110 }
4111 return RetainAutoreleaseCallee;
4112}
4113
4114Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4115 if (!RetainAutoreleaseRVCallee) {
4116 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00004117 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00004118 Type *Params[] = { I8X };
4119 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00004120 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00004121 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00004122 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00004123 RetainAutoreleaseRVCallee =
4124 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00004125 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00004126 }
4127 return RetainAutoreleaseRVCallee;
4128}
4129
Michael Gottesman81c61212013-01-14 00:35:14 +00004130/// Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00004131bool
4132ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4133 InstructionClass Class,
4134 SmallPtrSet<Instruction *, 4>
4135 &DependingInstructions,
4136 SmallPtrSet<const BasicBlock *, 4>
4137 &Visited) {
4138 const Value *Arg = GetObjCArg(Autorelease);
4139
4140 // Check that there are no instructions between the retain and the autorelease
4141 // (such as an autorelease_pop) which may change the count.
4142 CallInst *Retain = 0;
4143 if (Class == IC_AutoreleaseRV)
4144 FindDependencies(RetainAutoreleaseRVDep, Arg,
4145 Autorelease->getParent(), Autorelease,
4146 DependingInstructions, Visited, PA);
4147 else
4148 FindDependencies(RetainAutoreleaseDep, Arg,
4149 Autorelease->getParent(), Autorelease,
4150 DependingInstructions, Visited, PA);
4151
4152 Visited.clear();
4153 if (DependingInstructions.size() != 1) {
4154 DependingInstructions.clear();
4155 return false;
4156 }
4157
4158 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4159 DependingInstructions.clear();
4160
4161 if (!Retain ||
4162 GetBasicInstructionClass(Retain) != IC_Retain ||
4163 GetObjCArg(Retain) != Arg)
4164 return false;
4165
4166 Changed = true;
4167 ++NumPeeps;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004168
Michael Gottesman916d52a2013-01-07 00:31:26 +00004169 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4170 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4171 " Old Retain: "
4172 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004173
John McCall9fbd3182011-06-15 23:37:01 +00004174 if (Class == IC_AutoreleaseRV)
4175 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4176 else
4177 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004178
Michael Gottesman916d52a2013-01-07 00:31:26 +00004179 DEBUG(dbgs() << " New Retain: "
4180 << *Retain << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004181
John McCall9fbd3182011-06-15 23:37:01 +00004182 EraseInstruction(Autorelease);
4183 return true;
4184}
4185
Michael Gottesman81c61212013-01-14 00:35:14 +00004186/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4187/// an objc_storeStrong. This can be a little tricky because the instructions
4188/// don't always appear in order, and there may be unrelated intervening
4189/// instructions.
John McCall9fbd3182011-06-15 23:37:01 +00004190void ObjCARCContract::ContractRelease(Instruction *Release,
4191 inst_iterator &Iter) {
4192 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00004193 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00004194
4195 // For now, require everything to be in one basic block.
4196 BasicBlock *BB = Release->getParent();
4197 if (Load->getParent() != BB) return;
4198
Dan Gohman4670dac2012-05-08 23:34:08 +00004199 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00004200 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00004201 ++I;
4202 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00004203 StoreInst *Store = 0;
4204 bool SawRelease = false;
4205 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00004206 if (I == End)
4207 return;
4208
Dan Gohman4670dac2012-05-08 23:34:08 +00004209 Instruction *Inst = I;
4210 if (Inst == Release) {
4211 SawRelease = true;
4212 continue;
4213 }
4214
4215 InstructionClass Class = GetBasicInstructionClass(Inst);
4216
4217 // Unrelated retains are harmless.
4218 if (IsRetain(Class))
4219 continue;
4220
4221 if (Store) {
4222 // The store is the point where we're going to put the objc_storeStrong,
4223 // so make sure there are no uses after it.
4224 if (CanUse(Inst, Load, PA, Class))
4225 return;
4226 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4227 // We are moving the load down to the store, so check for anything
4228 // else which writes to the memory between the load and the store.
4229 Store = dyn_cast<StoreInst>(Inst);
4230 if (!Store || !Store->isSimple()) return;
4231 if (Store->getPointerOperand() != Loc.Ptr) return;
4232 }
4233 }
John McCall9fbd3182011-06-15 23:37:01 +00004234
4235 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4236
4237 // Walk up to find the retain.
4238 I = Store;
4239 BasicBlock::iterator Begin = BB->begin();
4240 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4241 --I;
4242 Instruction *Retain = I;
4243 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4244 if (GetObjCArg(Retain) != New) return;
4245
4246 Changed = true;
4247 ++NumStoreStrongs;
4248
4249 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004250 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4251 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004252
4253 Value *Args[] = { Load->getPointerOperand(), New };
4254 if (Args[0]->getType() != I8XX)
4255 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4256 if (Args[1]->getType() != I8X)
4257 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4258 CallInst *StoreStrong =
4259 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004260 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004261 StoreStrong->setDoesNotThrow();
4262 StoreStrong->setDebugLoc(Store->getDebugLoc());
4263
Dan Gohman0cdece42012-01-19 19:14:36 +00004264 // We can't set the tail flag yet, because we haven't yet determined
4265 // whether there are any escaping allocas. Remember this call, so that
4266 // we can set the tail flag once we know it's safe.
4267 StoreStrongCalls.insert(StoreStrong);
4268
John McCall9fbd3182011-06-15 23:37:01 +00004269 if (&*Iter == Store) ++Iter;
4270 Store->eraseFromParent();
4271 Release->eraseFromParent();
4272 EraseInstruction(Retain);
4273 if (Load->use_empty())
4274 Load->eraseFromParent();
4275}
4276
4277bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004278 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004279 Run = ModuleHasARC(M);
4280 if (!Run)
4281 return false;
4282
John McCall9fbd3182011-06-15 23:37:01 +00004283 // These are initialized lazily.
4284 StoreStrongCallee = 0;
4285 RetainAutoreleaseCallee = 0;
4286 RetainAutoreleaseRVCallee = 0;
4287
4288 // Initialize RetainRVMarker.
4289 RetainRVMarker = 0;
4290 if (NamedMDNode *NMD =
4291 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4292 if (NMD->getNumOperands() == 1) {
4293 const MDNode *N = NMD->getOperand(0);
4294 if (N->getNumOperands() == 1)
4295 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4296 RetainRVMarker = S;
4297 }
4298
4299 return false;
4300}
4301
4302bool ObjCARCContract::runOnFunction(Function &F) {
4303 if (!EnableARCOpts)
4304 return false;
4305
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004306 // If nothing in the Module uses ARC, don't do anything.
4307 if (!Run)
4308 return false;
4309
John McCall9fbd3182011-06-15 23:37:01 +00004310 Changed = false;
4311 AA = &getAnalysis<AliasAnalysis>();
4312 DT = &getAnalysis<DominatorTree>();
4313
4314 PA.setAA(&getAnalysis<AliasAnalysis>());
4315
Dan Gohman0cdece42012-01-19 19:14:36 +00004316 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4317 // keyword. Be conservative if the function has variadic arguments.
4318 // It seems that functions which "return twice" are also unsafe for the
4319 // "tail" argument, because they are setjmp, which could need to
4320 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004321 bool TailOkForStoreStrongs = !F.isVarArg() &&
4322 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004323
John McCall9fbd3182011-06-15 23:37:01 +00004324 // For ObjC library calls which return their argument, replace uses of the
4325 // argument with uses of the call return value, if it dominates the use. This
4326 // reduces register pressure.
4327 SmallPtrSet<Instruction *, 4> DependingInstructions;
4328 SmallPtrSet<const BasicBlock *, 4> Visited;
4329 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4330 Instruction *Inst = &*I++;
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004331
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004332 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004333
John McCall9fbd3182011-06-15 23:37:01 +00004334 // Only these library routines return their argument. In particular,
4335 // objc_retainBlock does not necessarily return its argument.
4336 InstructionClass Class = GetBasicInstructionClass(Inst);
4337 switch (Class) {
4338 case IC_Retain:
4339 case IC_FusedRetainAutorelease:
4340 case IC_FusedRetainAutoreleaseRV:
4341 break;
4342 case IC_Autorelease:
4343 case IC_AutoreleaseRV:
4344 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4345 continue;
4346 break;
4347 case IC_RetainRV: {
4348 // If we're compiling for a target which needs a special inline-asm
4349 // marker to do the retainAutoreleasedReturnValue optimization,
4350 // insert it now.
4351 if (!RetainRVMarker)
4352 break;
4353 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004354 BasicBlock *InstParent = Inst->getParent();
4355
4356 // Step up to see if the call immediately precedes the RetainRV call.
4357 // If it's an invoke, we have to cross a block boundary. And we have
4358 // to carefully dodge no-op instructions.
4359 do {
4360 if (&*BBI == InstParent->begin()) {
4361 BasicBlock *Pred = InstParent->getSinglePredecessor();
4362 if (!Pred)
4363 goto decline_rv_optimization;
4364 BBI = Pred->getTerminator();
4365 break;
4366 }
4367 --BBI;
4368 } while (isNoopInstruction(BBI));
4369
John McCall9fbd3182011-06-15 23:37:01 +00004370 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman50652cd2013-01-03 07:32:41 +00004371 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman5c0ae472013-01-04 21:29:57 +00004372 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohmand6bf2012012-04-13 18:57:48 +00004373 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004374 InlineAsm *IA =
4375 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4376 /*isVarArg=*/false),
4377 RetainRVMarker->getString(),
4378 /*Constraints=*/"", /*hasSideEffects=*/true);
4379 CallInst::Create(IA, "", Inst);
4380 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004381 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004382 break;
4383 }
4384 case IC_InitWeak: {
4385 // objc_initWeak(p, null) => *p = null
4386 CallInst *CI = cast<CallInst>(Inst);
4387 if (isNullOrUndef(CI->getArgOperand(1))) {
4388 Value *Null =
4389 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4390 Changed = true;
4391 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004392
Michael Gottesman1ebbdcf2013-01-03 07:32:53 +00004393 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4394 << " New = " << *Null << "\n");
Michael Gottesman2f1bfc42013-01-07 21:26:07 +00004395
John McCall9fbd3182011-06-15 23:37:01 +00004396 CI->replaceAllUsesWith(Null);
4397 CI->eraseFromParent();
4398 }
4399 continue;
4400 }
4401 case IC_Release:
4402 ContractRelease(Inst, I);
4403 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004404 case IC_User:
4405 // Be conservative if the function has any alloca instructions.
4406 // Technically we only care about escaping alloca instructions,
4407 // but this is sufficient to handle some interesting cases.
4408 if (isa<AllocaInst>(Inst))
4409 TailOkForStoreStrongs = false;
4410 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004411 default:
4412 continue;
4413 }
4414
Michael Gottesmanec21e2a2013-01-03 08:09:27 +00004415 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004416
John McCall9fbd3182011-06-15 23:37:01 +00004417 // Don't use GetObjCArg because we don't want to look through bitcasts
4418 // and such; to do the replacement, the argument must have type i8*.
4419 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4420 for (;;) {
4421 // If we're compiling bugpointed code, don't get in trouble.
4422 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4423 break;
4424 // Look through the uses of the pointer.
4425 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4426 UI != UE; ) {
4427 Use &U = UI.getUse();
4428 unsigned OperandNo = UI.getOperandNo();
4429 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004430
4431 // If the call's return value dominates a use of the call's argument
4432 // value, rewrite the use to use the return value. We check for
4433 // reachability here because an unreachable call is considered to
4434 // trivially dominate itself, which would lead us to rewriting its
4435 // argument in terms of its return value, which would lead to
4436 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004437 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004438 Changed = true;
4439 Instruction *Replacement = Inst;
4440 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004441 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004442 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004443 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4444 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004445 if (Replacement->getType() != UseTy)
4446 Replacement = new BitCastInst(Replacement, UseTy, "",
4447 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004448 // While we're here, rewrite all edges for this PHI, rather
4449 // than just one use at a time, to minimize the number of
4450 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004451 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004452 if (PHI->getIncomingBlock(i) == BB) {
4453 // Keep the UI iterator valid.
4454 if (&PHI->getOperandUse(
4455 PHINode::getOperandNumForIncomingValue(i)) ==
4456 &UI.getUse())
4457 ++UI;
4458 PHI->setIncomingValue(i, Replacement);
4459 }
4460 } else {
4461 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004462 Replacement = new BitCastInst(Replacement, UseTy, "",
4463 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004464 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004465 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004466 }
John McCall9fbd3182011-06-15 23:37:01 +00004467 }
4468
Dan Gohman447989c2012-04-27 18:56:31 +00004469 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004470 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4471 Arg = BI->getOperand(0);
4472 else if (isa<GEPOperator>(Arg) &&
4473 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4474 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4475 else if (isa<GlobalAlias>(Arg) &&
4476 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4477 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4478 else
4479 break;
4480 }
4481 }
4482
Dan Gohman0cdece42012-01-19 19:14:36 +00004483 // If this function has no escaping allocas or suspicious vararg usage,
4484 // objc_storeStrong calls can be marked with the "tail" keyword.
4485 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004486 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004487 E = StoreStrongCalls.end(); I != E; ++I)
4488 (*I)->setTailCall();
4489 StoreStrongCalls.clear();
4490
John McCall9fbd3182011-06-15 23:37:01 +00004491 return Changed;
4492}
Michael Gottesman81c61212013-01-14 00:35:14 +00004493
4494/// @}
4495///