blob: 411da6467a316bd8e980249a6668ee7989d945d9 [file] [log] [blame]
Michael Gottesman79d8d812013-01-28 01:35:51 +00001//===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
John McCalld935e9c2011-06-15 23:37:01 +00002//
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 Gottesman97e3df02013-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 McCalld935e9c2011-06-15 23:37:01 +000029//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
John McCalld935e9c2011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +000033#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
Chandler Carruthbe810232013-01-02 10:22:59 +000035#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/raw_ostream.h"
John McCalld935e9c2011-06-15 23:37:01 +000037using namespace llvm;
38
Michael Gottesman97e3df02013-01-14 00:35:14 +000039/// \brief A handy option to enable/disable all optimizations in this file.
John McCalld935e9c2011-06-15 23:37:01 +000040static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41
Michael Gottesman97e3df02013-01-14 00:35:14 +000042/// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
43/// @{
John McCalld935e9c2011-06-15 23:37:01 +000044
45namespace {
Michael Gottesman97e3df02013-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 McCalld935e9c2011-06-15 23:37:01 +000048 template<class KeyT, class ValueT>
49 class MapVector {
Michael Gottesman97e3df02013-01-14 00:35:14 +000050 /// Map keys to indices in Vector.
John McCalld935e9c2011-06-15 23:37:01 +000051 typedef DenseMap<KeyT, size_t> MapTy;
52 MapTy Map;
53
John McCalld935e9c2011-06-15 23:37:01 +000054 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
Michael Gottesman97e3df02013-01-14 00:35:14 +000055 /// Keys and values.
John McCalld935e9c2011-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 Gohman55b06742012-03-02 01:13:53 +000082 ValueT &operator[](const KeyT &Arg) {
John McCalld935e9c2011-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 Gohman55b06742012-03-02 01:13:53 +000086 size_t Num = Vector.size();
87 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +000088 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman55b06742012-03-02 01:13:53 +000089 return Vector[Num].second;
John McCalld935e9c2011-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 Gohman55b06742012-03-02 01:13:53 +000099 size_t Num = Vector.size();
100 Pair.first->second = Num;
John McCalld935e9c2011-06-15 23:37:01 +0000101 Vector.push_back(InsertPair);
Dan Gohman55b06742012-03-02 01:13:53 +0000102 return std::make_pair(Vector.begin() + Num, true);
John McCalld935e9c2011-06-15 23:37:01 +0000103 }
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
105 }
106
Dan Gohman55b06742012-03-02 01:13:53 +0000107 const_iterator find(const KeyT &Key) const {
John McCalld935e9c2011-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 Gottesman97e3df02013-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 Gohman55b06742012-03-02 01:13:53 +0000116 void blot(const KeyT &Key) {
John McCalld935e9c2011-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 Gottesman97e3df02013-01-14 00:35:14 +0000130/// @}
131///
132/// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
133/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000134
Chandler Carruthed0881b2012-12-03 16:50:05 +0000135#include "llvm/ADT/StringSwitch.h"
136#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000137#include "llvm/IR/Intrinsics.h"
138#include "llvm/IR/Module.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000139#include "llvm/Support/CallSite.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000140#include "llvm/Transforms/Utils/Local.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000141
John McCalld935e9c2011-06-15 23:37:01 +0000142namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000143 /// \enum InstructionClass
144 /// \brief A simple classification for instructions.
John McCalld935e9c2011-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 Gohmane1e352a2012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCalld935e9c2011-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 };
Michael Gottesman782e3442013-01-17 18:32:34 +0000170
171 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class)
172 LLVM_ATTRIBUTE_USED;
Michael Gottesman1d777512013-01-17 18:36:17 +0000173 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class) {
Michael Gottesman782e3442013-01-17 18:32:34 +0000174 switch (Class) {
175 case IC_Retain:
176 return OS << "IC_Retain";
177 case IC_RetainRV:
178 return OS << "IC_RetainRV";
179 case IC_RetainBlock:
180 return OS << "IC_RetainBlock";
181 case IC_Release:
182 return OS << "IC_Release";
183 case IC_Autorelease:
184 return OS << "IC_Autorelease";
185 case IC_AutoreleaseRV:
186 return OS << "IC_AutoreleaseRV";
187 case IC_AutoreleasepoolPush:
188 return OS << "IC_AutoreleasepoolPush";
189 case IC_AutoreleasepoolPop:
190 return OS << "IC_AutoreleasepoolPop";
191 case IC_NoopCast:
192 return OS << "IC_NoopCast";
193 case IC_FusedRetainAutorelease:
194 return OS << "IC_FusedRetainAutorelease";
195 case IC_FusedRetainAutoreleaseRV:
196 return OS << "IC_FusedRetainAutoreleaseRV";
197 case IC_LoadWeakRetained:
198 return OS << "IC_LoadWeakRetained";
199 case IC_StoreWeak:
200 return OS << "IC_StoreWeak";
201 case IC_InitWeak:
202 return OS << "IC_InitWeak";
203 case IC_LoadWeak:
204 return OS << "IC_LoadWeak";
205 case IC_MoveWeak:
206 return OS << "IC_MoveWeak";
207 case IC_CopyWeak:
208 return OS << "IC_CopyWeak";
209 case IC_DestroyWeak:
210 return OS << "IC_DestroyWeak";
211 case IC_StoreStrong:
212 return OS << "IC_StoreStrong";
213 case IC_CallOrUser:
214 return OS << "IC_CallOrUser";
215 case IC_Call:
216 return OS << "IC_Call";
217 case IC_User:
218 return OS << "IC_User";
219 case IC_None:
220 return OS << "IC_None";
221 }
Benjamin Kramer0eba5772013-01-18 19:45:22 +0000222 llvm_unreachable("Unknown instruction class!");
Michael Gottesman782e3442013-01-17 18:32:34 +0000223 }
John McCalld935e9c2011-06-15 23:37:01 +0000224}
225
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000226/// \brief Test whether the given value is possible a retainable object pointer.
227static bool IsPotentialRetainableObjPtr(const Value *Op) {
228 // Pointers to static or stack storage are not valid retainable object pointers.
John McCalld935e9c2011-06-15 23:37:01 +0000229 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
230 return false;
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000231 // Special arguments can not be a valid retainable object pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000232 if (const Argument *Arg = dyn_cast<Argument>(Op))
233 if (Arg->hasByValAttr() ||
234 Arg->hasNestAttr() ||
235 Arg->hasStructRetAttr())
236 return false;
Dan Gohmanbd944b42011-12-14 19:10:53 +0000237 // Only consider values with pointer types.
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000238 //
Dan Gohmanbd944b42011-12-14 19:10:53 +0000239 // It seemes intuitive to exclude function pointer types as well, since
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000240 // functions are never retainable object pointers, however clang occasionally
241 // bitcasts retainable object pointers to function-pointer type temporarily.
Chris Lattner229907c2011-07-18 04:54:35 +0000242 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanbd944b42011-12-14 19:10:53 +0000243 if (!Ty)
John McCalld935e9c2011-06-15 23:37:01 +0000244 return false;
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000245 // Conservatively assume anything else is a potential retainable object pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000246 return true;
247}
248
Michael Gottesman4385edf2013-01-14 01:47:53 +0000249/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
250/// is.
John McCalld935e9c2011-06-15 23:37:01 +0000251static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
252 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
253 I != E; ++I)
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000254 if (IsPotentialRetainableObjPtr(*I))
John McCalld935e9c2011-06-15 23:37:01 +0000255 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
256
257 return CS.onlyReadsMemory() ? IC_None : IC_Call;
258}
259
Michael Gottesman97e3df02013-01-14 00:35:14 +0000260/// \brief Determine if F is one of the special known Functions. If it isn't,
261/// return IC_CallOrUser.
John McCalld935e9c2011-06-15 23:37:01 +0000262static InstructionClass GetFunctionClass(const Function *F) {
263 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
264
265 // No arguments.
266 if (AI == AE)
267 return StringSwitch<InstructionClass>(F->getName())
268 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
269 .Default(IC_CallOrUser);
270
271 // One argument.
272 const Argument *A0 = AI++;
273 if (AI == AE)
274 // Argument is a pointer.
Chris Lattner229907c2011-07-18 04:54:35 +0000275 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
276 Type *ETy = PTy->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000277 // Argument is i8*.
278 if (ETy->isIntegerTy(8))
279 return StringSwitch<InstructionClass>(F->getName())
280 .Case("objc_retain", IC_Retain)
281 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
282 .Case("objc_retainBlock", IC_RetainBlock)
283 .Case("objc_release", IC_Release)
284 .Case("objc_autorelease", IC_Autorelease)
285 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
286 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
287 .Case("objc_retainedObject", IC_NoopCast)
288 .Case("objc_unretainedObject", IC_NoopCast)
289 .Case("objc_unretainedPointer", IC_NoopCast)
290 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
291 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
292 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
293 .Default(IC_CallOrUser);
294
295 // Argument is i8**
Chris Lattner229907c2011-07-18 04:54:35 +0000296 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCalld935e9c2011-06-15 23:37:01 +0000297 if (Pte->getElementType()->isIntegerTy(8))
298 return StringSwitch<InstructionClass>(F->getName())
299 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
300 .Case("objc_loadWeak", IC_LoadWeak)
301 .Case("objc_destroyWeak", IC_DestroyWeak)
302 .Default(IC_CallOrUser);
303 }
304
305 // Two arguments, first is i8**.
306 const Argument *A1 = AI++;
307 if (AI == AE)
Chris Lattner229907c2011-07-18 04:54:35 +0000308 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
309 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCalld935e9c2011-06-15 23:37:01 +0000310 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattner229907c2011-07-18 04:54:35 +0000311 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
312 Type *ETy1 = PTy1->getElementType();
John McCalld935e9c2011-06-15 23:37:01 +0000313 // Second argument is i8*
314 if (ETy1->isIntegerTy(8))
315 return StringSwitch<InstructionClass>(F->getName())
316 .Case("objc_storeWeak", IC_StoreWeak)
317 .Case("objc_initWeak", IC_InitWeak)
Dan Gohmane1e352a2012-04-13 18:28:58 +0000318 .Case("objc_storeStrong", IC_StoreStrong)
John McCalld935e9c2011-06-15 23:37:01 +0000319 .Default(IC_CallOrUser);
320 // Second argument is i8**.
Chris Lattner229907c2011-07-18 04:54:35 +0000321 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCalld935e9c2011-06-15 23:37:01 +0000322 if (Pte1->getElementType()->isIntegerTy(8))
323 return StringSwitch<InstructionClass>(F->getName())
324 .Case("objc_moveWeak", IC_MoveWeak)
325 .Case("objc_copyWeak", IC_CopyWeak)
326 .Default(IC_CallOrUser);
327 }
328
329 // Anything else.
330 return IC_CallOrUser;
331}
332
Michael Gottesman97e3df02013-01-14 00:35:14 +0000333/// \brief Determine what kind of construct V is.
John McCalld935e9c2011-06-15 23:37:01 +0000334static InstructionClass GetInstructionClass(const Value *V) {
335 if (const Instruction *I = dyn_cast<Instruction>(V)) {
336 // Any instruction other than bitcast and gep with a pointer operand have a
337 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
338 // to a subsequent use, rather than using it themselves, in this sense.
339 // As a short cut, several other opcodes are known to have no pointer
340 // operands of interest. And ret is never followed by a release, so it's
341 // not interesting to examine.
342 switch (I->getOpcode()) {
343 case Instruction::Call: {
344 const CallInst *CI = cast<CallInst>(I);
345 // Check for calls to special functions.
346 if (const Function *F = CI->getCalledFunction()) {
347 InstructionClass Class = GetFunctionClass(F);
348 if (Class != IC_CallOrUser)
349 return Class;
350
351 // None of the intrinsic functions do objc_release. For intrinsics, the
352 // only question is whether or not they may be users.
353 switch (F->getIntrinsicID()) {
John McCalld935e9c2011-06-15 23:37:01 +0000354 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
355 case Intrinsic::stacksave: case Intrinsic::stackrestore:
356 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman41375a32012-05-08 23:39:44 +0000357 case Intrinsic::objectsize: case Intrinsic::prefetch:
358 case Intrinsic::stackprotector:
359 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
360 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
361 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
362 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
363 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
364 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCalld935e9c2011-06-15 23:37:01 +0000365 // Don't let dbg info affect our results.
366 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
367 // Short cut: Some intrinsics obviously don't use ObjC pointers.
368 return IC_None;
369 default:
Dan Gohman41375a32012-05-08 23:39:44 +0000370 break;
John McCalld935e9c2011-06-15 23:37:01 +0000371 }
372 }
373 return GetCallSiteClass(CI);
374 }
375 case Instruction::Invoke:
376 return GetCallSiteClass(cast<InvokeInst>(I));
377 case Instruction::BitCast:
378 case Instruction::GetElementPtr:
379 case Instruction::Select: case Instruction::PHI:
380 case Instruction::Ret: case Instruction::Br:
381 case Instruction::Switch: case Instruction::IndirectBr:
382 case Instruction::Alloca: case Instruction::VAArg:
383 case Instruction::Add: case Instruction::FAdd:
384 case Instruction::Sub: case Instruction::FSub:
385 case Instruction::Mul: case Instruction::FMul:
386 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
387 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
388 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
389 case Instruction::And: case Instruction::Or: case Instruction::Xor:
390 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
391 case Instruction::IntToPtr: case Instruction::FCmp:
392 case Instruction::FPTrunc: case Instruction::FPExt:
393 case Instruction::FPToUI: case Instruction::FPToSI:
394 case Instruction::UIToFP: case Instruction::SIToFP:
395 case Instruction::InsertElement: case Instruction::ExtractElement:
396 case Instruction::ShuffleVector:
397 case Instruction::ExtractValue:
398 break;
399 case Instruction::ICmp:
400 // Comparing a pointer with null, or any other constant, isn't an
401 // interesting use, because we don't care what the pointer points to, or
402 // about the values of any other dynamic reference-counted pointers.
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000403 if (IsPotentialRetainableObjPtr(I->getOperand(1)))
John McCalld935e9c2011-06-15 23:37:01 +0000404 return IC_User;
405 break;
406 default:
407 // For anything else, check all the operands.
Dan Gohman4b8e8ce2011-08-22 17:29:37 +0000408 // Note that this includes both operands of a Store: while the first
409 // operand isn't actually being dereferenced, it is being stored to
410 // memory where we can no longer track who might read it and dereference
411 // it, so we have to consider it potentially used.
John McCalld935e9c2011-06-15 23:37:01 +0000412 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
413 OI != OE; ++OI)
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000414 if (IsPotentialRetainableObjPtr(*OI))
John McCalld935e9c2011-06-15 23:37:01 +0000415 return IC_User;
416 }
417 }
418
419 // Otherwise, it's totally inert for ARC purposes.
420 return IC_None;
421}
422
Michael Gottesman97e3df02013-01-14 00:35:14 +0000423/// \brief Determine which objc runtime call instruction class V belongs to.
424///
425/// This is similar to GetInstructionClass except that it only detects objc
426/// runtime calls. This allows it to be faster.
427///
John McCalld935e9c2011-06-15 23:37:01 +0000428static InstructionClass GetBasicInstructionClass(const Value *V) {
429 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
430 if (const Function *F = CI->getCalledFunction())
431 return GetFunctionClass(F);
432 // Otherwise, be conservative.
433 return IC_CallOrUser;
434 }
435
436 // Otherwise, be conservative.
Dan Gohmane7a243f2012-01-17 20:52:24 +0000437 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCalld935e9c2011-06-15 23:37:01 +0000438}
439
Michael Gottesman97e3df02013-01-14 00:35:14 +0000440/// \brief Test if the given class is objc_retain or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000441static bool IsRetain(InstructionClass Class) {
442 return Class == IC_Retain ||
443 Class == IC_RetainRV;
444}
445
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446/// \brief Test if the given class is objc_autorelease or equivalent.
John McCalld935e9c2011-06-15 23:37:01 +0000447static bool IsAutorelease(InstructionClass Class) {
448 return Class == IC_Autorelease ||
449 Class == IC_AutoreleaseRV;
450}
451
Michael Gottesman97e3df02013-01-14 00:35:14 +0000452/// \brief Test if the given class represents instructions which return their
453/// argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000454static bool IsForwarding(InstructionClass Class) {
455 // objc_retainBlock technically doesn't always return its argument
456 // verbatim, but it doesn't matter for our purposes here.
457 return Class == IC_Retain ||
458 Class == IC_RetainRV ||
459 Class == IC_Autorelease ||
460 Class == IC_AutoreleaseRV ||
461 Class == IC_RetainBlock ||
462 Class == IC_NoopCast;
463}
464
Michael Gottesman97e3df02013-01-14 00:35:14 +0000465/// \brief Test if the given class represents instructions which do nothing if
466/// passed a null pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000467static bool IsNoopOnNull(InstructionClass Class) {
468 return Class == IC_Retain ||
469 Class == IC_RetainRV ||
470 Class == IC_Release ||
471 Class == IC_Autorelease ||
472 Class == IC_AutoreleaseRV ||
473 Class == IC_RetainBlock;
474}
475
Michael Gottesman4385edf2013-01-14 01:47:53 +0000476/// \brief Test if the given class represents instructions which are always safe
477/// to mark with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000478static bool IsAlwaysTail(InstructionClass Class) {
479 // IC_RetainBlock may be given a stack argument.
480 return Class == IC_Retain ||
481 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000482 Class == IC_AutoreleaseRV;
483}
484
Michael Gottesmanc9656fa2013-01-12 01:25:15 +0000485/// \brief Test if the given class represents instructions which are never safe
486/// to mark with the "tail" keyword.
487static bool IsNeverTail(InstructionClass Class) {
488 /// It is never safe to tail call objc_autorelease since by tail calling
489 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
490 /// fast autoreleasing causing our object to be potentially reclaimed from the
491 /// autorelease pool which violates the semantics of __autoreleasing types in
492 /// ARC.
493 return Class == IC_Autorelease;
494}
495
Michael Gottesman97e3df02013-01-14 00:35:14 +0000496/// \brief Test if the given class represents instructions which are always safe
497/// to mark with the nounwind attribute.
John McCalld935e9c2011-06-15 23:37:01 +0000498static bool IsNoThrow(InstructionClass Class) {
Dan Gohmanfca43c22011-09-14 18:33:34 +0000499 // objc_retainBlock is not nounwind because it calls user copy constructors
500 // which could theoretically throw.
John McCalld935e9c2011-06-15 23:37:01 +0000501 return Class == IC_Retain ||
502 Class == IC_RetainRV ||
John McCalld935e9c2011-06-15 23:37:01 +0000503 Class == IC_Release ||
504 Class == IC_Autorelease ||
505 Class == IC_AutoreleaseRV ||
506 Class == IC_AutoreleasepoolPush ||
507 Class == IC_AutoreleasepoolPop;
508}
509
Michael Gottesman97e3df02013-01-14 00:35:14 +0000510/// \brief Erase the given instruction.
511///
512/// Many ObjC calls return their argument verbatim,
513/// so if it's such a call and the return value has users, replace them with the
514/// argument value.
515///
John McCalld935e9c2011-06-15 23:37:01 +0000516static void EraseInstruction(Instruction *CI) {
517 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
518
519 bool Unused = CI->use_empty();
520
521 if (!Unused) {
522 // Replace the return value with the argument.
523 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
524 "Can't delete non-forwarding instruction with users!");
525 CI->replaceAllUsesWith(OldArg);
526 }
527
528 CI->eraseFromParent();
529
530 if (Unused)
531 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
532}
533
Michael Gottesman97e3df02013-01-14 00:35:14 +0000534/// \brief This is a wrapper around getUnderlyingObject which also knows how to
535/// look through objc_retain and objc_autorelease calls, which we know to return
536/// their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000537static const Value *GetUnderlyingObjCPtr(const Value *V) {
538 for (;;) {
539 V = GetUnderlyingObject(V);
540 if (!IsForwarding(GetBasicInstructionClass(V)))
541 break;
542 V = cast<CallInst>(V)->getArgOperand(0);
543 }
544
545 return V;
546}
547
Michael Gottesman97e3df02013-01-14 00:35:14 +0000548/// \brief This is a wrapper around Value::stripPointerCasts which also knows
549/// how to look through objc_retain and objc_autorelease calls, which we know to
550/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000551static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
552 for (;;) {
553 V = V->stripPointerCasts();
554 if (!IsForwarding(GetBasicInstructionClass(V)))
555 break;
556 V = cast<CallInst>(V)->getArgOperand(0);
557 }
558 return V;
559}
560
Michael Gottesman97e3df02013-01-14 00:35:14 +0000561/// \brief This is a wrapper around Value::stripPointerCasts which also knows
562/// how to look through objc_retain and objc_autorelease calls, which we know to
563/// return their argument verbatim.
John McCalld935e9c2011-06-15 23:37:01 +0000564static Value *StripPointerCastsAndObjCCalls(Value *V) {
565 for (;;) {
566 V = V->stripPointerCasts();
567 if (!IsForwarding(GetBasicInstructionClass(V)))
568 break;
569 V = cast<CallInst>(V)->getArgOperand(0);
570 }
571 return V;
572}
573
Michael Gottesman97e3df02013-01-14 00:35:14 +0000574/// \brief Assuming the given instruction is one of the special calls such as
575/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCalld935e9c2011-06-15 23:37:01 +0000576/// casts and forwarding calls.
577static Value *GetObjCArg(Value *Inst) {
578 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
579}
580
Michael Gottesman87db35752013-01-18 23:02:45 +0000581/// \brief Return true if this value refers to a distinct and identifiable
582/// object.
583///
584/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
585/// special knowledge of ObjC conventions.
John McCalld935e9c2011-06-15 23:37:01 +0000586static bool IsObjCIdentifiedObject(const Value *V) {
587 // Assume that call results and arguments have their own "provenance".
588 // Constants (including GlobalVariables) and Allocas are never
589 // reference-counted.
590 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
591 isa<Argument>(V) || isa<Constant>(V) ||
592 isa<AllocaInst>(V))
593 return true;
594
595 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
596 const Value *Pointer =
597 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
598 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman56e1cef2011-08-22 17:29:11 +0000599 // A constant pointer can't be pointing to an object on the heap. It may
600 // be reference-counted, but it won't be deleted.
601 if (GV->isConstant())
602 return true;
John McCalld935e9c2011-06-15 23:37:01 +0000603 StringRef Name = GV->getName();
604 // These special variables are known to hold values which are not
605 // reference-counted pointers.
606 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
607 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
608 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
609 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
610 Name.startswith("\01l_objc_msgSend_fixup_"))
611 return true;
612 }
613 }
614
615 return false;
616}
617
Michael Gottesman97e3df02013-01-14 00:35:14 +0000618/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
619/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000620static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
621 if (Arg->hasOneUse()) {
622 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
623 return FindSingleUseIdentifiedObject(BC->getOperand(0));
624 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
625 if (GEP->hasAllZeroIndices())
626 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
627 if (IsForwarding(GetBasicInstructionClass(Arg)))
628 return FindSingleUseIdentifiedObject(
629 cast<CallInst>(Arg)->getArgOperand(0));
630 if (!IsObjCIdentifiedObject(Arg))
631 return 0;
632 return Arg;
633 }
634
Dan Gohman41375a32012-05-08 23:39:44 +0000635 // If we found an identifiable object but it has multiple uses, but they are
636 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000637 if (IsObjCIdentifiedObject(Arg)) {
638 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
639 UI != UE; ++UI) {
640 const User *U = *UI;
641 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
642 return 0;
643 }
644
645 return Arg;
646 }
647
648 return 0;
649}
650
Michael Gottesman97e3df02013-01-14 00:35:14 +0000651/// \brief Test if the given module looks interesting to run ARC optimization
652/// on.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000653static bool ModuleHasARC(const Module &M) {
654 return
655 M.getNamedValue("objc_retain") ||
656 M.getNamedValue("objc_release") ||
657 M.getNamedValue("objc_autorelease") ||
658 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
659 M.getNamedValue("objc_retainBlock") ||
660 M.getNamedValue("objc_autoreleaseReturnValue") ||
661 M.getNamedValue("objc_autoreleasePoolPush") ||
662 M.getNamedValue("objc_loadWeakRetained") ||
663 M.getNamedValue("objc_loadWeak") ||
664 M.getNamedValue("objc_destroyWeak") ||
665 M.getNamedValue("objc_storeWeak") ||
666 M.getNamedValue("objc_initWeak") ||
667 M.getNamedValue("objc_moveWeak") ||
668 M.getNamedValue("objc_copyWeak") ||
669 M.getNamedValue("objc_retainedObject") ||
670 M.getNamedValue("objc_unretainedObject") ||
671 M.getNamedValue("objc_unretainedPointer");
672}
673
Michael Gottesman4385edf2013-01-14 01:47:53 +0000674/// \brief Test whether the given pointer, which is an Objective C block
675/// pointer, does not "escape".
Michael Gottesman97e3df02013-01-14 00:35:14 +0000676///
677/// This differs from regular escape analysis in that a use as an
678/// argument to a call is not considered an escape.
679///
Dan Gohman728db492012-01-13 00:39:07 +0000680static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000681
682 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
683
Dan Gohman728db492012-01-13 00:39:07 +0000684 // Walk the def-use chains.
685 SmallVector<const Value *, 4> Worklist;
686 Worklist.push_back(BlockPtr);
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000687
688 // Ensure we do not visit any value twice.
689 SmallPtrSet<const Value *, 4> VisitedSet;
690
Dan Gohman728db492012-01-13 00:39:07 +0000691 do {
692 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000693
694 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
695
Dan Gohman728db492012-01-13 00:39:07 +0000696 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
697 UI != UE; ++UI) {
698 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000699
700 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
701
Dan Gohman728db492012-01-13 00:39:07 +0000702 // Special - Use by a call (callee or argument) is not considered
703 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000704 switch (GetBasicInstructionClass(UUser)) {
705 case IC_StoreWeak:
706 case IC_InitWeak:
707 case IC_StoreStrong:
708 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000709 case IC_AutoreleaseRV: {
710 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
711 "Block Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000712 // These special functions make copies of their pointer arguments.
713 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000714 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000715 case IC_User:
716 case IC_None:
717 // Use by an instruction which copies the value is an escape if the
718 // result is an escape.
719 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
720 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000721
Michael Gottesmane9145d32013-01-14 19:18:39 +0000722 if (!VisitedSet.insert(UUser)) {
Michael Gottesman4385edf2013-01-14 01:47:53 +0000723 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
724 "if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000725 Worklist.push_back(UUser);
726 } else {
727 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
728 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000729 continue;
730 }
731 // Use by a load is not an escape.
732 if (isa<LoadInst>(UUser))
733 continue;
734 // Use by a store is not an escape if the use is the address.
735 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
736 if (V != SI->getValueOperand())
737 continue;
738 break;
739 default:
740 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000741 continue;
742 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000743 // Otherwise, conservatively assume an escape.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000744 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000745 return true;
746 }
747 } while (!Worklist.empty());
748
749 // No escapes found.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000750 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000751 return false;
752}
753
Michael Gottesman97e3df02013-01-14 00:35:14 +0000754/// @}
755///
Michael Gottesman4385edf2013-01-14 01:47:53 +0000756/// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
Michael Gottesman97e3df02013-01-14 00:35:14 +0000757/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000758
John McCalld935e9c2011-06-15 23:37:01 +0000759#include "llvm/Analysis/AliasAnalysis.h"
760#include "llvm/Analysis/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000761#include "llvm/Pass.h"
John McCalld935e9c2011-06-15 23:37:01 +0000762
763namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000764 /// \brief This is a simple alias analysis implementation that uses knowledge
765 /// of ARC constructs to answer queries.
John McCalld935e9c2011-06-15 23:37:01 +0000766 ///
767 /// TODO: This class could be generalized to know about other ObjC-specific
768 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
769 /// even though their offsets are dynamic.
770 class ObjCARCAliasAnalysis : public ImmutablePass,
771 public AliasAnalysis {
772 public:
773 static char ID; // Class identification, replacement for typeinfo
774 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
775 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
776 }
777
778 private:
779 virtual void initializePass() {
780 InitializeAliasAnalysis(this);
781 }
782
Michael Gottesman97e3df02013-01-14 00:35:14 +0000783 /// This method is used when a pass implements an analysis interface through
784 /// multiple inheritance. If needed, it should override this to adjust the
785 /// this pointer as needed for the specified pass info.
John McCalld935e9c2011-06-15 23:37:01 +0000786 virtual void *getAdjustedAnalysisPointer(const void *PI) {
787 if (PI == &AliasAnalysis::ID)
Dan Gohmandae33492012-04-27 18:56:31 +0000788 return static_cast<AliasAnalysis *>(this);
John McCalld935e9c2011-06-15 23:37:01 +0000789 return this;
790 }
791
792 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
793 virtual AliasResult alias(const Location &LocA, const Location &LocB);
794 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
795 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
796 virtual ModRefBehavior getModRefBehavior(const Function *F);
797 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
798 const Location &Loc);
799 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
800 ImmutableCallSite CS2);
801 };
802} // End of anonymous namespace
803
804// Register this pass...
805char ObjCARCAliasAnalysis::ID = 0;
806INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
807 "ObjC-ARC-Based Alias Analysis", false, true, false)
808
809ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
810 return new ObjCARCAliasAnalysis();
811}
812
813void
814ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
815 AU.setPreservesAll();
816 AliasAnalysis::getAnalysisUsage(AU);
817}
818
819AliasAnalysis::AliasResult
820ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
821 if (!EnableARCOpts)
822 return AliasAnalysis::alias(LocA, LocB);
823
824 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
825 // precise alias query.
826 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
827 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
828 AliasResult Result =
829 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
830 Location(SB, LocB.Size, LocB.TBAATag));
831 if (Result != MayAlias)
832 return Result;
833
834 // If that failed, climb to the underlying object, including climbing through
835 // ObjC-specific no-ops, and try making an imprecise alias query.
836 const Value *UA = GetUnderlyingObjCPtr(SA);
837 const Value *UB = GetUnderlyingObjCPtr(SB);
838 if (UA != SA || UB != SB) {
839 Result = AliasAnalysis::alias(Location(UA), Location(UB));
840 // We can't use MustAlias or PartialAlias results here because
841 // GetUnderlyingObjCPtr may return an offsetted pointer value.
842 if (Result == NoAlias)
843 return NoAlias;
844 }
845
846 // If that failed, fail. We don't need to chain here, since that's covered
847 // by the earlier precise query.
848 return MayAlias;
849}
850
851bool
852ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
853 bool OrLocal) {
854 if (!EnableARCOpts)
855 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
856
857 // First, strip off no-ops, including ObjC-specific no-ops, and try making
858 // a precise alias query.
859 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
860 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
861 OrLocal))
862 return true;
863
864 // If that failed, climb to the underlying object, including climbing through
865 // ObjC-specific no-ops, and try making an imprecise alias query.
866 const Value *U = GetUnderlyingObjCPtr(S);
867 if (U != S)
868 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
869
870 // If that failed, fail. We don't need to chain here, since that's covered
871 // by the earlier precise query.
872 return false;
873}
874
875AliasAnalysis::ModRefBehavior
876ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
877 // We have nothing to do. Just chain to the next AliasAnalysis.
878 return AliasAnalysis::getModRefBehavior(CS);
879}
880
881AliasAnalysis::ModRefBehavior
882ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
883 if (!EnableARCOpts)
884 return AliasAnalysis::getModRefBehavior(F);
885
886 switch (GetFunctionClass(F)) {
887 case IC_NoopCast:
888 return DoesNotAccessMemory;
889 default:
890 break;
891 }
892
893 return AliasAnalysis::getModRefBehavior(F);
894}
895
896AliasAnalysis::ModRefResult
897ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
898 if (!EnableARCOpts)
899 return AliasAnalysis::getModRefInfo(CS, Loc);
900
901 switch (GetBasicInstructionClass(CS.getInstruction())) {
902 case IC_Retain:
903 case IC_RetainRV:
John McCalld935e9c2011-06-15 23:37:01 +0000904 case IC_Autorelease:
905 case IC_AutoreleaseRV:
906 case IC_NoopCast:
907 case IC_AutoreleasepoolPush:
908 case IC_FusedRetainAutorelease:
909 case IC_FusedRetainAutoreleaseRV:
910 // These functions don't access any memory visible to the compiler.
Benjamin Kramerbde91762012-06-02 10:20:22 +0000911 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohmand4b5e3a2011-09-14 18:13:00 +0000912 // pointers when it copies block data.
John McCalld935e9c2011-06-15 23:37:01 +0000913 return NoModRef;
914 default:
915 break;
916 }
917
918 return AliasAnalysis::getModRefInfo(CS, Loc);
919}
920
921AliasAnalysis::ModRefResult
922ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
923 ImmutableCallSite CS2) {
924 // TODO: Theoretically we could check for dependencies between objc_* calls
925 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
926 return AliasAnalysis::getModRefInfo(CS1, CS2);
927}
928
Michael Gottesman97e3df02013-01-14 00:35:14 +0000929/// @}
930///
931/// \defgroup ARCExpansion Early ARC Optimizations.
932/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000933
934#include "llvm/Support/InstIterator.h"
Michael Gottesman79d8d812013-01-28 01:35:51 +0000935#include "llvm/Transforms/ObjCARC.h"
John McCalld935e9c2011-06-15 23:37:01 +0000936
937namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000938 /// \brief Early ARC transformations.
John McCalld935e9c2011-06-15 23:37:01 +0000939 class ObjCARCExpand : public FunctionPass {
940 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000941 virtual bool doInitialization(Module &M);
John McCalld935e9c2011-06-15 23:37:01 +0000942 virtual bool runOnFunction(Function &F);
943
Michael Gottesman97e3df02013-01-14 00:35:14 +0000944 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000945 bool Run;
946
John McCalld935e9c2011-06-15 23:37:01 +0000947 public:
948 static char ID;
949 ObjCARCExpand() : FunctionPass(ID) {
950 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
951 }
952 };
953}
954
955char ObjCARCExpand::ID = 0;
956INITIALIZE_PASS(ObjCARCExpand,
957 "objc-arc-expand", "ObjC ARC expansion", false, false)
958
959Pass *llvm::createObjCARCExpandPass() {
960 return new ObjCARCExpand();
961}
962
963void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
964 AU.setPreservesCFG();
965}
966
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000967bool ObjCARCExpand::doInitialization(Module &M) {
968 Run = ModuleHasARC(M);
969 return false;
970}
971
John McCalld935e9c2011-06-15 23:37:01 +0000972bool ObjCARCExpand::runOnFunction(Function &F) {
973 if (!EnableARCOpts)
974 return false;
975
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000976 // If nothing in the Module uses ARC, don't do anything.
977 if (!Run)
978 return false;
979
John McCalld935e9c2011-06-15 23:37:01 +0000980 bool Changed = false;
981
Michael Gottesmanaf2113f2013-01-13 07:00:51 +0000982 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
983
John McCalld935e9c2011-06-15 23:37:01 +0000984 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
985 Instruction *Inst = &*I;
Michael Gottesman10426b52013-01-07 21:26:07 +0000986
Michael Gottesman3f146e22013-01-01 16:05:48 +0000987 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +0000988
John McCalld935e9c2011-06-15 23:37:01 +0000989 switch (GetBasicInstructionClass(Inst)) {
990 case IC_Retain:
991 case IC_RetainRV:
992 case IC_Autorelease:
993 case IC_AutoreleaseRV:
994 case IC_FusedRetainAutorelease:
Michael Gottesmanc8a11df2013-01-01 16:05:54 +0000995 case IC_FusedRetainAutoreleaseRV: {
John McCalld935e9c2011-06-15 23:37:01 +0000996 // These calls return their argument verbatim, as a low-level
997 // optimization. However, this makes high-level optimizations
998 // harder. Undo any uses of this optimization that the front-end
Dan Gohman670f9372012-04-13 18:57:48 +0000999 // emitted here. We'll redo them in the contract pass.
John McCalld935e9c2011-06-15 23:37:01 +00001000 Changed = true;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +00001001 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
1002 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
1003 " New = " << *Value << "\n");
1004 Inst->replaceAllUsesWith(Value);
John McCalld935e9c2011-06-15 23:37:01 +00001005 break;
Michael Gottesmanc8a11df2013-01-01 16:05:54 +00001006 }
John McCalld935e9c2011-06-15 23:37:01 +00001007 default:
1008 break;
1009 }
1010 }
Michael Gottesman10426b52013-01-07 21:26:07 +00001011
Michael Gottesman50ae5b22013-01-03 08:09:27 +00001012 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001013
John McCalld935e9c2011-06-15 23:37:01 +00001014 return Changed;
1015}
1016
Michael Gottesman97e3df02013-01-14 00:35:14 +00001017/// @}
1018///
1019/// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
1020/// @{
Dan Gohmane7a243f2012-01-17 20:52:24 +00001021
Dan Gohman41375a32012-05-08 23:39:44 +00001022#include "llvm/ADT/STLExtras.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001023#include "llvm/IR/Constants.h"
Dan Gohman82041c22012-01-18 21:19:38 +00001024
Dan Gohmane7a243f2012-01-17 20:52:24 +00001025namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001026 /// \brief Autorelease pool elimination.
Dan Gohmane7a243f2012-01-17 20:52:24 +00001027 class ObjCARCAPElim : public ModulePass {
1028 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1029 virtual bool runOnModule(Module &M);
1030
Dan Gohmandae33492012-04-27 18:56:31 +00001031 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
1032 static bool OptimizeBB(BasicBlock *BB);
Dan Gohmane7a243f2012-01-17 20:52:24 +00001033
1034 public:
1035 static char ID;
1036 ObjCARCAPElim() : ModulePass(ID) {
1037 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
1038 }
1039 };
1040}
1041
1042char ObjCARCAPElim::ID = 0;
1043INITIALIZE_PASS(ObjCARCAPElim,
1044 "objc-arc-apelim",
1045 "ObjC ARC autorelease pool elimination",
1046 false, false)
1047
1048Pass *llvm::createObjCARCAPElimPass() {
1049 return new ObjCARCAPElim();
1050}
1051
1052void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
1053 AU.setPreservesCFG();
1054}
1055
Michael Gottesman97e3df02013-01-14 00:35:14 +00001056/// Interprocedurally determine if calls made by the given call site can
1057/// possibly produce autoreleases.
Dan Gohmandae33492012-04-27 18:56:31 +00001058bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1059 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohmane7a243f2012-01-17 20:52:24 +00001060 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1061 return true;
Dan Gohmandae33492012-04-27 18:56:31 +00001062 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohmane7a243f2012-01-17 20:52:24 +00001063 I != E; ++I) {
Dan Gohmandae33492012-04-27 18:56:31 +00001064 const BasicBlock *BB = I;
1065 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1066 J != F; ++J)
1067 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman8f12fae2012-01-18 21:24:45 +00001068 // This recursion depth limit is arbitrary. It's just great
1069 // enough to cover known interesting testcases.
1070 if (Depth < 3 &&
1071 !JCS.onlyReadsMemory() &&
1072 MayAutorelease(JCS, Depth + 1))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001073 return true;
1074 }
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1081bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1082 bool Changed = false;
1083
1084 Instruction *Push = 0;
1085 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1086 Instruction *Inst = I++;
1087 switch (GetBasicInstructionClass(Inst)) {
1088 case IC_AutoreleasepoolPush:
1089 Push = Inst;
1090 break;
1091 case IC_AutoreleasepoolPop:
1092 // If this pop matches a push and nothing in between can autorelease,
1093 // zap the pair.
1094 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1095 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001096 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1097 "autorelease pair:\n"
1098 " Pop: " << *Inst << "\n"
Michael Gottesmanef682c52013-01-03 08:09:17 +00001099 << " Push: " << *Push << "\n");
Dan Gohmane7a243f2012-01-17 20:52:24 +00001100 Inst->eraseFromParent();
1101 Push->eraseFromParent();
1102 }
1103 Push = 0;
1104 break;
1105 case IC_CallOrUser:
Dan Gohmandae33492012-04-27 18:56:31 +00001106 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohmane7a243f2012-01-17 20:52:24 +00001107 Push = 0;
1108 break;
1109 default:
1110 break;
1111 }
1112 }
1113
1114 return Changed;
1115}
1116
1117bool ObjCARCAPElim::runOnModule(Module &M) {
1118 if (!EnableARCOpts)
1119 return false;
1120
1121 // If nothing in the Module uses ARC, don't do anything.
1122 if (!ModuleHasARC(M))
1123 return false;
1124
Dan Gohman82041c22012-01-18 21:19:38 +00001125 // Find the llvm.global_ctors variable, as the first step in
Dan Gohman670f9372012-04-13 18:57:48 +00001126 // identifying the global constructors. In theory, unnecessary autorelease
1127 // pools could occur anywhere, but in practice it's pretty rare. Global
1128 // ctors are a place where autorelease pools get inserted automatically,
1129 // so it's pretty common for them to be unnecessary, and it's pretty
1130 // profitable to eliminate them.
Dan Gohman82041c22012-01-18 21:19:38 +00001131 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1132 if (!GV)
1133 return false;
1134
1135 assert(GV->hasDefinitiveInitializer() &&
1136 "llvm.global_ctors is uncooperative!");
1137
Dan Gohmane7a243f2012-01-17 20:52:24 +00001138 bool Changed = false;
1139
Dan Gohman82041c22012-01-18 21:19:38 +00001140 // Dig the constructor functions out of GV's initializer.
1141 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1142 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1143 OI != OE; ++OI) {
1144 Value *Op = *OI;
1145 // llvm.global_ctors is an array of pairs where the second members
1146 // are constructor functions.
Dan Gohman22fbe8d2012-04-18 22:24:33 +00001147 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1148 // If the user used a constructor function with the wrong signature and
1149 // it got bitcasted or whatever, look the other way.
1150 if (!F)
1151 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001152 // Only look at function definitions.
1153 if (F->isDeclaration())
1154 continue;
Dan Gohmane7a243f2012-01-17 20:52:24 +00001155 // Only look at functions with one basic block.
1156 if (llvm::next(F->begin()) != F->end())
1157 continue;
1158 // Ok, a single-block constructor function definition. Try to optimize it.
1159 Changed |= OptimizeBB(F->begin());
1160 }
1161
1162 return Changed;
1163}
1164
Michael Gottesman97e3df02013-01-14 00:35:14 +00001165/// @}
1166///
1167/// \defgroup ARCOpt ARC Optimization.
1168/// @{
John McCalld935e9c2011-06-15 23:37:01 +00001169
1170// TODO: On code like this:
1171//
1172// objc_retain(%x)
1173// stuff_that_cannot_release()
1174// objc_autorelease(%x)
1175// stuff_that_cannot_release()
1176// objc_retain(%x)
1177// stuff_that_cannot_release()
1178// objc_autorelease(%x)
1179//
1180// The second retain and autorelease can be deleted.
1181
1182// TODO: It should be possible to delete
1183// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1184// pairs if nothing is actually autoreleased between them. Also, autorelease
1185// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1186// after inlining) can be turned into plain release calls.
1187
1188// TODO: Critical-edge splitting. If the optimial insertion point is
1189// a critical edge, the current algorithm has to fail, because it doesn't
1190// know how to split edges. It should be possible to make the optimizer
1191// think in terms of edges, rather than blocks, and then split critical
1192// edges on demand.
1193
1194// TODO: OptimizeSequences could generalized to be Interprocedural.
1195
1196// TODO: Recognize that a bunch of other objc runtime calls have
1197// non-escaping arguments and non-releasing arguments, and may be
1198// non-autoreleasing.
1199
1200// TODO: Sink autorelease calls as far as possible. Unfortunately we
1201// usually can't sink them past other calls, which would be the main
1202// case where it would be useful.
1203
Dan Gohmanb3894012011-08-19 00:26:36 +00001204// TODO: The pointer returned from objc_loadWeakRetained is retained.
1205
1206// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001207
Chandler Carruthed0881b2012-12-03 16:50:05 +00001208#include "llvm/ADT/SmallPtrSet.h"
1209#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00001210#include "llvm/IR/LLVMContext.h"
John McCalld935e9c2011-06-15 23:37:01 +00001211#include "llvm/Support/CFG.h"
John McCalld935e9c2011-06-15 23:37:01 +00001212
1213STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1214STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1215STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1216STATISTIC(NumRets, "Number of return value forwarding "
1217 "retain+autoreleaes eliminated");
1218STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1219STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1220
1221namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001222 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1223 /// techniques, except it uses special ObjC-specific reasoning about pointer
1224 /// relationships.
Michael Gottesman12780c2d2013-01-24 21:35:00 +00001225 ///
1226 /// In this context ``Provenance'' is defined as the history of an object's
1227 /// ownership. Thus ``Provenance Analysis'' is defined by using the notion of
1228 /// an ``independent provenance source'' of a pointer to determine whether or
1229 /// not two pointers have the same provenance source and thus could
1230 /// potentially be related.
John McCalld935e9c2011-06-15 23:37:01 +00001231 class ProvenanceAnalysis {
1232 AliasAnalysis *AA;
1233
1234 typedef std::pair<const Value *, const Value *> ValuePairTy;
1235 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1236 CachedResultsTy CachedResults;
1237
1238 bool relatedCheck(const Value *A, const Value *B);
1239 bool relatedSelect(const SelectInst *A, const Value *B);
1240 bool relatedPHI(const PHINode *A, const Value *B);
1241
Craig Topperb1d83e82012-09-18 02:01:41 +00001242 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1243 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCalld935e9c2011-06-15 23:37:01 +00001244
1245 public:
1246 ProvenanceAnalysis() {}
1247
1248 void setAA(AliasAnalysis *aa) { AA = aa; }
1249
1250 AliasAnalysis *getAA() const { return AA; }
1251
1252 bool related(const Value *A, const Value *B);
1253
1254 void clear() {
1255 CachedResults.clear();
1256 }
1257 };
1258}
1259
1260bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1261 // If the values are Selects with the same condition, we can do a more precise
1262 // check: just check for relations between the values on corresponding arms.
1263 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohmandae33492012-04-27 18:56:31 +00001264 if (A->getCondition() == SB->getCondition())
1265 return related(A->getTrueValue(), SB->getTrueValue()) ||
1266 related(A->getFalseValue(), SB->getFalseValue());
John McCalld935e9c2011-06-15 23:37:01 +00001267
1268 // Check both arms of the Select node individually.
Dan Gohmandae33492012-04-27 18:56:31 +00001269 return related(A->getTrueValue(), B) ||
1270 related(A->getFalseValue(), B);
John McCalld935e9c2011-06-15 23:37:01 +00001271}
1272
1273bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1274 // If the values are PHIs in the same block, we can do a more precise as well
1275 // as efficient check: just check for relations between the values on
1276 // corresponding edges.
1277 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1278 if (PNB->getParent() == A->getParent()) {
1279 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1280 if (related(A->getIncomingValue(i),
1281 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1282 return true;
1283 return false;
1284 }
1285
1286 // Check each unique source of the PHI node against B.
1287 SmallPtrSet<const Value *, 4> UniqueSrc;
1288 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1289 const Value *PV1 = A->getIncomingValue(i);
1290 if (UniqueSrc.insert(PV1) && related(PV1, B))
1291 return true;
1292 }
1293
1294 // All of the arms checked out.
1295 return false;
1296}
1297
Michael Gottesman97e3df02013-01-14 00:35:14 +00001298/// Test if the value of P, or any value covered by its provenance, is ever
1299/// stored within the function (not counting callees).
John McCalld935e9c2011-06-15 23:37:01 +00001300static bool isStoredObjCPointer(const Value *P) {
1301 SmallPtrSet<const Value *, 8> Visited;
1302 SmallVector<const Value *, 8> Worklist;
1303 Worklist.push_back(P);
1304 Visited.insert(P);
1305 do {
1306 P = Worklist.pop_back_val();
1307 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1308 UI != UE; ++UI) {
1309 const User *Ur = *UI;
1310 if (isa<StoreInst>(Ur)) {
1311 if (UI.getOperandNo() == 0)
1312 // The pointer is stored.
1313 return true;
1314 // The pointed is stored through.
1315 continue;
1316 }
1317 if (isa<CallInst>(Ur))
1318 // The pointer is passed as an argument, ignore this.
1319 continue;
1320 if (isa<PtrToIntInst>(P))
1321 // Assume the worst.
1322 return true;
1323 if (Visited.insert(Ur))
1324 Worklist.push_back(Ur);
1325 }
1326 } while (!Worklist.empty());
1327
1328 // Everything checked out.
1329 return false;
1330}
1331
1332bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1333 // Skip past provenance pass-throughs.
1334 A = GetUnderlyingObjCPtr(A);
1335 B = GetUnderlyingObjCPtr(B);
1336
1337 // Quick check.
1338 if (A == B)
1339 return true;
1340
1341 // Ask regular AliasAnalysis, for a first approximation.
1342 switch (AA->alias(A, B)) {
1343 case AliasAnalysis::NoAlias:
1344 return false;
1345 case AliasAnalysis::MustAlias:
1346 case AliasAnalysis::PartialAlias:
1347 return true;
1348 case AliasAnalysis::MayAlias:
1349 break;
1350 }
1351
1352 bool AIsIdentified = IsObjCIdentifiedObject(A);
1353 bool BIsIdentified = IsObjCIdentifiedObject(B);
1354
1355 // An ObjC-Identified object can't alias a load if it is never locally stored.
1356 if (AIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001357 // Check for an obvious escape.
1358 if (isa<LoadInst>(B))
1359 return isStoredObjCPointer(A);
John McCalld935e9c2011-06-15 23:37:01 +00001360 if (BIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001361 // Check for an obvious escape.
1362 if (isa<LoadInst>(A))
1363 return isStoredObjCPointer(B);
1364 // Both pointers are identified and escapes aren't an evident problem.
1365 return false;
John McCalld935e9c2011-06-15 23:37:01 +00001366 }
Dan Gohmandf476e52012-09-04 23:16:20 +00001367 } else if (BIsIdentified) {
1368 // Check for an obvious escape.
1369 if (isa<LoadInst>(A))
John McCalld935e9c2011-06-15 23:37:01 +00001370 return isStoredObjCPointer(B);
1371 }
1372
1373 // Special handling for PHI and Select.
1374 if (const PHINode *PN = dyn_cast<PHINode>(A))
1375 return relatedPHI(PN, B);
1376 if (const PHINode *PN = dyn_cast<PHINode>(B))
1377 return relatedPHI(PN, A);
1378 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1379 return relatedSelect(S, B);
1380 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1381 return relatedSelect(S, A);
1382
1383 // Conservative.
1384 return true;
1385}
1386
1387bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1388 // Begin by inserting a conservative value into the map. If the insertion
1389 // fails, we have the answer already. If it succeeds, leave it there until we
1390 // compute the real answer to guard against recursive queries.
1391 if (A > B) std::swap(A, B);
1392 std::pair<CachedResultsTy::iterator, bool> Pair =
1393 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1394 if (!Pair.second)
1395 return Pair.first->second;
1396
1397 bool Result = relatedCheck(A, B);
1398 CachedResults[ValuePairTy(A, B)] = Result;
1399 return Result;
1400}
1401
1402namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001403 /// \enum Sequence
1404 ///
1405 /// \brief A sequence of states that a pointer may go through in which an
1406 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +00001407 enum Sequence {
1408 S_None,
1409 S_Retain, ///< objc_retain(x)
1410 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1411 S_Use, ///< any use of x
1412 S_Stop, ///< like S_Release, but code motion is stopped
1413 S_Release, ///< objc_release(x)
1414 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1415 };
1416}
1417
1418static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1419 // The easy cases.
1420 if (A == B)
1421 return A;
1422 if (A == S_None || B == S_None)
1423 return S_None;
1424
John McCalld935e9c2011-06-15 23:37:01 +00001425 if (A > B) std::swap(A, B);
1426 if (TopDown) {
1427 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +00001428 if ((A == S_Retain || A == S_CanRelease) &&
1429 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +00001430 return B;
1431 } else {
1432 // Choose the side which is further along in the sequence.
1433 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +00001434 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +00001435 return A;
1436 // If both sides are releases, choose the more conservative one.
1437 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1438 return A;
1439 if (A == S_Release && B == S_MovableRelease)
1440 return A;
1441 }
1442
1443 return S_None;
1444}
1445
1446namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001447 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +00001448 /// retain-decrement-use-release sequence or release-use-decrement-retain
1449 /// reverese sequence.
1450 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001451 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +00001452 /// object is known to be positive. Similarly, before an objc_release, the
1453 /// reference count of the referenced object is known to be positive. If
1454 /// there are retain-release pairs in code regions where the retain count
1455 /// is known to be positive, they can be eliminated, regardless of any side
1456 /// effects between them.
1457 ///
1458 /// Also, a retain+release pair nested within another retain+release
1459 /// pair all on the known same pointer value can be eliminated, regardless
1460 /// of any intervening side effects.
1461 ///
1462 /// KnownSafe is true when either of these conditions is satisfied.
1463 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +00001464
Michael Gottesman97e3df02013-01-14 00:35:14 +00001465 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1466 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +00001467 bool IsRetainBlock;
1468
Michael Gottesman97e3df02013-01-14 00:35:14 +00001469 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +00001470 bool IsTailCallRelease;
1471
Michael Gottesman97e3df02013-01-14 00:35:14 +00001472 /// If the Calls are objc_release calls and they all have a
1473 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +00001474 MDNode *ReleaseMetadata;
1475
Michael Gottesman97e3df02013-01-14 00:35:14 +00001476 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +00001477 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1478 SmallPtrSet<Instruction *, 2> Calls;
1479
Michael Gottesman97e3df02013-01-14 00:35:14 +00001480 /// The set of optimal insert positions for moving calls in the opposite
1481 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +00001482 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1483
1484 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +00001485 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +00001486 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +00001487 ReleaseMetadata(0) {}
1488
1489 void clear();
1490 };
1491}
1492
1493void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +00001494 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +00001495 IsRetainBlock = false;
1496 IsTailCallRelease = false;
1497 ReleaseMetadata = 0;
1498 Calls.clear();
1499 ReverseInsertPts.clear();
1500}
1501
1502namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001503 /// \brief This class summarizes several per-pointer runtime properties which
1504 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +00001505 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001506 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +00001507 bool KnownPositiveRefCount;
1508
Michael Gottesman97e3df02013-01-14 00:35:14 +00001509 /// True of we've seen an opportunity for partial RR elimination, such as
1510 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +00001511 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +00001512
Michael Gottesman97e3df02013-01-14 00:35:14 +00001513 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +00001514 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +00001515
1516 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +00001517 /// Unidirectional information about the current sequence.
1518 ///
John McCalld935e9c2011-06-15 23:37:01 +00001519 /// TODO: Encapsulate this better.
1520 RRInfo RRI;
1521
Dan Gohmandf476e52012-09-04 23:16:20 +00001522 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +00001523 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +00001524
Dan Gohman62079b42012-04-25 00:50:46 +00001525 void SetKnownPositiveRefCount() {
1526 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +00001527 }
1528
Dan Gohman62079b42012-04-25 00:50:46 +00001529 void ClearRefCount() {
1530 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +00001531 }
1532
John McCalld935e9c2011-06-15 23:37:01 +00001533 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +00001534 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001535 }
1536
1537 void SetSeq(Sequence NewSeq) {
1538 Seq = NewSeq;
1539 }
1540
John McCalld935e9c2011-06-15 23:37:01 +00001541 Sequence GetSeq() const {
1542 return Seq;
1543 }
1544
1545 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +00001546 ResetSequenceProgress(S_None);
1547 }
1548
1549 void ResetSequenceProgress(Sequence NewSeq) {
1550 Seq = NewSeq;
1551 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001552 RRI.clear();
1553 }
1554
1555 void Merge(const PtrState &Other, bool TopDown);
1556 };
1557}
1558
1559void
1560PtrState::Merge(const PtrState &Other, bool TopDown) {
1561 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +00001562 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +00001563
1564 // We can't merge a plain objc_retain with an objc_retainBlock.
1565 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1566 Seq = S_None;
1567
Dan Gohman1736c142011-10-17 18:48:25 +00001568 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +00001569 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +00001570 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +00001571 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +00001572 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +00001573 // If we're doing a merge on a path that's previously seen a partial
1574 // merge, conservatively drop the sequence, to avoid doing partial
1575 // RR elimination. If the branch predicates for the two merge differ,
1576 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +00001577 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +00001578 } else {
1579 // Conservatively merge the ReleaseMetadata information.
1580 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1581 RRI.ReleaseMetadata = 0;
1582
Dan Gohmanb3894012011-08-19 00:26:36 +00001583 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +00001584 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1585 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +00001586 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +00001587
1588 // Merge the insert point sets. If there are any differences,
1589 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +00001590 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +00001591 for (SmallPtrSet<Instruction *, 2>::const_iterator
1592 I = Other.RRI.ReverseInsertPts.begin(),
1593 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +00001594 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +00001595 }
1596}
1597
1598namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001599 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +00001600 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001601 /// The number of unique control paths from the entry which can reach this
1602 /// block.
John McCalld935e9c2011-06-15 23:37:01 +00001603 unsigned TopDownPathCount;
1604
Michael Gottesman97e3df02013-01-14 00:35:14 +00001605 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +00001606 unsigned BottomUpPathCount;
1607
Michael Gottesman97e3df02013-01-14 00:35:14 +00001608 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +00001609 typedef MapVector<const Value *, PtrState> MapTy;
1610
Michael Gottesman97e3df02013-01-14 00:35:14 +00001611 /// The top-down traversal uses this to record information known about a
1612 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001613 MapTy PerPtrTopDown;
1614
Michael Gottesman97e3df02013-01-14 00:35:14 +00001615 /// The bottom-up traversal uses this to record information known about a
1616 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +00001617 MapTy PerPtrBottomUp;
1618
Michael Gottesman97e3df02013-01-14 00:35:14 +00001619 /// Effective predecessors of the current block ignoring ignorable edges and
1620 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001621 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +00001622 /// Effective successors of the current block ignoring ignorable edges and
1623 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001624 SmallVector<BasicBlock *, 2> Succs;
1625
John McCalld935e9c2011-06-15 23:37:01 +00001626 public:
1627 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1628
1629 typedef MapTy::iterator ptr_iterator;
1630 typedef MapTy::const_iterator ptr_const_iterator;
1631
1632 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1633 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1634 ptr_const_iterator top_down_ptr_begin() const {
1635 return PerPtrTopDown.begin();
1636 }
1637 ptr_const_iterator top_down_ptr_end() const {
1638 return PerPtrTopDown.end();
1639 }
1640
1641 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1642 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1643 ptr_const_iterator bottom_up_ptr_begin() const {
1644 return PerPtrBottomUp.begin();
1645 }
1646 ptr_const_iterator bottom_up_ptr_end() const {
1647 return PerPtrBottomUp.end();
1648 }
1649
Michael Gottesman97e3df02013-01-14 00:35:14 +00001650 /// Mark this block as being an entry block, which has one path from the
1651 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +00001652 void SetAsEntry() { TopDownPathCount = 1; }
1653
Michael Gottesman97e3df02013-01-14 00:35:14 +00001654 /// Mark this block as being an exit block, which has one path to an exit by
1655 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +00001656 void SetAsExit() { BottomUpPathCount = 1; }
1657
1658 PtrState &getPtrTopDownState(const Value *Arg) {
1659 return PerPtrTopDown[Arg];
1660 }
1661
1662 PtrState &getPtrBottomUpState(const Value *Arg) {
1663 return PerPtrBottomUp[Arg];
1664 }
1665
1666 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +00001667 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +00001668 }
1669
1670 void clearTopDownPointers() {
1671 PerPtrTopDown.clear();
1672 }
1673
1674 void InitFromPred(const BBState &Other);
1675 void InitFromSucc(const BBState &Other);
1676 void MergePred(const BBState &Other);
1677 void MergeSucc(const BBState &Other);
1678
Michael Gottesman97e3df02013-01-14 00:35:14 +00001679 /// Return the number of possible unique paths from an entry to an exit
1680 /// which pass through this block. This is only valid after both the
1681 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +00001682 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001683 assert(TopDownPathCount != 0);
1684 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +00001685 return TopDownPathCount * BottomUpPathCount;
1686 }
Dan Gohman12130272011-08-12 00:26:31 +00001687
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001688 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +00001689 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00001690 edge_iterator pred_begin() { return Preds.begin(); }
1691 edge_iterator pred_end() { return Preds.end(); }
1692 edge_iterator succ_begin() { return Succs.begin(); }
1693 edge_iterator succ_end() { return Succs.end(); }
1694
1695 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1696 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1697
1698 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +00001699 };
1700}
1701
1702void BBState::InitFromPred(const BBState &Other) {
1703 PerPtrTopDown = Other.PerPtrTopDown;
1704 TopDownPathCount = Other.TopDownPathCount;
1705}
1706
1707void BBState::InitFromSucc(const BBState &Other) {
1708 PerPtrBottomUp = Other.PerPtrBottomUp;
1709 BottomUpPathCount = Other.BottomUpPathCount;
1710}
1711
Michael Gottesman97e3df02013-01-14 00:35:14 +00001712/// The top-down traversal uses this to merge information about predecessors to
1713/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001714void BBState::MergePred(const BBState &Other) {
1715 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1716 // loop backedge. Loop backedges are special.
1717 TopDownPathCount += Other.TopDownPathCount;
1718
Michael Gottesman4385edf2013-01-14 01:47:53 +00001719 // Check for overflow. If we have overflow, fall back to conservative
1720 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001721 if (TopDownPathCount < Other.TopDownPathCount) {
1722 clearTopDownPointers();
1723 return;
1724 }
1725
John McCalld935e9c2011-06-15 23:37:01 +00001726 // For each entry in the other set, if our set has an entry with the same key,
1727 // merge the entries. Otherwise, copy the entry and merge it with an empty
1728 // entry.
1729 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1730 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1731 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1732 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1733 /*TopDown=*/true);
1734 }
1735
Dan Gohman7e315fc32011-08-11 21:06:32 +00001736 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +00001737 // same key, force it to merge with an empty entry.
1738 for (ptr_iterator MI = top_down_ptr_begin(),
1739 ME = top_down_ptr_end(); MI != ME; ++MI)
1740 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1741 MI->second.Merge(PtrState(), /*TopDown=*/true);
1742}
1743
Michael Gottesman97e3df02013-01-14 00:35:14 +00001744/// The bottom-up traversal uses this to merge information about successors to
1745/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001746void BBState::MergeSucc(const BBState &Other) {
1747 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1748 // loop backedge. Loop backedges are special.
1749 BottomUpPathCount += Other.BottomUpPathCount;
1750
Michael Gottesman4385edf2013-01-14 01:47:53 +00001751 // Check for overflow. If we have overflow, fall back to conservative
1752 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001753 if (BottomUpPathCount < Other.BottomUpPathCount) {
1754 clearBottomUpPointers();
1755 return;
1756 }
1757
John McCalld935e9c2011-06-15 23:37:01 +00001758 // For each entry in the other set, if our set has an entry with the
1759 // same key, merge the entries. Otherwise, copy the entry and merge
1760 // it with an empty entry.
1761 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1762 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1763 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1764 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1765 /*TopDown=*/false);
1766 }
1767
Dan Gohman7e315fc32011-08-11 21:06:32 +00001768 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +00001769 // with the same key, force it to merge with an empty entry.
1770 for (ptr_iterator MI = bottom_up_ptr_begin(),
1771 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1772 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1773 MI->second.Merge(PtrState(), /*TopDown=*/false);
1774}
1775
1776namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001777 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001778 class ObjCARCOpt : public FunctionPass {
1779 bool Changed;
1780 ProvenanceAnalysis PA;
1781
Michael Gottesman97e3df02013-01-14 00:35:14 +00001782 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001783 bool Run;
1784
Michael Gottesman97e3df02013-01-14 00:35:14 +00001785 /// Declarations for ObjC runtime functions, for use in creating calls to
1786 /// them. These are initialized lazily to avoid cluttering up the Module
1787 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001788
Michael Gottesman97e3df02013-01-14 00:35:14 +00001789 /// Declaration for ObjC runtime function
1790 /// objc_retainAutoreleasedReturnValue.
1791 Constant *RetainRVCallee;
1792 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1793 Constant *AutoreleaseRVCallee;
1794 /// Declaration for ObjC runtime function objc_release.
1795 Constant *ReleaseCallee;
1796 /// Declaration for ObjC runtime function objc_retain.
1797 Constant *RetainCallee;
1798 /// Declaration for ObjC runtime function objc_retainBlock.
1799 Constant *RetainBlockCallee;
1800 /// Declaration for ObjC runtime function objc_autorelease.
1801 Constant *AutoreleaseCallee;
1802
1803 /// Flags which determine whether each of the interesting runtine functions
1804 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001805 unsigned UsedInThisFunction;
1806
Michael Gottesman97e3df02013-01-14 00:35:14 +00001807 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001808 unsigned ImpreciseReleaseMDKind;
1809
Michael Gottesman97e3df02013-01-14 00:35:14 +00001810 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001811 unsigned CopyOnEscapeMDKind;
1812
Michael Gottesman97e3df02013-01-14 00:35:14 +00001813 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001814 unsigned NoObjCARCExceptionsMDKind;
1815
John McCalld935e9c2011-06-15 23:37:01 +00001816 Constant *getRetainRVCallee(Module *M);
1817 Constant *getAutoreleaseRVCallee(Module *M);
1818 Constant *getReleaseCallee(Module *M);
1819 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001820 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001821 Constant *getAutoreleaseCallee(Module *M);
1822
Dan Gohman728db492012-01-13 00:39:07 +00001823 bool IsRetainBlockOptimizable(const Instruction *Inst);
1824
John McCalld935e9c2011-06-15 23:37:01 +00001825 void OptimizeRetainCall(Function &F, Instruction *Retain);
1826 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001827 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1828 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001829 void OptimizeIndividualCalls(Function &F);
1830
1831 void CheckForCFGHazards(const BasicBlock *BB,
1832 DenseMap<const BasicBlock *, BBState> &BBStates,
1833 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001834 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001835 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001836 MapVector<Value *, RRInfo> &Retains,
1837 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001838 bool VisitBottomUp(BasicBlock *BB,
1839 DenseMap<const BasicBlock *, BBState> &BBStates,
1840 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001841 bool VisitInstructionTopDown(Instruction *Inst,
1842 DenseMap<Value *, RRInfo> &Releases,
1843 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001844 bool VisitTopDown(BasicBlock *BB,
1845 DenseMap<const BasicBlock *, BBState> &BBStates,
1846 DenseMap<Value *, RRInfo> &Releases);
1847 bool Visit(Function &F,
1848 DenseMap<const BasicBlock *, BBState> &BBStates,
1849 MapVector<Value *, RRInfo> &Retains,
1850 DenseMap<Value *, RRInfo> &Releases);
1851
1852 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1853 MapVector<Value *, RRInfo> &Retains,
1854 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001855 SmallVectorImpl<Instruction *> &DeadInsts,
1856 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001857
Michael Gottesman9de6f962013-01-22 21:49:00 +00001858 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1859 MapVector<Value *, RRInfo> &Retains,
1860 DenseMap<Value *, RRInfo> &Releases,
1861 Module *M,
1862 SmallVector<Instruction *, 4> &NewRetains,
1863 SmallVector<Instruction *, 4> &NewReleases,
1864 SmallVector<Instruction *, 8> &DeadInsts,
1865 RRInfo &RetainsToMove,
1866 RRInfo &ReleasesToMove,
1867 Value *Arg,
1868 bool KnownSafe,
1869 bool &AnyPairsCompletelyEliminated);
1870
John McCalld935e9c2011-06-15 23:37:01 +00001871 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1872 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001873 DenseMap<Value *, RRInfo> &Releases,
1874 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001875
1876 void OptimizeWeakCalls(Function &F);
1877
1878 bool OptimizeSequences(Function &F);
1879
1880 void OptimizeReturns(Function &F);
1881
1882 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1883 virtual bool doInitialization(Module &M);
1884 virtual bool runOnFunction(Function &F);
1885 virtual void releaseMemory();
1886
1887 public:
1888 static char ID;
1889 ObjCARCOpt() : FunctionPass(ID) {
1890 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1891 }
1892 };
1893}
1894
1895char ObjCARCOpt::ID = 0;
1896INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1897 "objc-arc", "ObjC ARC optimization", false, false)
1898INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1899INITIALIZE_PASS_END(ObjCARCOpt,
1900 "objc-arc", "ObjC ARC optimization", false, false)
1901
1902Pass *llvm::createObjCARCOptPass() {
1903 return new ObjCARCOpt();
1904}
1905
1906void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1907 AU.addRequired<ObjCARCAliasAnalysis>();
1908 AU.addRequired<AliasAnalysis>();
1909 // ARC optimization doesn't currently split critical edges.
1910 AU.setPreservesCFG();
1911}
1912
Dan Gohman728db492012-01-13 00:39:07 +00001913bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1914 // Without the magic metadata tag, we have to assume this might be an
1915 // objc_retainBlock call inserted to convert a block pointer to an id,
1916 // in which case it really is needed.
1917 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1918 return false;
1919
1920 // If the pointer "escapes" (not including being used in a call),
1921 // the copy may be needed.
1922 if (DoesObjCBlockEscape(Inst))
1923 return false;
1924
1925 // Otherwise, it's not needed.
1926 return true;
1927}
1928
John McCalld935e9c2011-06-15 23:37:01 +00001929Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1930 if (!RetainRVCallee) {
1931 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001932 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001933 Type *Params[] = { I8X };
1934 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001935 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001936 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1937 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001938 RetainRVCallee =
1939 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001940 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001941 }
1942 return RetainRVCallee;
1943}
1944
1945Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1946 if (!AutoreleaseRVCallee) {
1947 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001948 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001949 Type *Params[] = { I8X };
1950 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001951 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001952 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1953 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001954 AutoreleaseRVCallee =
1955 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001956 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001957 }
1958 return AutoreleaseRVCallee;
1959}
1960
1961Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1962 if (!ReleaseCallee) {
1963 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001964 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001965 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001966 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1967 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001968 ReleaseCallee =
1969 M->getOrInsertFunction(
1970 "objc_release",
1971 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001972 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001973 }
1974 return ReleaseCallee;
1975}
1976
1977Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1978 if (!RetainCallee) {
1979 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001980 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001981 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001982 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1983 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001984 RetainCallee =
1985 M->getOrInsertFunction(
1986 "objc_retain",
1987 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001988 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001989 }
1990 return RetainCallee;
1991}
1992
Dan Gohman6320f522011-07-22 22:29:21 +00001993Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1994 if (!RetainBlockCallee) {
1995 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001996 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001997 // objc_retainBlock is not nounwind because it calls user copy constructors
1998 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001999 RetainBlockCallee =
2000 M->getOrInsertFunction(
2001 "objc_retainBlock",
2002 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00002003 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00002004 }
2005 return RetainBlockCallee;
2006}
2007
John McCalld935e9c2011-06-15 23:37:01 +00002008Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
2009 if (!AutoreleaseCallee) {
2010 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00002011 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002012 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00002013 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
2014 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00002015 AutoreleaseCallee =
2016 M->getOrInsertFunction(
2017 "objc_autorelease",
2018 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002019 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00002020 }
2021 return AutoreleaseCallee;
2022}
2023
Michael Gottesman97e3df02013-01-14 00:35:14 +00002024/// Test whether the given value is possible a reference-counted pointer,
2025/// including tests which utilize AliasAnalysis.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002026static bool IsPotentialRetainableObjPtr(const Value *Op, AliasAnalysis &AA) {
Dan Gohmandf476e52012-09-04 23:16:20 +00002027 // First make the rudimentary check.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002028 if (!IsPotentialRetainableObjPtr(Op))
Dan Gohmandf476e52012-09-04 23:16:20 +00002029 return false;
2030
2031 // Objects in constant memory are not reference-counted.
2032 if (AA.pointsToConstantMemory(Op))
2033 return false;
2034
2035 // Pointers in constant memory are not pointing to reference-counted objects.
2036 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
2037 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
2038 return false;
2039
2040 // Otherwise assume the worst.
2041 return true;
2042}
2043
Michael Gottesman97e3df02013-01-14 00:35:14 +00002044/// Test whether the given instruction can result in a reference count
2045/// modification (positive or negative) for the pointer's object.
John McCalld935e9c2011-06-15 23:37:01 +00002046static bool
2047CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
2048 ProvenanceAnalysis &PA, InstructionClass Class) {
2049 switch (Class) {
2050 case IC_Autorelease:
2051 case IC_AutoreleaseRV:
2052 case IC_User:
2053 // These operations never directly modify a reference count.
2054 return false;
2055 default: break;
2056 }
2057
2058 ImmutableCallSite CS = static_cast<const Value *>(Inst);
2059 assert(CS && "Only calls can alter reference counts!");
2060
2061 // See if AliasAnalysis can help us with the call.
2062 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
2063 if (AliasAnalysis::onlyReadsMemory(MRB))
2064 return false;
2065 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
2066 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2067 I != E; ++I) {
2068 const Value *Op = *I;
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002069 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002070 return true;
2071 }
2072 return false;
2073 }
2074
2075 // Assume the worst.
2076 return true;
2077}
2078
Michael Gottesman97e3df02013-01-14 00:35:14 +00002079/// Test whether the given instruction can "use" the given pointer's object in a
2080/// way that requires the reference count to be positive.
John McCalld935e9c2011-06-15 23:37:01 +00002081static bool
2082CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2083 InstructionClass Class) {
2084 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2085 if (Class == IC_Call)
2086 return false;
2087
2088 // Consider various instructions which may have pointer arguments which are
2089 // not "uses".
2090 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2091 // Comparing a pointer with null, or any other constant, isn't really a use,
2092 // because we don't care what the pointer points to, or about the values
2093 // of any other dynamic reference-counted pointers.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002094 if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
John McCalld935e9c2011-06-15 23:37:01 +00002095 return false;
2096 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2097 // For calls, just check the arguments (and not the callee operand).
2098 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2099 OE = CS.arg_end(); OI != OE; ++OI) {
2100 const Value *Op = *OI;
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002101 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002102 return true;
2103 }
2104 return false;
2105 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2106 // Special-case stores, because we don't care about the stored value, just
2107 // the store address.
2108 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2109 // If we can't tell what the underlying object was, assume there is a
2110 // dependence.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002111 return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCalld935e9c2011-06-15 23:37:01 +00002112 }
2113
2114 // Check each operand for a match.
2115 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2116 OI != OE; ++OI) {
2117 const Value *Op = *OI;
Michael Gottesman5300cdd2013-01-27 06:19:48 +00002118 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00002119 return true;
2120 }
2121 return false;
2122}
2123
Michael Gottesman97e3df02013-01-14 00:35:14 +00002124/// Test whether the given instruction can autorelease any pointer or cause an
2125/// autoreleasepool pop.
John McCalld935e9c2011-06-15 23:37:01 +00002126static bool
2127CanInterruptRV(InstructionClass Class) {
2128 switch (Class) {
2129 case IC_AutoreleasepoolPop:
2130 case IC_CallOrUser:
2131 case IC_Call:
2132 case IC_Autorelease:
2133 case IC_AutoreleaseRV:
2134 case IC_FusedRetainAutorelease:
2135 case IC_FusedRetainAutoreleaseRV:
2136 return true;
2137 default:
2138 return false;
2139 }
2140}
2141
2142namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002143 /// \enum DependenceKind
2144 /// \brief Defines different dependence kinds among various ARC constructs.
2145 ///
2146 /// There are several kinds of dependence-like concepts in use here.
2147 ///
John McCalld935e9c2011-06-15 23:37:01 +00002148 enum DependenceKind {
2149 NeedsPositiveRetainCount,
Dan Gohman8478d762012-04-13 00:59:57 +00002150 AutoreleasePoolBoundary,
John McCalld935e9c2011-06-15 23:37:01 +00002151 CanChangeRetainCount,
2152 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2153 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2154 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2155 };
2156}
2157
Michael Gottesman97e3df02013-01-14 00:35:14 +00002158/// Test if there can be dependencies on Inst through Arg. This function only
2159/// tests dependencies relevant for removing pairs of calls.
John McCalld935e9c2011-06-15 23:37:01 +00002160static bool
2161Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2162 ProvenanceAnalysis &PA) {
2163 // If we've reached the definition of Arg, stop.
2164 if (Inst == Arg)
2165 return true;
2166
2167 switch (Flavor) {
2168 case NeedsPositiveRetainCount: {
2169 InstructionClass Class = GetInstructionClass(Inst);
2170 switch (Class) {
2171 case IC_AutoreleasepoolPop:
2172 case IC_AutoreleasepoolPush:
2173 case IC_None:
2174 return false;
2175 default:
2176 return CanUse(Inst, Arg, PA, Class);
2177 }
2178 }
2179
Dan Gohman8478d762012-04-13 00:59:57 +00002180 case AutoreleasePoolBoundary: {
2181 InstructionClass Class = GetInstructionClass(Inst);
2182 switch (Class) {
2183 case IC_AutoreleasepoolPop:
2184 case IC_AutoreleasepoolPush:
2185 // These mark the end and begin of an autorelease pool scope.
2186 return true;
2187 default:
2188 // Nothing else does this.
2189 return false;
2190 }
2191 }
2192
John McCalld935e9c2011-06-15 23:37:01 +00002193 case CanChangeRetainCount: {
2194 InstructionClass Class = GetInstructionClass(Inst);
2195 switch (Class) {
2196 case IC_AutoreleasepoolPop:
2197 // Conservatively assume this can decrement any count.
2198 return true;
2199 case IC_AutoreleasepoolPush:
2200 case IC_None:
2201 return false;
2202 default:
2203 return CanAlterRefCount(Inst, Arg, PA, Class);
2204 }
2205 }
2206
2207 case RetainAutoreleaseDep:
2208 switch (GetBasicInstructionClass(Inst)) {
2209 case IC_AutoreleasepoolPop:
Dan Gohman8478d762012-04-13 00:59:57 +00002210 case IC_AutoreleasepoolPush:
John McCalld935e9c2011-06-15 23:37:01 +00002211 // Don't merge an objc_autorelease with an objc_retain inside a different
2212 // autoreleasepool scope.
2213 return true;
2214 case IC_Retain:
2215 case IC_RetainRV:
2216 // Check for a retain of the same pointer for merging.
2217 return GetObjCArg(Inst) == Arg;
2218 default:
2219 // Nothing else matters for objc_retainAutorelease formation.
2220 return false;
2221 }
John McCalld935e9c2011-06-15 23:37:01 +00002222
2223 case RetainAutoreleaseRVDep: {
2224 InstructionClass Class = GetBasicInstructionClass(Inst);
2225 switch (Class) {
2226 case IC_Retain:
2227 case IC_RetainRV:
2228 // Check for a retain of the same pointer for merging.
2229 return GetObjCArg(Inst) == Arg;
2230 default:
2231 // Anything that can autorelease interrupts
2232 // retainAutoreleaseReturnValue formation.
2233 return CanInterruptRV(Class);
2234 }
John McCalld935e9c2011-06-15 23:37:01 +00002235 }
2236
2237 case RetainRVDep:
2238 return CanInterruptRV(GetBasicInstructionClass(Inst));
2239 }
2240
2241 llvm_unreachable("Invalid dependence flavor");
John McCalld935e9c2011-06-15 23:37:01 +00002242}
2243
Michael Gottesman97e3df02013-01-14 00:35:14 +00002244/// Walk up the CFG from StartPos (which is in StartBB) and find local and
2245/// non-local dependencies on Arg.
2246///
John McCalld935e9c2011-06-15 23:37:01 +00002247/// TODO: Cache results?
2248static void
2249FindDependencies(DependenceKind Flavor,
2250 const Value *Arg,
2251 BasicBlock *StartBB, Instruction *StartInst,
2252 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2253 SmallPtrSet<const BasicBlock *, 4> &Visited,
2254 ProvenanceAnalysis &PA) {
2255 BasicBlock::iterator StartPos = StartInst;
2256
2257 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2258 Worklist.push_back(std::make_pair(StartBB, StartPos));
2259 do {
2260 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2261 Worklist.pop_back_val();
2262 BasicBlock *LocalStartBB = Pair.first;
2263 BasicBlock::iterator LocalStartPos = Pair.second;
2264 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2265 for (;;) {
2266 if (LocalStartPos == StartBBBegin) {
2267 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2268 if (PI == PE)
2269 // If we've reached the function entry, produce a null dependence.
2270 DependingInstructions.insert(0);
2271 else
2272 // Add the predecessors to the worklist.
2273 do {
2274 BasicBlock *PredBB = *PI;
2275 if (Visited.insert(PredBB))
2276 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2277 } while (++PI != PE);
2278 break;
2279 }
2280
2281 Instruction *Inst = --LocalStartPos;
2282 if (Depends(Flavor, Inst, Arg, PA)) {
2283 DependingInstructions.insert(Inst);
2284 break;
2285 }
2286 }
2287 } while (!Worklist.empty());
2288
2289 // Determine whether the original StartBB post-dominates all of the blocks we
2290 // visited. If not, insert a sentinal indicating that most optimizations are
2291 // not safe.
2292 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2293 E = Visited.end(); I != E; ++I) {
2294 const BasicBlock *BB = *I;
2295 if (BB == StartBB)
2296 continue;
2297 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2298 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2299 const BasicBlock *Succ = *SI;
2300 if (Succ != StartBB && !Visited.count(Succ)) {
2301 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2302 return;
2303 }
2304 }
2305 }
2306}
2307
2308static bool isNullOrUndef(const Value *V) {
2309 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2310}
2311
2312static bool isNoopInstruction(const Instruction *I) {
2313 return isa<BitCastInst>(I) ||
2314 (isa<GetElementPtrInst>(I) &&
2315 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2316}
2317
Michael Gottesman97e3df02013-01-14 00:35:14 +00002318/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2319/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00002320void
2321ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00002322 ImmutableCallSite CS(GetObjCArg(Retain));
2323 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00002324 if (!Call) return;
2325 if (Call->getParent() != Retain->getParent()) return;
2326
2327 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00002328 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002329 ++I;
2330 while (isNoopInstruction(I)) ++I;
2331 if (&*I != Retain)
2332 return;
2333
2334 // Turn it to an objc_retainAutoreleasedReturnValue..
2335 Changed = true;
2336 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002337
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002338 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +00002339 "objc_retain => objc_retainAutoreleasedReturnValue"
2340 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002341 " Old: "
2342 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002343
John McCalld935e9c2011-06-15 23:37:01 +00002344 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00002345
2346 DEBUG(dbgs() << " New: "
2347 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002348}
2349
Michael Gottesman97e3df02013-01-14 00:35:14 +00002350/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2351/// not a return value. Or, if it can be paired with an
2352/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00002353bool
2354ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002355 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00002356 const Value *Arg = GetObjCArg(RetainRV);
2357 ImmutableCallSite CS(Arg);
2358 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00002359 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00002360 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00002361 ++I;
2362 while (isNoopInstruction(I)) ++I;
2363 if (&*I == RetainRV)
2364 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00002365 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002366 BasicBlock *RetainRVParent = RetainRV->getParent();
2367 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00002368 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002369 while (isNoopInstruction(I)) ++I;
2370 if (&*I == RetainRV)
2371 return false;
2372 }
John McCalld935e9c2011-06-15 23:37:01 +00002373 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00002374 }
John McCalld935e9c2011-06-15 23:37:01 +00002375
2376 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2377 // pointer. In this case, we can delete the pair.
2378 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2379 if (I != Begin) {
2380 do --I; while (I != Begin && isNoopInstruction(I));
2381 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2382 GetObjCArg(I) == Arg) {
2383 Changed = true;
2384 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002385
Michael Gottesman5c32ce92013-01-05 17:55:35 +00002386 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2387 << " Erasing " << *RetainRV
2388 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002389
John McCalld935e9c2011-06-15 23:37:01 +00002390 EraseInstruction(I);
2391 EraseInstruction(RetainRV);
2392 return true;
2393 }
2394 }
2395
2396 // Turn it to a plain objc_retain.
2397 Changed = true;
2398 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00002399
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002400 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2401 "objc_retainAutoreleasedReturnValue => "
2402 "objc_retain since the operand is not a return value.\n"
2403 " Old: "
2404 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002405
John McCalld935e9c2011-06-15 23:37:01 +00002406 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00002407
2408 DEBUG(dbgs() << " New: "
2409 << *RetainRV << "\n");
2410
John McCalld935e9c2011-06-15 23:37:01 +00002411 return false;
2412}
2413
Michael Gottesman97e3df02013-01-14 00:35:14 +00002414/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2415/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00002416void
Michael Gottesman556ff612013-01-12 01:25:19 +00002417ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2418 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00002419 // Check for a return of the pointer value.
2420 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00002421 SmallVector<const Value *, 2> Users;
2422 Users.push_back(Ptr);
2423 do {
2424 Ptr = Users.pop_back_val();
2425 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2426 UI != UE; ++UI) {
2427 const User *I = *UI;
2428 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2429 return;
2430 if (isa<BitCastInst>(I))
2431 Users.push_back(I);
2432 }
2433 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00002434
2435 Changed = true;
2436 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00002437
2438 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2439 "objc_autoreleaseReturnValue => "
2440 "objc_autorelease since its operand is not used as a return "
2441 "value.\n"
2442 " Old: "
2443 << *AutoreleaseRV << "\n");
2444
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002445 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2446 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00002447 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002448 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00002449 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00002450
Michael Gottesman1bf69082013-01-06 21:07:11 +00002451 DEBUG(dbgs() << " New: "
2452 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002453
John McCalld935e9c2011-06-15 23:37:01 +00002454}
2455
Michael Gottesman97e3df02013-01-14 00:35:14 +00002456/// Visit each call, one at a time, and make simplifications without doing any
2457/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00002458void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2459 // Reset all the flags in preparation for recomputing them.
2460 UsedInThisFunction = 0;
2461
2462 // Visit all objc_* calls in F.
2463 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2464 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002465
John McCalld935e9c2011-06-15 23:37:01 +00002466 InstructionClass Class = GetBasicInstructionClass(Inst);
2467
Michael Gottesmand359e062013-01-18 03:08:39 +00002468 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
2469 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00002470
John McCalld935e9c2011-06-15 23:37:01 +00002471 switch (Class) {
2472 default: break;
2473
2474 // Delete no-op casts. These function calls have special semantics, but
2475 // the semantics are entirely implemented via lowering in the front-end,
2476 // so by the time they reach the optimizer, they are just no-op calls
2477 // which return their argument.
2478 //
2479 // There are gray areas here, as the ability to cast reference-counted
2480 // pointers to raw void* and back allows code to break ARC assumptions,
2481 // however these are currently considered to be unimportant.
2482 case IC_NoopCast:
2483 Changed = true;
2484 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00002485 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2486 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002487 EraseInstruction(Inst);
2488 continue;
2489
2490 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2491 case IC_StoreWeak:
2492 case IC_LoadWeak:
2493 case IC_LoadWeakRetained:
2494 case IC_InitWeak:
2495 case IC_DestroyWeak: {
2496 CallInst *CI = cast<CallInst>(Inst);
2497 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002498 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002499 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002500 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2501 Constant::getNullValue(Ty),
2502 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00002503 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002504 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2505 "pointer-to-weak-pointer is undefined behavior.\n"
2506 " Old = " << *CI <<
2507 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00002508 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002509 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002510 CI->eraseFromParent();
2511 continue;
2512 }
2513 break;
2514 }
2515 case IC_CopyWeak:
2516 case IC_MoveWeak: {
2517 CallInst *CI = cast<CallInst>(Inst);
2518 if (isNullOrUndef(CI->getArgOperand(0)) ||
2519 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00002520 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00002521 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002522 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2523 Constant::getNullValue(Ty),
2524 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002525
2526 llvm::Value *NewValue = UndefValue::get(CI->getType());
2527 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2528 "pointer-to-weak-pointer is undefined behavior.\n"
2529 " Old = " << *CI <<
2530 "\n New = " <<
2531 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002532
Michael Gottesmanfec61c02013-01-06 21:54:30 +00002533 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00002534 CI->eraseFromParent();
2535 continue;
2536 }
2537 break;
2538 }
2539 case IC_Retain:
2540 OptimizeRetainCall(F, Inst);
2541 break;
2542 case IC_RetainRV:
2543 if (OptimizeRetainRVCall(F, Inst))
2544 continue;
2545 break;
2546 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00002547 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00002548 break;
2549 }
2550
2551 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2552 if (IsAutorelease(Class) && Inst->use_empty()) {
2553 CallInst *Call = cast<CallInst>(Inst);
2554 const Value *Arg = Call->getArgOperand(0);
2555 Arg = FindSingleUseIdentifiedObject(Arg);
2556 if (Arg) {
2557 Changed = true;
2558 ++NumAutoreleases;
2559
2560 // Create the declaration lazily.
2561 LLVMContext &C = Inst->getContext();
2562 CallInst *NewCall =
2563 CallInst::Create(getReleaseCallee(F.getParent()),
2564 Call->getArgOperand(0), "", Call);
2565 NewCall->setMetadata(ImpreciseReleaseMDKind,
2566 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00002567
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002568 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2569 "objc_autorelease(x) with objc_release(x) since x is "
2570 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00002571 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00002572 "\n New: " <<
2573 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00002574
John McCalld935e9c2011-06-15 23:37:01 +00002575 EraseInstruction(Call);
2576 Inst = NewCall;
2577 Class = IC_Release;
2578 }
2579 }
2580
2581 // For functions which can never be passed stack arguments, add
2582 // a tail keyword.
2583 if (IsAlwaysTail(Class)) {
2584 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00002585 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2586 " to function since it can never be passed stack args: " << *Inst <<
2587 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002588 cast<CallInst>(Inst)->setTailCall();
2589 }
2590
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002591 // Ensure that functions that can never have a "tail" keyword due to the
2592 // semantics of ARC truly do not do so.
2593 if (IsNeverTail(Class)) {
2594 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00002595 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2596 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00002597 "\n");
2598 cast<CallInst>(Inst)->setTailCall(false);
2599 }
2600
John McCalld935e9c2011-06-15 23:37:01 +00002601 // Set nounwind as needed.
2602 if (IsNoThrow(Class)) {
2603 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00002604 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2605 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002606 cast<CallInst>(Inst)->setDoesNotThrow();
2607 }
2608
2609 if (!IsNoopOnNull(Class)) {
2610 UsedInThisFunction |= 1 << Class;
2611 continue;
2612 }
2613
2614 const Value *Arg = GetObjCArg(Inst);
2615
2616 // ARC calls with null are no-ops. Delete them.
2617 if (isNullOrUndef(Arg)) {
2618 Changed = true;
2619 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00002620 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2621 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002622 EraseInstruction(Inst);
2623 continue;
2624 }
2625
2626 // Keep track of which of retain, release, autorelease, and retain_block
2627 // are actually present in this function.
2628 UsedInThisFunction |= 1 << Class;
2629
2630 // If Arg is a PHI, and one or more incoming values to the
2631 // PHI are null, and the call is control-equivalent to the PHI, and there
2632 // are no relevant side effects between the PHI and the call, the call
2633 // could be pushed up to just those paths with non-null incoming values.
2634 // For now, don't bother splitting critical edges for this.
2635 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2636 Worklist.push_back(std::make_pair(Inst, Arg));
2637 do {
2638 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2639 Inst = Pair.first;
2640 Arg = Pair.second;
2641
2642 const PHINode *PN = dyn_cast<PHINode>(Arg);
2643 if (!PN) continue;
2644
2645 // Determine if the PHI has any null operands, or any incoming
2646 // critical edges.
2647 bool HasNull = false;
2648 bool HasCriticalEdges = false;
2649 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2650 Value *Incoming =
2651 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2652 if (isNullOrUndef(Incoming))
2653 HasNull = true;
2654 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2655 .getNumSuccessors() != 1) {
2656 HasCriticalEdges = true;
2657 break;
2658 }
2659 }
2660 // If we have null operands and no critical edges, optimize.
2661 if (!HasCriticalEdges && HasNull) {
2662 SmallPtrSet<Instruction *, 4> DependingInstructions;
2663 SmallPtrSet<const BasicBlock *, 4> Visited;
2664
2665 // Check that there is nothing that cares about the reference
2666 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00002667 switch (Class) {
2668 case IC_Retain:
2669 case IC_RetainBlock:
2670 // These can always be moved up.
2671 break;
2672 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00002673 // These can't be moved across things that care about the retain
2674 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00002675 FindDependencies(NeedsPositiveRetainCount, Arg,
2676 Inst->getParent(), Inst,
2677 DependingInstructions, Visited, PA);
2678 break;
2679 case IC_Autorelease:
2680 // These can't be moved across autorelease pool scope boundaries.
2681 FindDependencies(AutoreleasePoolBoundary, Arg,
2682 Inst->getParent(), Inst,
2683 DependingInstructions, Visited, PA);
2684 break;
2685 case IC_RetainRV:
2686 case IC_AutoreleaseRV:
2687 // Don't move these; the RV optimization depends on the autoreleaseRV
2688 // being tail called, and the retainRV being immediately after a call
2689 // (which might still happen if we get lucky with codegen layout, but
2690 // it's not worth taking the chance).
2691 continue;
2692 default:
2693 llvm_unreachable("Invalid dependence flavor");
2694 }
2695
John McCalld935e9c2011-06-15 23:37:01 +00002696 if (DependingInstructions.size() == 1 &&
2697 *DependingInstructions.begin() == PN) {
2698 Changed = true;
2699 ++NumPartialNoops;
2700 // Clone the call into each predecessor that has a non-null value.
2701 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00002702 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00002703 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2704 Value *Incoming =
2705 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2706 if (!isNullOrUndef(Incoming)) {
2707 CallInst *Clone = cast<CallInst>(CInst->clone());
2708 Value *Op = PN->getIncomingValue(i);
2709 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2710 if (Op->getType() != ParamTy)
2711 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2712 Clone->setArgOperand(0, Op);
2713 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002714
2715 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2716 << *CInst << "\n"
2717 " And inserting "
2718 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002719 Worklist.push_back(std::make_pair(Clone, Incoming));
2720 }
2721 }
2722 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00002723 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002724 EraseInstruction(CInst);
2725 continue;
2726 }
2727 }
2728 } while (!Worklist.empty());
2729 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002730 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00002731}
2732
Michael Gottesman97e3df02013-01-14 00:35:14 +00002733/// Check for critical edges, loop boundaries, irreducible control flow, or
2734/// other CFG structures where moving code across the edge would result in it
2735/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00002736void
2737ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2738 DenseMap<const BasicBlock *, BBState> &BBStates,
2739 BBState &MyStates) const {
2740 // If any top-down local-use or possible-dec has a succ which is earlier in
2741 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00002742 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00002743 E = MyStates.top_down_ptr_end(); I != E; ++I)
2744 switch (I->second.GetSeq()) {
2745 default: break;
2746 case S_Use: {
2747 const Value *Arg = I->first;
2748 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2749 bool SomeSuccHasSame = false;
2750 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002751 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002752 succ_const_iterator SI(TI), SE(TI, false);
2753
Dan Gohman0155f302012-02-17 18:59:53 +00002754 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002755 Sequence SuccSSeq = S_None;
2756 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002757 // If VisitBottomUp has pointer information for this successor, take
2758 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002759 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2760 BBStates.find(*SI);
2761 assert(BBI != BBStates.end());
2762 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2763 SuccSSeq = SuccS.GetSeq();
2764 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002765 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00002766 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00002767 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00002768 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002769 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002770 break;
2771 }
Dan Gohman12130272011-08-12 00:26:31 +00002772 continue;
2773 }
John McCalld935e9c2011-06-15 23:37:01 +00002774 case S_Use:
2775 SomeSuccHasSame = true;
2776 break;
2777 case S_Stop:
2778 case S_Release:
2779 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00002780 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002781 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002782 break;
2783 case S_Retain:
2784 llvm_unreachable("bottom-up pointer in retain state!");
2785 }
Dan Gohman12130272011-08-12 00:26:31 +00002786 }
John McCalld935e9c2011-06-15 23:37:01 +00002787 // If the state at the other end of any of the successor edges
2788 // matches the current state, require all edges to match. This
2789 // guards against loops in the middle of a sequence.
2790 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002791 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002792 break;
John McCalld935e9c2011-06-15 23:37:01 +00002793 }
2794 case S_CanRelease: {
2795 const Value *Arg = I->first;
2796 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2797 bool SomeSuccHasSame = false;
2798 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002799 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002800 succ_const_iterator SI(TI), SE(TI, false);
2801
Dan Gohman0155f302012-02-17 18:59:53 +00002802 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002803 Sequence SuccSSeq = S_None;
2804 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002805 // If VisitBottomUp has pointer information for this successor, take
2806 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002807 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2808 BBStates.find(*SI);
2809 assert(BBI != BBStates.end());
2810 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2811 SuccSSeq = SuccS.GetSeq();
2812 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002813 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00002814 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00002815 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002816 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002817 break;
2818 }
Dan Gohman12130272011-08-12 00:26:31 +00002819 continue;
2820 }
John McCalld935e9c2011-06-15 23:37:01 +00002821 case S_CanRelease:
2822 SomeSuccHasSame = true;
2823 break;
2824 case S_Stop:
2825 case S_Release:
2826 case S_MovableRelease:
2827 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00002828 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002829 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002830 break;
2831 case S_Retain:
2832 llvm_unreachable("bottom-up pointer in retain state!");
2833 }
Dan Gohman12130272011-08-12 00:26:31 +00002834 }
John McCalld935e9c2011-06-15 23:37:01 +00002835 // If the state at the other end of any of the successor edges
2836 // matches the current state, require all edges to match. This
2837 // guards against loops in the middle of a sequence.
2838 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002839 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002840 break;
John McCalld935e9c2011-06-15 23:37:01 +00002841 }
2842 }
2843}
2844
2845bool
Dan Gohman817a7c62012-03-22 18:24:56 +00002846ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00002847 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00002848 MapVector<Value *, RRInfo> &Retains,
2849 BBState &MyStates) {
2850 bool NestingDetected = false;
2851 InstructionClass Class = GetInstructionClass(Inst);
2852 const Value *Arg = 0;
2853
2854 switch (Class) {
2855 case IC_Release: {
2856 Arg = GetObjCArg(Inst);
2857
2858 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2859
2860 // If we see two releases in a row on the same pointer. If so, make
2861 // a note, and we'll cicle back to revisit it after we've
2862 // hopefully eliminated the second release, which may allow us to
2863 // eliminate the first release too.
2864 // Theoretically we could implement removal of nested retain+release
2865 // pairs by making PtrState hold a stack of states, but this is
2866 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002867 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2868 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2869 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002870 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002871 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002872
Dan Gohman817a7c62012-03-22 18:24:56 +00002873 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00002874 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00002875 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00002876 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00002877 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2878 S.RRI.Calls.insert(Inst);
2879
Dan Gohmandf476e52012-09-04 23:16:20 +00002880 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002881 break;
2882 }
2883 case IC_RetainBlock:
2884 // An objc_retainBlock call with just a use may need to be kept,
2885 // because it may be copying a block from the stack to the heap.
2886 if (!IsRetainBlockOptimizable(Inst))
2887 break;
2888 // FALLTHROUGH
2889 case IC_Retain:
2890 case IC_RetainRV: {
2891 Arg = GetObjCArg(Inst);
2892
2893 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00002894 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002895
2896 switch (S.GetSeq()) {
2897 case S_Stop:
2898 case S_Release:
2899 case S_MovableRelease:
2900 case S_Use:
2901 S.RRI.ReverseInsertPts.clear();
2902 // FALL THROUGH
2903 case S_CanRelease:
2904 // Don't do retain+release tracking for IC_RetainRV, because it's
2905 // better to let it remain as the first instruction after a call.
2906 if (Class != IC_RetainRV) {
2907 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2908 Retains[Inst] = S.RRI;
2909 }
2910 S.ClearSequenceProgress();
2911 break;
2912 case S_None:
2913 break;
2914 case S_Retain:
2915 llvm_unreachable("bottom-up pointer in retain state!");
2916 }
2917 return NestingDetected;
2918 }
2919 case IC_AutoreleasepoolPop:
2920 // Conservatively, clear MyStates for all known pointers.
2921 MyStates.clearBottomUpPointers();
2922 return NestingDetected;
2923 case IC_AutoreleasepoolPush:
2924 case IC_None:
2925 // These are irrelevant.
2926 return NestingDetected;
2927 default:
2928 break;
2929 }
2930
2931 // Consider any other possible effects of this instruction on each
2932 // pointer being tracked.
2933 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2934 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2935 const Value *Ptr = MI->first;
2936 if (Ptr == Arg)
2937 continue; // Handled above.
2938 PtrState &S = MI->second;
2939 Sequence Seq = S.GetSeq();
2940
2941 // Check for possible releases.
2942 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00002943 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002944 switch (Seq) {
2945 case S_Use:
2946 S.SetSeq(S_CanRelease);
2947 continue;
2948 case S_CanRelease:
2949 case S_Release:
2950 case S_MovableRelease:
2951 case S_Stop:
2952 case S_None:
2953 break;
2954 case S_Retain:
2955 llvm_unreachable("bottom-up pointer in retain state!");
2956 }
2957 }
2958
2959 // Check for possible direct uses.
2960 switch (Seq) {
2961 case S_Release:
2962 case S_MovableRelease:
2963 if (CanUse(Inst, Ptr, PA, Class)) {
2964 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002965 // If this is an invoke instruction, we're scanning it as part of
2966 // one of its successor blocks, since we can't insert code after it
2967 // in its own block, and we don't want to split critical edges.
2968 if (isa<InvokeInst>(Inst))
2969 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2970 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002971 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002972 S.SetSeq(S_Use);
2973 } else if (Seq == S_Release &&
2974 (Class == IC_User || Class == IC_CallOrUser)) {
2975 // Non-movable releases depend on any possible objc pointer use.
2976 S.SetSeq(S_Stop);
2977 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002978 // As above; handle invoke specially.
2979 if (isa<InvokeInst>(Inst))
2980 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2981 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002982 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002983 }
2984 break;
2985 case S_Stop:
2986 if (CanUse(Inst, Ptr, PA, Class))
2987 S.SetSeq(S_Use);
2988 break;
2989 case S_CanRelease:
2990 case S_Use:
2991 case S_None:
2992 break;
2993 case S_Retain:
2994 llvm_unreachable("bottom-up pointer in retain state!");
2995 }
2996 }
2997
2998 return NestingDetected;
2999}
3000
3001bool
John McCalld935e9c2011-06-15 23:37:01 +00003002ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
3003 DenseMap<const BasicBlock *, BBState> &BBStates,
3004 MapVector<Value *, RRInfo> &Retains) {
3005 bool NestingDetected = false;
3006 BBState &MyStates = BBStates[BB];
3007
3008 // Merge the states from each successor to compute the initial state
3009 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00003010 BBState::edge_iterator SI(MyStates.succ_begin()),
3011 SE(MyStates.succ_end());
3012 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003013 const BasicBlock *Succ = *SI;
3014 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
3015 assert(I != BBStates.end());
3016 MyStates.InitFromSucc(I->second);
3017 ++SI;
3018 for (; SI != SE; ++SI) {
3019 Succ = *SI;
3020 I = BBStates.find(Succ);
3021 assert(I != BBStates.end());
3022 MyStates.MergeSucc(I->second);
3023 }
Dan Gohman0155f302012-02-17 18:59:53 +00003024 }
John McCalld935e9c2011-06-15 23:37:01 +00003025
3026 // Visit all the instructions, bottom-up.
3027 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
3028 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00003029
3030 // Invoke instructions are visited as part of their successors (below).
3031 if (isa<InvokeInst>(Inst))
3032 continue;
3033
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003034 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
3035
Dan Gohman5c70fad2012-03-23 17:47:54 +00003036 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
3037 }
3038
Dan Gohmandae33492012-04-27 18:56:31 +00003039 // If there's a predecessor with an invoke, visit the invoke as if it were
3040 // part of this block, since we can't insert code after an invoke in its own
3041 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003042 for (BBState::edge_iterator PI(MyStates.pred_begin()),
3043 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003044 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00003045 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
3046 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00003047 }
John McCalld935e9c2011-06-15 23:37:01 +00003048
Dan Gohman817a7c62012-03-22 18:24:56 +00003049 return NestingDetected;
3050}
John McCalld935e9c2011-06-15 23:37:01 +00003051
Dan Gohman817a7c62012-03-22 18:24:56 +00003052bool
3053ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3054 DenseMap<Value *, RRInfo> &Releases,
3055 BBState &MyStates) {
3056 bool NestingDetected = false;
3057 InstructionClass Class = GetInstructionClass(Inst);
3058 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003059
Dan Gohman817a7c62012-03-22 18:24:56 +00003060 switch (Class) {
3061 case IC_RetainBlock:
3062 // An objc_retainBlock call with just a use may need to be kept,
3063 // because it may be copying a block from the stack to the heap.
3064 if (!IsRetainBlockOptimizable(Inst))
3065 break;
3066 // FALLTHROUGH
3067 case IC_Retain:
3068 case IC_RetainRV: {
3069 Arg = GetObjCArg(Inst);
3070
3071 PtrState &S = MyStates.getPtrTopDownState(Arg);
3072
3073 // Don't do retain+release tracking for IC_RetainRV, because it's
3074 // better to let it remain as the first instruction after a call.
3075 if (Class != IC_RetainRV) {
3076 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00003077 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00003078 // hopefully eliminated the second retain, which may allow us to
3079 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00003080 // Theoretically we could implement removal of nested retain+release
3081 // pairs by making PtrState hold a stack of states, but this is
3082 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00003083 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00003084 NestingDetected = true;
3085
Dan Gohman62079b42012-04-25 00:50:46 +00003086 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00003087 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00003088 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00003089 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00003090 }
John McCalld935e9c2011-06-15 23:37:01 +00003091
Dan Gohmandf476e52012-09-04 23:16:20 +00003092 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00003093
3094 // A retain can be a potential use; procede to the generic checking
3095 // code below.
3096 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003097 }
3098 case IC_Release: {
3099 Arg = GetObjCArg(Inst);
3100
3101 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00003102 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00003103
3104 switch (S.GetSeq()) {
3105 case S_Retain:
3106 case S_CanRelease:
3107 S.RRI.ReverseInsertPts.clear();
3108 // FALL THROUGH
3109 case S_Use:
3110 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3111 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3112 Releases[Inst] = S.RRI;
3113 S.ClearSequenceProgress();
3114 break;
3115 case S_None:
3116 break;
3117 case S_Stop:
3118 case S_Release:
3119 case S_MovableRelease:
3120 llvm_unreachable("top-down pointer in release state!");
3121 }
3122 break;
3123 }
3124 case IC_AutoreleasepoolPop:
3125 // Conservatively, clear MyStates for all known pointers.
3126 MyStates.clearTopDownPointers();
3127 return NestingDetected;
3128 case IC_AutoreleasepoolPush:
3129 case IC_None:
3130 // These are irrelevant.
3131 return NestingDetected;
3132 default:
3133 break;
3134 }
3135
3136 // Consider any other possible effects of this instruction on each
3137 // pointer being tracked.
3138 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3139 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3140 const Value *Ptr = MI->first;
3141 if (Ptr == Arg)
3142 continue; // Handled above.
3143 PtrState &S = MI->second;
3144 Sequence Seq = S.GetSeq();
3145
3146 // Check for possible releases.
3147 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00003148 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00003149 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00003150 case S_Retain:
3151 S.SetSeq(S_CanRelease);
3152 assert(S.RRI.ReverseInsertPts.empty());
3153 S.RRI.ReverseInsertPts.insert(Inst);
3154
3155 // One call can't cause a transition from S_Retain to S_CanRelease
3156 // and S_CanRelease to S_Use. If we've made the first transition,
3157 // we're done.
3158 continue;
John McCalld935e9c2011-06-15 23:37:01 +00003159 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00003160 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00003161 case S_None:
3162 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00003163 case S_Stop:
3164 case S_Release:
3165 case S_MovableRelease:
3166 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00003167 }
3168 }
Dan Gohman817a7c62012-03-22 18:24:56 +00003169
3170 // Check for possible direct uses.
3171 switch (Seq) {
3172 case S_CanRelease:
3173 if (CanUse(Inst, Ptr, PA, Class))
3174 S.SetSeq(S_Use);
3175 break;
3176 case S_Retain:
3177 case S_Use:
3178 case S_None:
3179 break;
3180 case S_Stop:
3181 case S_Release:
3182 case S_MovableRelease:
3183 llvm_unreachable("top-down pointer in release state!");
3184 }
John McCalld935e9c2011-06-15 23:37:01 +00003185 }
3186
3187 return NestingDetected;
3188}
3189
3190bool
3191ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3192 DenseMap<const BasicBlock *, BBState> &BBStates,
3193 DenseMap<Value *, RRInfo> &Releases) {
3194 bool NestingDetected = false;
3195 BBState &MyStates = BBStates[BB];
3196
3197 // Merge the states from each predecessor to compute the initial state
3198 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00003199 BBState::edge_iterator PI(MyStates.pred_begin()),
3200 PE(MyStates.pred_end());
3201 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003202 const BasicBlock *Pred = *PI;
3203 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3204 assert(I != BBStates.end());
3205 MyStates.InitFromPred(I->second);
3206 ++PI;
3207 for (; PI != PE; ++PI) {
3208 Pred = *PI;
3209 I = BBStates.find(Pred);
3210 assert(I != BBStates.end());
3211 MyStates.MergePred(I->second);
3212 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003213 }
John McCalld935e9c2011-06-15 23:37:01 +00003214
3215 // Visit all the instructions, top-down.
3216 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3217 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00003218
3219 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3220
Dan Gohman817a7c62012-03-22 18:24:56 +00003221 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00003222 }
3223
3224 CheckForCFGHazards(BB, BBStates, MyStates);
3225 return NestingDetected;
3226}
3227
Dan Gohmana53a12c2011-12-12 19:42:25 +00003228static void
3229ComputePostOrders(Function &F,
3230 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003231 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3232 unsigned NoObjCARCExceptionsMDKind,
3233 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00003234 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003235 SmallPtrSet<BasicBlock *, 16> Visited;
3236
3237 // Do DFS, computing the PostOrder.
3238 SmallPtrSet<BasicBlock *, 16> OnStack;
3239 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003240
3241 // Functions always have exactly one entry block, and we don't have
3242 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00003243 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00003244 BBState &MyStates = BBStates[EntryBB];
3245 MyStates.SetAsEntry();
3246 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3247 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003248 Visited.insert(EntryBB);
3249 OnStack.insert(EntryBB);
3250 do {
3251 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003252 BasicBlock *CurrBB = SuccStack.back().first;
3253 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3254 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00003255
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003256 while (SuccStack.back().second != SE) {
3257 BasicBlock *SuccBB = *SuccStack.back().second++;
3258 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00003259 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3260 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003261 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00003262 BBState &SuccStates = BBStates[SuccBB];
3263 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003264 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003265 goto dfs_next_succ;
3266 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003267
3268 if (!OnStack.count(SuccBB)) {
3269 BBStates[CurrBB].addSucc(SuccBB);
3270 BBStates[SuccBB].addPred(CurrBB);
3271 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00003272 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003273 OnStack.erase(CurrBB);
3274 PostOrder.push_back(CurrBB);
3275 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00003276 } while (!SuccStack.empty());
3277
3278 Visited.clear();
3279
Dan Gohmana53a12c2011-12-12 19:42:25 +00003280 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003281 // Functions may have many exits, and there also blocks which we treat
3282 // as exits due to ignored edges.
3283 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3284 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3285 BasicBlock *ExitBB = I;
3286 BBState &MyStates = BBStates[ExitBB];
3287 if (!MyStates.isExit())
3288 continue;
3289
Dan Gohmandae33492012-04-27 18:56:31 +00003290 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003291
3292 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003293 Visited.insert(ExitBB);
3294 while (!PredStack.empty()) {
3295 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003296 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3297 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003298 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003299 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003300 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00003301 goto reverse_dfs_next_succ;
3302 }
3303 }
3304 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3305 }
3306 }
3307}
3308
Michael Gottesman97e3df02013-01-14 00:35:14 +00003309// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003310bool
3311ObjCARCOpt::Visit(Function &F,
3312 DenseMap<const BasicBlock *, BBState> &BBStates,
3313 MapVector<Value *, RRInfo> &Retains,
3314 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00003315
3316 // Use reverse-postorder traversals, because we magically know that loops
3317 // will be well behaved, i.e. they won't repeatedly call retain on a single
3318 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3319 // class here because we want the reverse-CFG postorder to consider each
3320 // function exit point, and we want to ignore selected cycle edges.
3321 SmallVector<BasicBlock *, 16> PostOrder;
3322 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00003323 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3324 NoObjCARCExceptionsMDKind,
3325 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00003326
3327 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00003328 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00003329 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00003330 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3331 I != E; ++I)
3332 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00003333
Dan Gohmana53a12c2011-12-12 19:42:25 +00003334 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00003335 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00003336 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3337 PostOrder.rbegin(), E = PostOrder.rend();
3338 I != E; ++I)
3339 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00003340
3341 return TopDownNestingDetected && BottomUpNestingDetected;
3342}
3343
Michael Gottesman97e3df02013-01-14 00:35:14 +00003344/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00003345void ObjCARCOpt::MoveCalls(Value *Arg,
3346 RRInfo &RetainsToMove,
3347 RRInfo &ReleasesToMove,
3348 MapVector<Value *, RRInfo> &Retains,
3349 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00003350 SmallVectorImpl<Instruction *> &DeadInsts,
3351 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00003352 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00003353 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00003354
3355 // Insert the new retain and release calls.
3356 for (SmallPtrSet<Instruction *, 2>::const_iterator
3357 PI = ReleasesToMove.ReverseInsertPts.begin(),
3358 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3359 Instruction *InsertPt = *PI;
3360 Value *MyArg = ArgTy == ParamTy ? Arg :
3361 new BitCastInst(Arg, ParamTy, "", InsertPt);
3362 CallInst *Call =
3363 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00003364 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00003365 MyArg, "", InsertPt);
3366 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00003367 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00003368 Call->setMetadata(CopyOnEscapeMDKind,
3369 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00003370 else
John McCalld935e9c2011-06-15 23:37:01 +00003371 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003372
3373 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3374 << "\n"
3375 " At insertion point: " << *InsertPt
3376 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003377 }
3378 for (SmallPtrSet<Instruction *, 2>::const_iterator
3379 PI = RetainsToMove.ReverseInsertPts.begin(),
3380 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00003381 Instruction *InsertPt = *PI;
3382 Value *MyArg = ArgTy == ParamTy ? Arg :
3383 new BitCastInst(Arg, ParamTy, "", InsertPt);
3384 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3385 "", InsertPt);
3386 // Attach a clang.imprecise_release metadata tag, if appropriate.
3387 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3388 Call->setMetadata(ImpreciseReleaseMDKind, M);
3389 Call->setDoesNotThrow();
3390 if (ReleasesToMove.IsTailCallRelease)
3391 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00003392
3393 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3394 << "\n"
3395 " At insertion point: " << *InsertPt
3396 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003397 }
3398
3399 // Delete the original retain and release calls.
3400 for (SmallPtrSet<Instruction *, 2>::const_iterator
3401 AI = RetainsToMove.Calls.begin(),
3402 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3403 Instruction *OrigRetain = *AI;
3404 Retains.blot(OrigRetain);
3405 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003406 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3407 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003408 }
3409 for (SmallPtrSet<Instruction *, 2>::const_iterator
3410 AI = ReleasesToMove.Calls.begin(),
3411 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3412 Instruction *OrigRelease = *AI;
3413 Releases.erase(OrigRelease);
3414 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003415 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3416 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003417 }
3418}
3419
Michael Gottesman9de6f962013-01-22 21:49:00 +00003420bool
3421ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
3422 &BBStates,
3423 MapVector<Value *, RRInfo> &Retains,
3424 DenseMap<Value *, RRInfo> &Releases,
3425 Module *M,
3426 SmallVector<Instruction *, 4> &NewRetains,
3427 SmallVector<Instruction *, 4> &NewReleases,
3428 SmallVector<Instruction *, 8> &DeadInsts,
3429 RRInfo &RetainsToMove,
3430 RRInfo &ReleasesToMove,
3431 Value *Arg,
3432 bool KnownSafe,
3433 bool &AnyPairsCompletelyEliminated) {
3434 // If a pair happens in a region where it is known that the reference count
3435 // is already incremented, we can similarly ignore possible decrements.
3436 bool KnownSafeTD = true, KnownSafeBU = true;
3437
3438 // Connect the dots between the top-down-collected RetainsToMove and
3439 // bottom-up-collected ReleasesToMove to form sets of related calls.
3440 // This is an iterative process so that we connect multiple releases
3441 // to multiple retains if needed.
3442 unsigned OldDelta = 0;
3443 unsigned NewDelta = 0;
3444 unsigned OldCount = 0;
3445 unsigned NewCount = 0;
3446 bool FirstRelease = true;
3447 bool FirstRetain = true;
3448 for (;;) {
3449 for (SmallVectorImpl<Instruction *>::const_iterator
3450 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3451 Instruction *NewRetain = *NI;
3452 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3453 assert(It != Retains.end());
3454 const RRInfo &NewRetainRRI = It->second;
3455 KnownSafeTD &= NewRetainRRI.KnownSafe;
3456 for (SmallPtrSet<Instruction *, 2>::const_iterator
3457 LI = NewRetainRRI.Calls.begin(),
3458 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3459 Instruction *NewRetainRelease = *LI;
3460 DenseMap<Value *, RRInfo>::const_iterator Jt =
3461 Releases.find(NewRetainRelease);
3462 if (Jt == Releases.end())
3463 return false;
3464 const RRInfo &NewRetainReleaseRRI = Jt->second;
3465 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3466 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3467 OldDelta -=
3468 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3469
3470 // Merge the ReleaseMetadata and IsTailCallRelease values.
3471 if (FirstRelease) {
3472 ReleasesToMove.ReleaseMetadata =
3473 NewRetainReleaseRRI.ReleaseMetadata;
3474 ReleasesToMove.IsTailCallRelease =
3475 NewRetainReleaseRRI.IsTailCallRelease;
3476 FirstRelease = false;
3477 } else {
3478 if (ReleasesToMove.ReleaseMetadata !=
3479 NewRetainReleaseRRI.ReleaseMetadata)
3480 ReleasesToMove.ReleaseMetadata = 0;
3481 if (ReleasesToMove.IsTailCallRelease !=
3482 NewRetainReleaseRRI.IsTailCallRelease)
3483 ReleasesToMove.IsTailCallRelease = false;
3484 }
3485
3486 // Collect the optimal insertion points.
3487 if (!KnownSafe)
3488 for (SmallPtrSet<Instruction *, 2>::const_iterator
3489 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3490 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3491 RI != RE; ++RI) {
3492 Instruction *RIP = *RI;
3493 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3494 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3495 }
3496 NewReleases.push_back(NewRetainRelease);
3497 }
3498 }
3499 }
3500 NewRetains.clear();
3501 if (NewReleases.empty()) break;
3502
3503 // Back the other way.
3504 for (SmallVectorImpl<Instruction *>::const_iterator
3505 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3506 Instruction *NewRelease = *NI;
3507 DenseMap<Value *, RRInfo>::const_iterator It =
3508 Releases.find(NewRelease);
3509 assert(It != Releases.end());
3510 const RRInfo &NewReleaseRRI = It->second;
3511 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3512 for (SmallPtrSet<Instruction *, 2>::const_iterator
3513 LI = NewReleaseRRI.Calls.begin(),
3514 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3515 Instruction *NewReleaseRetain = *LI;
3516 MapVector<Value *, RRInfo>::const_iterator Jt =
3517 Retains.find(NewReleaseRetain);
3518 if (Jt == Retains.end())
3519 return false;
3520 const RRInfo &NewReleaseRetainRRI = Jt->second;
3521 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3522 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3523 unsigned PathCount =
3524 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3525 OldDelta += PathCount;
3526 OldCount += PathCount;
3527
3528 // Merge the IsRetainBlock values.
3529 if (FirstRetain) {
3530 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3531 FirstRetain = false;
3532 } else if (ReleasesToMove.IsRetainBlock !=
3533 NewReleaseRetainRRI.IsRetainBlock)
3534 // It's not possible to merge the sequences if one uses
3535 // objc_retain and the other uses objc_retainBlock.
3536 return false;
3537
3538 // Collect the optimal insertion points.
3539 if (!KnownSafe)
3540 for (SmallPtrSet<Instruction *, 2>::const_iterator
3541 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3542 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3543 RI != RE; ++RI) {
3544 Instruction *RIP = *RI;
3545 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3546 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3547 NewDelta += PathCount;
3548 NewCount += PathCount;
3549 }
3550 }
3551 NewRetains.push_back(NewReleaseRetain);
3552 }
3553 }
3554 }
3555 NewReleases.clear();
3556 if (NewRetains.empty()) break;
3557 }
3558
3559 // If the pointer is known incremented or nested, we can safely delete the
3560 // pair regardless of what's between them.
3561 if (KnownSafeTD || KnownSafeBU) {
3562 RetainsToMove.ReverseInsertPts.clear();
3563 ReleasesToMove.ReverseInsertPts.clear();
3564 NewCount = 0;
3565 } else {
3566 // Determine whether the new insertion points we computed preserve the
3567 // balance of retain and release calls through the program.
3568 // TODO: If the fully aggressive solution isn't valid, try to find a
3569 // less aggressive solution which is.
3570 if (NewDelta != 0)
3571 return false;
3572 }
3573
3574 // Determine whether the original call points are balanced in the retain and
3575 // release calls through the program. If not, conservatively don't touch
3576 // them.
3577 // TODO: It's theoretically possible to do code motion in this case, as
3578 // long as the existing imbalances are maintained.
3579 if (OldDelta != 0)
3580 return false;
3581
3582 Changed = true;
3583 assert(OldCount != 0 && "Unreachable code?");
3584 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00003585 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00003586 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00003587
3588 // We can move calls!
3589 return true;
3590}
3591
Michael Gottesman97e3df02013-01-14 00:35:14 +00003592/// Identify pairings between the retains and releases, and delete and/or move
3593/// them.
John McCalld935e9c2011-06-15 23:37:01 +00003594bool
3595ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3596 &BBStates,
3597 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00003598 DenseMap<Value *, RRInfo> &Releases,
3599 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00003600 bool AnyPairsCompletelyEliminated = false;
3601 RRInfo RetainsToMove;
3602 RRInfo ReleasesToMove;
3603 SmallVector<Instruction *, 4> NewRetains;
3604 SmallVector<Instruction *, 4> NewReleases;
3605 SmallVector<Instruction *, 8> DeadInsts;
3606
Dan Gohman670f9372012-04-13 18:57:48 +00003607 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00003608 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00003609 E = Retains.end(); I != E; ++I) {
3610 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00003611 if (!V) continue; // blotted
3612
3613 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00003614
3615 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3616 << "\n");
3617
John McCalld935e9c2011-06-15 23:37:01 +00003618 Value *Arg = GetObjCArg(Retain);
3619
Dan Gohman728db492012-01-13 00:39:07 +00003620 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00003621 // not being managed by ObjC reference counting, so we can delete pairs
3622 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00003623 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00003624
Dan Gohman56e1cef2011-08-22 17:29:11 +00003625 // A constant pointer can't be pointing to an object on the heap. It may
3626 // be reference-counted, but it won't be deleted.
3627 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3628 if (const GlobalVariable *GV =
3629 dyn_cast<GlobalVariable>(
3630 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3631 if (GV->isConstant())
3632 KnownSafe = true;
3633
John McCalld935e9c2011-06-15 23:37:01 +00003634 // Connect the dots between the top-down-collected RetainsToMove and
3635 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00003636 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00003637 bool PerformMoveCalls =
3638 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
3639 NewReleases, DeadInsts, RetainsToMove,
3640 ReleasesToMove, Arg, KnownSafe,
3641 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00003642
Michael Gottesman9de6f962013-01-22 21:49:00 +00003643 if (PerformMoveCalls) {
3644 // Ok, everything checks out and we're all set. Let's move/delete some
3645 // code!
3646 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3647 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00003648 }
3649
Michael Gottesman9de6f962013-01-22 21:49:00 +00003650 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00003651 NewReleases.clear();
3652 NewRetains.clear();
3653 RetainsToMove.clear();
3654 ReleasesToMove.clear();
3655 }
3656
3657 // Now that we're done moving everything, we can delete the newly dead
3658 // instructions, as we no longer need them as insert points.
3659 while (!DeadInsts.empty())
3660 EraseInstruction(DeadInsts.pop_back_val());
3661
3662 return AnyPairsCompletelyEliminated;
3663}
3664
Michael Gottesman97e3df02013-01-14 00:35:14 +00003665/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00003666void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3667 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3668 // itself because it uses AliasAnalysis and we need to do provenance
3669 // queries instead.
3670 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3671 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00003672
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003673 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00003674 "\n");
3675
John McCalld935e9c2011-06-15 23:37:01 +00003676 InstructionClass Class = GetBasicInstructionClass(Inst);
3677 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3678 continue;
3679
3680 // Delete objc_loadWeak calls with no users.
3681 if (Class == IC_LoadWeak && Inst->use_empty()) {
3682 Inst->eraseFromParent();
3683 continue;
3684 }
3685
3686 // TODO: For now, just look for an earlier available version of this value
3687 // within the same block. Theoretically, we could do memdep-style non-local
3688 // analysis too, but that would want caching. A better approach would be to
3689 // use the technique that EarlyCSE uses.
3690 inst_iterator Current = llvm::prior(I);
3691 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3692 for (BasicBlock::iterator B = CurrentBB->begin(),
3693 J = Current.getInstructionIterator();
3694 J != B; --J) {
3695 Instruction *EarlierInst = &*llvm::prior(J);
3696 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3697 switch (EarlierClass) {
3698 case IC_LoadWeak:
3699 case IC_LoadWeakRetained: {
3700 // If this is loading from the same pointer, replace this load's value
3701 // with that one.
3702 CallInst *Call = cast<CallInst>(Inst);
3703 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3704 Value *Arg = Call->getArgOperand(0);
3705 Value *EarlierArg = EarlierCall->getArgOperand(0);
3706 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3707 case AliasAnalysis::MustAlias:
3708 Changed = true;
3709 // If the load has a builtin retain, insert a plain retain for it.
3710 if (Class == IC_LoadWeakRetained) {
3711 CallInst *CI =
3712 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3713 "", Call);
3714 CI->setTailCall();
3715 }
3716 // Zap the fully redundant load.
3717 Call->replaceAllUsesWith(EarlierCall);
3718 Call->eraseFromParent();
3719 goto clobbered;
3720 case AliasAnalysis::MayAlias:
3721 case AliasAnalysis::PartialAlias:
3722 goto clobbered;
3723 case AliasAnalysis::NoAlias:
3724 break;
3725 }
3726 break;
3727 }
3728 case IC_StoreWeak:
3729 case IC_InitWeak: {
3730 // If this is storing to the same pointer and has the same size etc.
3731 // replace this load's value with the stored value.
3732 CallInst *Call = cast<CallInst>(Inst);
3733 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3734 Value *Arg = Call->getArgOperand(0);
3735 Value *EarlierArg = EarlierCall->getArgOperand(0);
3736 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3737 case AliasAnalysis::MustAlias:
3738 Changed = true;
3739 // If the load has a builtin retain, insert a plain retain for it.
3740 if (Class == IC_LoadWeakRetained) {
3741 CallInst *CI =
3742 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3743 "", Call);
3744 CI->setTailCall();
3745 }
3746 // Zap the fully redundant load.
3747 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3748 Call->eraseFromParent();
3749 goto clobbered;
3750 case AliasAnalysis::MayAlias:
3751 case AliasAnalysis::PartialAlias:
3752 goto clobbered;
3753 case AliasAnalysis::NoAlias:
3754 break;
3755 }
3756 break;
3757 }
3758 case IC_MoveWeak:
3759 case IC_CopyWeak:
3760 // TOOD: Grab the copied value.
3761 goto clobbered;
3762 case IC_AutoreleasepoolPush:
3763 case IC_None:
3764 case IC_User:
3765 // Weak pointers are only modified through the weak entry points
3766 // (and arbitrary calls, which could call the weak entry points).
3767 break;
3768 default:
3769 // Anything else could modify the weak pointer.
3770 goto clobbered;
3771 }
3772 }
3773 clobbered:;
3774 }
3775
3776 // Then, for each destroyWeak with an alloca operand, check to see if
3777 // the alloca and all its users can be zapped.
3778 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3779 Instruction *Inst = &*I++;
3780 InstructionClass Class = GetBasicInstructionClass(Inst);
3781 if (Class != IC_DestroyWeak)
3782 continue;
3783
3784 CallInst *Call = cast<CallInst>(Inst);
3785 Value *Arg = Call->getArgOperand(0);
3786 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3787 for (Value::use_iterator UI = Alloca->use_begin(),
3788 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00003789 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00003790 switch (GetBasicInstructionClass(UserInst)) {
3791 case IC_InitWeak:
3792 case IC_StoreWeak:
3793 case IC_DestroyWeak:
3794 continue;
3795 default:
3796 goto done;
3797 }
3798 }
3799 Changed = true;
3800 for (Value::use_iterator UI = Alloca->use_begin(),
3801 UE = Alloca->use_end(); UI != UE; ) {
3802 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00003803 switch (GetBasicInstructionClass(UserInst)) {
3804 case IC_InitWeak:
3805 case IC_StoreWeak:
3806 // These functions return their second argument.
3807 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3808 break;
3809 case IC_DestroyWeak:
3810 // No return value.
3811 break;
3812 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00003813 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00003814 }
John McCalld935e9c2011-06-15 23:37:01 +00003815 UserInst->eraseFromParent();
3816 }
3817 Alloca->eraseFromParent();
3818 done:;
3819 }
3820 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003821
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003822 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003823
John McCalld935e9c2011-06-15 23:37:01 +00003824}
3825
Michael Gottesman97e3df02013-01-14 00:35:14 +00003826/// Identify program paths which execute sequences of retains and releases which
3827/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003828bool ObjCARCOpt::OptimizeSequences(Function &F) {
3829 /// Releases, Retains - These are used to store the results of the main flow
3830 /// analysis. These use Value* as the key instead of Instruction* so that the
3831 /// map stays valid when we get around to rewriting code and calls get
3832 /// replaced by arguments.
3833 DenseMap<Value *, RRInfo> Releases;
3834 MapVector<Value *, RRInfo> Retains;
3835
Michael Gottesman97e3df02013-01-14 00:35:14 +00003836 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00003837 /// states for each identified object at each block.
3838 DenseMap<const BasicBlock *, BBState> BBStates;
3839
3840 // Analyze the CFG of the function, and all instructions.
3841 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3842
3843 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00003844 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3845 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003846}
3847
Michael Gottesman97e3df02013-01-14 00:35:14 +00003848/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003849/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003850/// %call = call i8* @something(...)
3851/// %2 = call i8* @objc_retain(i8* %call)
3852/// %3 = call i8* @objc_autorelease(i8* %2)
3853/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003854/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003855/// And delete the retain and autorelease.
3856///
3857/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003858/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003859/// %3 = call i8* @objc_autorelease(i8* %2)
3860/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003861/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003862/// convert the autorelease to autoreleaseRV.
3863void ObjCARCOpt::OptimizeReturns(Function &F) {
3864 if (!F.getReturnType()->isPointerTy())
3865 return;
3866
3867 SmallPtrSet<Instruction *, 4> DependingInstructions;
3868 SmallPtrSet<const BasicBlock *, 4> Visited;
3869 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3870 BasicBlock *BB = FI;
3871 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003872
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003873 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003874
John McCalld935e9c2011-06-15 23:37:01 +00003875 if (!Ret) continue;
3876
3877 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3878 FindDependencies(NeedsPositiveRetainCount, Arg,
3879 BB, Ret, DependingInstructions, Visited, PA);
3880 if (DependingInstructions.size() != 1)
3881 goto next_block;
3882
3883 {
3884 CallInst *Autorelease =
3885 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3886 if (!Autorelease)
3887 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00003888 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003889 if (!IsAutorelease(AutoreleaseClass))
3890 goto next_block;
3891 if (GetObjCArg(Autorelease) != Arg)
3892 goto next_block;
3893
3894 DependingInstructions.clear();
3895 Visited.clear();
3896
3897 // Check that there is nothing that can affect the reference
3898 // count between the autorelease and the retain.
3899 FindDependencies(CanChangeRetainCount, Arg,
3900 BB, Autorelease, DependingInstructions, Visited, PA);
3901 if (DependingInstructions.size() != 1)
3902 goto next_block;
3903
3904 {
3905 CallInst *Retain =
3906 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3907
3908 // Check that we found a retain with the same argument.
3909 if (!Retain ||
3910 !IsRetain(GetBasicInstructionClass(Retain)) ||
3911 GetObjCArg(Retain) != Arg)
3912 goto next_block;
3913
3914 DependingInstructions.clear();
3915 Visited.clear();
3916
3917 // Convert the autorelease to an autoreleaseRV, since it's
3918 // returning the value.
3919 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003920 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3921 "=> autoreleaseRV since it's returning a value.\n"
3922 " In: " << *Autorelease
3923 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003924 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003925 DEBUG(dbgs() << " Out: " << *Autorelease
3926 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00003927 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00003928 AutoreleaseClass = IC_AutoreleaseRV;
3929 }
3930
3931 // Check that there is nothing that can affect the reference
3932 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00003933 // Note that Retain need not be in BB.
3934 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00003935 DependingInstructions, Visited, PA);
3936 if (DependingInstructions.size() != 1)
3937 goto next_block;
3938
3939 {
3940 CallInst *Call =
3941 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3942
3943 // Check that the pointer is the return value of the call.
3944 if (!Call || Arg != Call)
3945 goto next_block;
3946
3947 // Check that the call is a regular call.
3948 InstructionClass Class = GetBasicInstructionClass(Call);
3949 if (Class != IC_CallOrUser && Class != IC_Call)
3950 goto next_block;
3951
3952 // If so, we can zap the retain and autorelease.
3953 Changed = true;
3954 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00003955 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3956 << "\n Erasing: "
3957 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003958 EraseInstruction(Retain);
3959 EraseInstruction(Autorelease);
3960 }
3961 }
3962 }
3963
3964 next_block:
3965 DependingInstructions.clear();
3966 Visited.clear();
3967 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003968
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003969 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003970
John McCalld935e9c2011-06-15 23:37:01 +00003971}
3972
3973bool ObjCARCOpt::doInitialization(Module &M) {
3974 if (!EnableARCOpts)
3975 return false;
3976
Dan Gohman670f9372012-04-13 18:57:48 +00003977 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003978 Run = ModuleHasARC(M);
3979 if (!Run)
3980 return false;
3981
John McCalld935e9c2011-06-15 23:37:01 +00003982 // Identify the imprecise release metadata kind.
3983 ImpreciseReleaseMDKind =
3984 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003985 CopyOnEscapeMDKind =
3986 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003987 NoObjCARCExceptionsMDKind =
3988 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00003989
John McCalld935e9c2011-06-15 23:37:01 +00003990 // Intuitively, objc_retain and others are nocapture, however in practice
3991 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003992 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003993
3994 // These are initialized lazily.
3995 RetainRVCallee = 0;
3996 AutoreleaseRVCallee = 0;
3997 ReleaseCallee = 0;
3998 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003999 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00004000 AutoreleaseCallee = 0;
4001
4002 return false;
4003}
4004
4005bool ObjCARCOpt::runOnFunction(Function &F) {
4006 if (!EnableARCOpts)
4007 return false;
4008
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004009 // If nothing in the Module uses ARC, don't do anything.
4010 if (!Run)
4011 return false;
4012
John McCalld935e9c2011-06-15 23:37:01 +00004013 Changed = false;
4014
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00004015 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
4016
John McCalld935e9c2011-06-15 23:37:01 +00004017 PA.setAA(&getAnalysis<AliasAnalysis>());
4018
4019 // This pass performs several distinct transformations. As a compile-time aid
4020 // when compiling code that isn't ObjC, skip these if the relevant ObjC
4021 // library functions aren't declared.
4022
4023 // Preliminary optimizations. This also computs UsedInThisFunction.
4024 OptimizeIndividualCalls(F);
4025
4026 // Optimizations for weak pointers.
4027 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
4028 (1 << IC_LoadWeakRetained) |
4029 (1 << IC_StoreWeak) |
4030 (1 << IC_InitWeak) |
4031 (1 << IC_CopyWeak) |
4032 (1 << IC_MoveWeak) |
4033 (1 << IC_DestroyWeak)))
4034 OptimizeWeakCalls(F);
4035
4036 // Optimizations for retain+release pairs.
4037 if (UsedInThisFunction & ((1 << IC_Retain) |
4038 (1 << IC_RetainRV) |
4039 (1 << IC_RetainBlock)))
4040 if (UsedInThisFunction & (1 << IC_Release))
4041 // Run OptimizeSequences until it either stops making changes or
4042 // no retain+release pair nesting is detected.
4043 while (OptimizeSequences(F)) {}
4044
4045 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00004046 if (UsedInThisFunction & ((1 << IC_Autorelease) |
4047 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00004048 OptimizeReturns(F);
4049
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00004050 DEBUG(dbgs() << "\n");
4051
John McCalld935e9c2011-06-15 23:37:01 +00004052 return Changed;
4053}
4054
4055void ObjCARCOpt::releaseMemory() {
4056 PA.clear();
4057}
4058
Michael Gottesman97e3df02013-01-14 00:35:14 +00004059/// @}
4060///
4061/// \defgroup ARCContract ARC Contraction.
4062/// @{
John McCalld935e9c2011-06-15 23:37:01 +00004063
4064// TODO: ObjCARCContract could insert PHI nodes when uses aren't
4065// dominated by single calls.
4066
John McCalld935e9c2011-06-15 23:37:01 +00004067#include "llvm/Analysis/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00004068#include "llvm/IR/InlineAsm.h"
4069#include "llvm/IR/Operator.h"
John McCalld935e9c2011-06-15 23:37:01 +00004070
4071STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
4072
4073namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00004074 /// \brief Late ARC optimizations
4075 ///
4076 /// These change the IR in a way that makes it difficult to be analyzed by
4077 /// ObjCARCOpt, so it's run late.
John McCalld935e9c2011-06-15 23:37:01 +00004078 class ObjCARCContract : public FunctionPass {
4079 bool Changed;
4080 AliasAnalysis *AA;
4081 DominatorTree *DT;
4082 ProvenanceAnalysis PA;
4083
Michael Gottesman97e3df02013-01-14 00:35:14 +00004084 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004085 bool Run;
4086
Michael Gottesman97e3df02013-01-14 00:35:14 +00004087 /// Declarations for ObjC runtime functions, for use in creating calls to
4088 /// them. These are initialized lazily to avoid cluttering up the Module
4089 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00004090
Michael Gottesman97e3df02013-01-14 00:35:14 +00004091 /// Declaration for objc_storeStrong().
4092 Constant *StoreStrongCallee;
4093 /// Declaration for objc_retainAutorelease().
4094 Constant *RetainAutoreleaseCallee;
4095 /// Declaration for objc_retainAutoreleaseReturnValue().
4096 Constant *RetainAutoreleaseRVCallee;
4097
4098 /// The inline asm string to insert between calls and RetainRV calls to make
4099 /// the optimization work on targets which need it.
John McCalld935e9c2011-06-15 23:37:01 +00004100 const MDString *RetainRVMarker;
4101
Michael Gottesman97e3df02013-01-14 00:35:14 +00004102 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4103 /// function we have found no alloca instructions, these calls can be marked
4104 /// "tail".
Dan Gohman41375a32012-05-08 23:39:44 +00004105 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004106
John McCalld935e9c2011-06-15 23:37:01 +00004107 Constant *getStoreStrongCallee(Module *M);
4108 Constant *getRetainAutoreleaseCallee(Module *M);
4109 Constant *getRetainAutoreleaseRVCallee(Module *M);
4110
4111 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4112 InstructionClass Class,
4113 SmallPtrSet<Instruction *, 4>
4114 &DependingInstructions,
4115 SmallPtrSet<const BasicBlock *, 4>
4116 &Visited);
4117
4118 void ContractRelease(Instruction *Release,
4119 inst_iterator &Iter);
4120
4121 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4122 virtual bool doInitialization(Module &M);
4123 virtual bool runOnFunction(Function &F);
4124
4125 public:
4126 static char ID;
4127 ObjCARCContract() : FunctionPass(ID) {
4128 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4129 }
4130 };
4131}
4132
4133char ObjCARCContract::ID = 0;
4134INITIALIZE_PASS_BEGIN(ObjCARCContract,
4135 "objc-arc-contract", "ObjC ARC contraction", false, false)
4136INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4137INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4138INITIALIZE_PASS_END(ObjCARCContract,
4139 "objc-arc-contract", "ObjC ARC contraction", false, false)
4140
4141Pass *llvm::createObjCARCContractPass() {
4142 return new ObjCARCContract();
4143}
4144
4145void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4146 AU.addRequired<AliasAnalysis>();
4147 AU.addRequired<DominatorTree>();
4148 AU.setPreservesCFG();
4149}
4150
4151Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4152 if (!StoreStrongCallee) {
4153 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004154 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4155 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman41375a32012-05-08 23:39:44 +00004156 Type *Params[] = { I8XX, I8X };
John McCalld935e9c2011-06-15 23:37:01 +00004157
Bill Wendling09175b32013-01-22 21:15:51 +00004158 AttributeSet Attr = AttributeSet()
4159 .addAttribute(M->getContext(), AttributeSet::FunctionIndex,
4160 Attribute::NoUnwind)
4161 .addAttribute(M->getContext(), 1, Attribute::NoCapture);
John McCalld935e9c2011-06-15 23:37:01 +00004162
4163 StoreStrongCallee =
4164 M->getOrInsertFunction(
4165 "objc_storeStrong",
4166 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling09175b32013-01-22 21:15:51 +00004167 Attr);
John McCalld935e9c2011-06-15 23:37:01 +00004168 }
4169 return StoreStrongCallee;
4170}
4171
4172Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4173 if (!RetainAutoreleaseCallee) {
4174 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004175 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004176 Type *Params[] = { I8X };
4177 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004178 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00004179 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
4180 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00004181 RetainAutoreleaseCallee =
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004182 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004183 }
4184 return RetainAutoreleaseCallee;
4185}
4186
4187Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4188 if (!RetainAutoreleaseRVCallee) {
4189 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00004190 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00004191 Type *Params[] = { I8X };
4192 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004193 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00004194 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
4195 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00004196 RetainAutoreleaseRVCallee =
4197 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00004198 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00004199 }
4200 return RetainAutoreleaseRVCallee;
4201}
4202
Michael Gottesman97e3df02013-01-14 00:35:14 +00004203/// Merge an autorelease with a retain into a fused call.
John McCalld935e9c2011-06-15 23:37:01 +00004204bool
4205ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4206 InstructionClass Class,
4207 SmallPtrSet<Instruction *, 4>
4208 &DependingInstructions,
4209 SmallPtrSet<const BasicBlock *, 4>
4210 &Visited) {
4211 const Value *Arg = GetObjCArg(Autorelease);
4212
4213 // Check that there are no instructions between the retain and the autorelease
4214 // (such as an autorelease_pop) which may change the count.
4215 CallInst *Retain = 0;
4216 if (Class == IC_AutoreleaseRV)
4217 FindDependencies(RetainAutoreleaseRVDep, Arg,
4218 Autorelease->getParent(), Autorelease,
4219 DependingInstructions, Visited, PA);
4220 else
4221 FindDependencies(RetainAutoreleaseDep, Arg,
4222 Autorelease->getParent(), Autorelease,
4223 DependingInstructions, Visited, PA);
4224
4225 Visited.clear();
4226 if (DependingInstructions.size() != 1) {
4227 DependingInstructions.clear();
4228 return false;
4229 }
4230
4231 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4232 DependingInstructions.clear();
4233
4234 if (!Retain ||
4235 GetBasicInstructionClass(Retain) != IC_Retain ||
4236 GetObjCArg(Retain) != Arg)
4237 return false;
4238
4239 Changed = true;
4240 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00004241
Michael Gottesmanadd08472013-01-07 00:31:26 +00004242 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4243 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4244 " Old Retain: "
4245 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004246
John McCalld935e9c2011-06-15 23:37:01 +00004247 if (Class == IC_AutoreleaseRV)
4248 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4249 else
4250 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman10426b52013-01-07 21:26:07 +00004251
Michael Gottesmanadd08472013-01-07 00:31:26 +00004252 DEBUG(dbgs() << " New Retain: "
4253 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004254
John McCalld935e9c2011-06-15 23:37:01 +00004255 EraseInstruction(Autorelease);
4256 return true;
4257}
4258
Michael Gottesman97e3df02013-01-14 00:35:14 +00004259/// Attempt to merge an objc_release with a store, load, and objc_retain to form
4260/// an objc_storeStrong. This can be a little tricky because the instructions
4261/// don't always appear in order, and there may be unrelated intervening
4262/// instructions.
John McCalld935e9c2011-06-15 23:37:01 +00004263void ObjCARCContract::ContractRelease(Instruction *Release,
4264 inst_iterator &Iter) {
4265 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman7c5dc122011-09-12 20:23:13 +00004266 if (!Load || !Load->isSimple()) return;
John McCalld935e9c2011-06-15 23:37:01 +00004267
4268 // For now, require everything to be in one basic block.
4269 BasicBlock *BB = Release->getParent();
4270 if (Load->getParent() != BB) return;
4271
Dan Gohman61708d32012-05-08 23:34:08 +00004272 // Walk down to find the store and the release, which may be in either order.
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004273 BasicBlock::iterator I = Load, End = BB->end();
John McCalld935e9c2011-06-15 23:37:01 +00004274 ++I;
4275 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman61708d32012-05-08 23:34:08 +00004276 StoreInst *Store = 0;
4277 bool SawRelease = false;
4278 for (; !Store || !SawRelease; ++I) {
Dan Gohmanf8b19d02012-05-09 23:08:33 +00004279 if (I == End)
4280 return;
4281
Dan Gohman61708d32012-05-08 23:34:08 +00004282 Instruction *Inst = I;
4283 if (Inst == Release) {
4284 SawRelease = true;
4285 continue;
4286 }
4287
4288 InstructionClass Class = GetBasicInstructionClass(Inst);
4289
4290 // Unrelated retains are harmless.
4291 if (IsRetain(Class))
4292 continue;
4293
4294 if (Store) {
4295 // The store is the point where we're going to put the objc_storeStrong,
4296 // so make sure there are no uses after it.
4297 if (CanUse(Inst, Load, PA, Class))
4298 return;
4299 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4300 // We are moving the load down to the store, so check for anything
4301 // else which writes to the memory between the load and the store.
4302 Store = dyn_cast<StoreInst>(Inst);
4303 if (!Store || !Store->isSimple()) return;
4304 if (Store->getPointerOperand() != Loc.Ptr) return;
4305 }
4306 }
John McCalld935e9c2011-06-15 23:37:01 +00004307
4308 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4309
4310 // Walk up to find the retain.
4311 I = Store;
4312 BasicBlock::iterator Begin = BB->begin();
4313 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4314 --I;
4315 Instruction *Retain = I;
4316 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4317 if (GetObjCArg(Retain) != New) return;
4318
4319 Changed = true;
4320 ++NumStoreStrongs;
4321
4322 LLVMContext &C = Release->getContext();
Chris Lattner229907c2011-07-18 04:54:35 +00004323 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4324 Type *I8XX = PointerType::getUnqual(I8X);
John McCalld935e9c2011-06-15 23:37:01 +00004325
4326 Value *Args[] = { Load->getPointerOperand(), New };
4327 if (Args[0]->getType() != I8XX)
4328 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4329 if (Args[1]->getType() != I8X)
4330 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4331 CallInst *StoreStrong =
4332 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foad5bd375a2011-07-15 08:37:34 +00004333 Args, "", Store);
John McCalld935e9c2011-06-15 23:37:01 +00004334 StoreStrong->setDoesNotThrow();
4335 StoreStrong->setDebugLoc(Store->getDebugLoc());
4336
Dan Gohman8ee108b2012-01-19 19:14:36 +00004337 // We can't set the tail flag yet, because we haven't yet determined
4338 // whether there are any escaping allocas. Remember this call, so that
4339 // we can set the tail flag once we know it's safe.
4340 StoreStrongCalls.insert(StoreStrong);
4341
John McCalld935e9c2011-06-15 23:37:01 +00004342 if (&*Iter == Store) ++Iter;
4343 Store->eraseFromParent();
4344 Release->eraseFromParent();
4345 EraseInstruction(Retain);
4346 if (Load->use_empty())
4347 Load->eraseFromParent();
4348}
4349
4350bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohman670f9372012-04-13 18:57:48 +00004351 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004352 Run = ModuleHasARC(M);
4353 if (!Run)
4354 return false;
4355
John McCalld935e9c2011-06-15 23:37:01 +00004356 // These are initialized lazily.
4357 StoreStrongCallee = 0;
4358 RetainAutoreleaseCallee = 0;
4359 RetainAutoreleaseRVCallee = 0;
4360
4361 // Initialize RetainRVMarker.
4362 RetainRVMarker = 0;
4363 if (NamedMDNode *NMD =
4364 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4365 if (NMD->getNumOperands() == 1) {
4366 const MDNode *N = NMD->getOperand(0);
4367 if (N->getNumOperands() == 1)
4368 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4369 RetainRVMarker = S;
4370 }
4371
4372 return false;
4373}
4374
4375bool ObjCARCContract::runOnFunction(Function &F) {
4376 if (!EnableARCOpts)
4377 return false;
4378
Dan Gohmanceaac7c2011-06-20 23:20:43 +00004379 // If nothing in the Module uses ARC, don't do anything.
4380 if (!Run)
4381 return false;
4382
John McCalld935e9c2011-06-15 23:37:01 +00004383 Changed = false;
4384 AA = &getAnalysis<AliasAnalysis>();
4385 DT = &getAnalysis<DominatorTree>();
4386
4387 PA.setAA(&getAnalysis<AliasAnalysis>());
4388
Dan Gohman8ee108b2012-01-19 19:14:36 +00004389 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4390 // keyword. Be conservative if the function has variadic arguments.
4391 // It seems that functions which "return twice" are also unsafe for the
4392 // "tail" argument, because they are setjmp, which could need to
4393 // return to an earlier stack state.
Dan Gohman41375a32012-05-08 23:39:44 +00004394 bool TailOkForStoreStrongs = !F.isVarArg() &&
4395 !F.callsFunctionThatReturnsTwice();
Dan Gohman8ee108b2012-01-19 19:14:36 +00004396
John McCalld935e9c2011-06-15 23:37:01 +00004397 // For ObjC library calls which return their argument, replace uses of the
4398 // argument with uses of the call return value, if it dominates the use. This
4399 // reduces register pressure.
4400 SmallPtrSet<Instruction *, 4> DependingInstructions;
4401 SmallPtrSet<const BasicBlock *, 4> Visited;
4402 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4403 Instruction *Inst = &*I++;
Michael Gottesman10426b52013-01-07 21:26:07 +00004404
Michael Gottesman3f146e22013-01-01 16:05:48 +00004405 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004406
John McCalld935e9c2011-06-15 23:37:01 +00004407 // Only these library routines return their argument. In particular,
4408 // objc_retainBlock does not necessarily return its argument.
4409 InstructionClass Class = GetBasicInstructionClass(Inst);
4410 switch (Class) {
4411 case IC_Retain:
4412 case IC_FusedRetainAutorelease:
4413 case IC_FusedRetainAutoreleaseRV:
4414 break;
4415 case IC_Autorelease:
4416 case IC_AutoreleaseRV:
4417 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4418 continue;
4419 break;
4420 case IC_RetainRV: {
4421 // If we're compiling for a target which needs a special inline-asm
4422 // marker to do the retainAutoreleasedReturnValue optimization,
4423 // insert it now.
4424 if (!RetainRVMarker)
4425 break;
4426 BasicBlock::iterator BBI = Inst;
Dan Gohman5f725cd2012-06-25 19:47:37 +00004427 BasicBlock *InstParent = Inst->getParent();
4428
4429 // Step up to see if the call immediately precedes the RetainRV call.
4430 // If it's an invoke, we have to cross a block boundary. And we have
4431 // to carefully dodge no-op instructions.
4432 do {
4433 if (&*BBI == InstParent->begin()) {
4434 BasicBlock *Pred = InstParent->getSinglePredecessor();
4435 if (!Pred)
4436 goto decline_rv_optimization;
4437 BBI = Pred->getTerminator();
4438 break;
4439 }
4440 --BBI;
4441 } while (isNoopInstruction(BBI));
4442
John McCalld935e9c2011-06-15 23:37:01 +00004443 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman00d1f962013-01-03 07:32:41 +00004444 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman9f848ae2013-01-04 21:29:57 +00004445 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohman670f9372012-04-13 18:57:48 +00004446 Changed = true;
John McCalld935e9c2011-06-15 23:37:01 +00004447 InlineAsm *IA =
4448 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4449 /*isVarArg=*/false),
4450 RetainRVMarker->getString(),
4451 /*Constraints=*/"", /*hasSideEffects=*/true);
4452 CallInst::Create(IA, "", Inst);
4453 }
Dan Gohman5f725cd2012-06-25 19:47:37 +00004454 decline_rv_optimization:
John McCalld935e9c2011-06-15 23:37:01 +00004455 break;
4456 }
4457 case IC_InitWeak: {
4458 // objc_initWeak(p, null) => *p = null
4459 CallInst *CI = cast<CallInst>(Inst);
4460 if (isNullOrUndef(CI->getArgOperand(1))) {
4461 Value *Null =
4462 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4463 Changed = true;
4464 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00004465
Michael Gottesman416dc002013-01-03 07:32:53 +00004466 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4467 << " New = " << *Null << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00004468
John McCalld935e9c2011-06-15 23:37:01 +00004469 CI->replaceAllUsesWith(Null);
4470 CI->eraseFromParent();
4471 }
4472 continue;
4473 }
4474 case IC_Release:
4475 ContractRelease(Inst, I);
4476 continue;
Dan Gohman8ee108b2012-01-19 19:14:36 +00004477 case IC_User:
4478 // Be conservative if the function has any alloca instructions.
4479 // Technically we only care about escaping alloca instructions,
4480 // but this is sufficient to handle some interesting cases.
4481 if (isa<AllocaInst>(Inst))
4482 TailOkForStoreStrongs = false;
4483 continue;
John McCalld935e9c2011-06-15 23:37:01 +00004484 default:
4485 continue;
4486 }
4487
Michael Gottesman50ae5b22013-01-03 08:09:27 +00004488 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00004489
John McCalld935e9c2011-06-15 23:37:01 +00004490 // Don't use GetObjCArg because we don't want to look through bitcasts
4491 // and such; to do the replacement, the argument must have type i8*.
4492 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4493 for (;;) {
4494 // If we're compiling bugpointed code, don't get in trouble.
4495 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4496 break;
4497 // Look through the uses of the pointer.
4498 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4499 UI != UE; ) {
4500 Use &U = UI.getUse();
4501 unsigned OperandNo = UI.getOperandNo();
4502 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohman670f9372012-04-13 18:57:48 +00004503
4504 // If the call's return value dominates a use of the call's argument
4505 // value, rewrite the use to use the return value. We check for
4506 // reachability here because an unreachable call is considered to
4507 // trivially dominate itself, which would lead us to rewriting its
4508 // argument in terms of its return value, which would lead to
4509 // infinite loops in GetObjCArg.
Dan Gohman41375a32012-05-08 23:39:44 +00004510 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004511 Changed = true;
4512 Instruction *Replacement = Inst;
4513 Type *UseTy = U.get()->getType();
Dan Gohmande8d2c42012-04-13 01:08:28 +00004514 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00004515 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman41375a32012-05-08 23:39:44 +00004516 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4517 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindolaf5892782012-03-15 15:52:59 +00004518 if (Replacement->getType() != UseTy)
4519 Replacement = new BitCastInst(Replacement, UseTy, "",
4520 &BB->back());
Dan Gohman670f9372012-04-13 18:57:48 +00004521 // While we're here, rewrite all edges for this PHI, rather
4522 // than just one use at a time, to minimize the number of
4523 // bitcasts we emit.
Dan Gohmandae33492012-04-27 18:56:31 +00004524 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindolaf5892782012-03-15 15:52:59 +00004525 if (PHI->getIncomingBlock(i) == BB) {
4526 // Keep the UI iterator valid.
4527 if (&PHI->getOperandUse(
4528 PHINode::getOperandNumForIncomingValue(i)) ==
4529 &UI.getUse())
4530 ++UI;
4531 PHI->setIncomingValue(i, Replacement);
4532 }
4533 } else {
4534 if (Replacement->getType() != UseTy)
Dan Gohmande8d2c42012-04-13 01:08:28 +00004535 Replacement = new BitCastInst(Replacement, UseTy, "",
4536 cast<Instruction>(U.getUser()));
Rafael Espindolaf5892782012-03-15 15:52:59 +00004537 U.set(Replacement);
John McCalld935e9c2011-06-15 23:37:01 +00004538 }
Rafael Espindolaf5892782012-03-15 15:52:59 +00004539 }
John McCalld935e9c2011-06-15 23:37:01 +00004540 }
4541
Dan Gohmandae33492012-04-27 18:56:31 +00004542 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCalld935e9c2011-06-15 23:37:01 +00004543 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4544 Arg = BI->getOperand(0);
4545 else if (isa<GEPOperator>(Arg) &&
4546 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4547 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4548 else if (isa<GlobalAlias>(Arg) &&
4549 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4550 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4551 else
4552 break;
4553 }
4554 }
4555
Dan Gohman8ee108b2012-01-19 19:14:36 +00004556 // If this function has no escaping allocas or suspicious vararg usage,
4557 // objc_storeStrong calls can be marked with the "tail" keyword.
4558 if (TailOkForStoreStrongs)
Dan Gohman41375a32012-05-08 23:39:44 +00004559 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman8ee108b2012-01-19 19:14:36 +00004560 E = StoreStrongCalls.end(); I != E; ++I)
4561 (*I)->setTailCall();
4562 StoreStrongCalls.clear();
4563
John McCalld935e9c2011-06-15 23:37:01 +00004564 return Changed;
4565}
Michael Gottesman97e3df02013-01-14 00:35:14 +00004566
4567/// @}
4568///