blob: 894f4ee9733e6c374ceae0979c2b4a539152662d [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
Michael Gottesman08904e32013-01-28 03:28:38 +000031#define DEBUG_TYPE "objc-arc-opts"
32#include "ObjCARC.h"
Michael Gottesman294e7da2013-01-28 05:51:54 +000033#include "ObjCARCAliasAnalysis.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000034
John McCalld935e9c2011-06-15 23:37:01 +000035#include "llvm/ADT/DenseMap.h"
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +000036#include "llvm/ADT/SmallPtrSet.h"
Michael Gottesmanfa0939f2013-01-28 04:12:07 +000037#include "llvm/ADT/STLExtras.h"
38
John McCalld935e9c2011-06-15 23:37:01 +000039using namespace llvm;
Michael Gottesman08904e32013-01-28 03:28:38 +000040using namespace llvm::objcarc;
John McCalld935e9c2011-06-15 23:37:01 +000041
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 Carruth9fb823b2013-01-02 11:36:10 +0000135#include "llvm/IR/Intrinsics.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000136#include "llvm/Support/CallSite.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +0000137#include "llvm/Transforms/Utils/Local.h"
Dan Gohman41375a32012-05-08 23:39:44 +0000138
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000139/// \brief Test whether the given value is possible a retainable object pointer.
140static bool IsPotentialRetainableObjPtr(const Value *Op) {
141 // Pointers to static or stack storage are not valid retainable object pointers.
John McCalld935e9c2011-06-15 23:37:01 +0000142 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
143 return false;
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000144 // Special arguments can not be a valid retainable object pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000145 if (const Argument *Arg = dyn_cast<Argument>(Op))
146 if (Arg->hasByValAttr() ||
147 Arg->hasNestAttr() ||
148 Arg->hasStructRetAttr())
149 return false;
Dan Gohmanbd944b42011-12-14 19:10:53 +0000150 // Only consider values with pointer types.
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000151 //
Dan Gohmanbd944b42011-12-14 19:10:53 +0000152 // It seemes intuitive to exclude function pointer types as well, since
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000153 // functions are never retainable object pointers, however clang occasionally
154 // bitcasts retainable object pointers to function-pointer type temporarily.
Chris Lattner229907c2011-07-18 04:54:35 +0000155 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanbd944b42011-12-14 19:10:53 +0000156 if (!Ty)
John McCalld935e9c2011-06-15 23:37:01 +0000157 return false;
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000158 // Conservatively assume anything else is a potential retainable object pointer.
John McCalld935e9c2011-06-15 23:37:01 +0000159 return true;
160}
161
Michael Gottesman4385edf2013-01-14 01:47:53 +0000162/// \brief Helper for GetInstructionClass. Determines what kind of construct CS
163/// is.
John McCalld935e9c2011-06-15 23:37:01 +0000164static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
165 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
166 I != E; ++I)
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000167 if (IsPotentialRetainableObjPtr(*I))
John McCalld935e9c2011-06-15 23:37:01 +0000168 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
169
170 return CS.onlyReadsMemory() ? IC_None : IC_Call;
171}
172
Michael Gottesman97e3df02013-01-14 00:35:14 +0000173/// \brief Determine what kind of construct V is.
John McCalld935e9c2011-06-15 23:37:01 +0000174static InstructionClass GetInstructionClass(const Value *V) {
175 if (const Instruction *I = dyn_cast<Instruction>(V)) {
176 // Any instruction other than bitcast and gep with a pointer operand have a
177 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
178 // to a subsequent use, rather than using it themselves, in this sense.
179 // As a short cut, several other opcodes are known to have no pointer
180 // operands of interest. And ret is never followed by a release, so it's
181 // not interesting to examine.
182 switch (I->getOpcode()) {
183 case Instruction::Call: {
184 const CallInst *CI = cast<CallInst>(I);
185 // Check for calls to special functions.
186 if (const Function *F = CI->getCalledFunction()) {
187 InstructionClass Class = GetFunctionClass(F);
188 if (Class != IC_CallOrUser)
189 return Class;
190
191 // None of the intrinsic functions do objc_release. For intrinsics, the
192 // only question is whether or not they may be users.
193 switch (F->getIntrinsicID()) {
John McCalld935e9c2011-06-15 23:37:01 +0000194 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
195 case Intrinsic::stacksave: case Intrinsic::stackrestore:
196 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman41375a32012-05-08 23:39:44 +0000197 case Intrinsic::objectsize: case Intrinsic::prefetch:
198 case Intrinsic::stackprotector:
199 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
200 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
201 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
202 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
203 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
204 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCalld935e9c2011-06-15 23:37:01 +0000205 // Don't let dbg info affect our results.
206 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
207 // Short cut: Some intrinsics obviously don't use ObjC pointers.
208 return IC_None;
209 default:
Dan Gohman41375a32012-05-08 23:39:44 +0000210 break;
John McCalld935e9c2011-06-15 23:37:01 +0000211 }
212 }
213 return GetCallSiteClass(CI);
214 }
215 case Instruction::Invoke:
216 return GetCallSiteClass(cast<InvokeInst>(I));
217 case Instruction::BitCast:
218 case Instruction::GetElementPtr:
219 case Instruction::Select: case Instruction::PHI:
220 case Instruction::Ret: case Instruction::Br:
221 case Instruction::Switch: case Instruction::IndirectBr:
222 case Instruction::Alloca: case Instruction::VAArg:
223 case Instruction::Add: case Instruction::FAdd:
224 case Instruction::Sub: case Instruction::FSub:
225 case Instruction::Mul: case Instruction::FMul:
226 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
227 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
228 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
229 case Instruction::And: case Instruction::Or: case Instruction::Xor:
230 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
231 case Instruction::IntToPtr: case Instruction::FCmp:
232 case Instruction::FPTrunc: case Instruction::FPExt:
233 case Instruction::FPToUI: case Instruction::FPToSI:
234 case Instruction::UIToFP: case Instruction::SIToFP:
235 case Instruction::InsertElement: case Instruction::ExtractElement:
236 case Instruction::ShuffleVector:
237 case Instruction::ExtractValue:
238 break;
239 case Instruction::ICmp:
240 // Comparing a pointer with null, or any other constant, isn't an
241 // interesting use, because we don't care what the pointer points to, or
242 // about the values of any other dynamic reference-counted pointers.
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000243 if (IsPotentialRetainableObjPtr(I->getOperand(1)))
John McCalld935e9c2011-06-15 23:37:01 +0000244 return IC_User;
245 break;
246 default:
247 // For anything else, check all the operands.
Dan Gohman4b8e8ce2011-08-22 17:29:37 +0000248 // Note that this includes both operands of a Store: while the first
249 // operand isn't actually being dereferenced, it is being stored to
250 // memory where we can no longer track who might read it and dereference
251 // it, so we have to consider it potentially used.
John McCalld935e9c2011-06-15 23:37:01 +0000252 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
253 OI != OE; ++OI)
Michael Gottesman5300cdd2013-01-27 06:19:48 +0000254 if (IsPotentialRetainableObjPtr(*OI))
John McCalld935e9c2011-06-15 23:37:01 +0000255 return IC_User;
256 }
257 }
258
259 // Otherwise, it's totally inert for ARC purposes.
260 return IC_None;
261}
262
Michael Gottesman97e3df02013-01-14 00:35:14 +0000263/// \brief Erase the given instruction.
264///
265/// Many ObjC calls return their argument verbatim,
266/// so if it's such a call and the return value has users, replace them with the
267/// argument value.
268///
John McCalld935e9c2011-06-15 23:37:01 +0000269static void EraseInstruction(Instruction *CI) {
270 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
271
272 bool Unused = CI->use_empty();
273
274 if (!Unused) {
275 // Replace the return value with the argument.
276 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
277 "Can't delete non-forwarding instruction with users!");
278 CI->replaceAllUsesWith(OldArg);
279 }
280
281 CI->eraseFromParent();
282
283 if (Unused)
284 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
285}
286
Michael Gottesman97e3df02013-01-14 00:35:14 +0000287/// \brief Assuming the given instruction is one of the special calls such as
288/// objc_retain or objc_release, return the argument value, stripped of no-op
John McCalld935e9c2011-06-15 23:37:01 +0000289/// casts and forwarding calls.
290static Value *GetObjCArg(Value *Inst) {
291 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
292}
293
Michael Gottesman87db35752013-01-18 23:02:45 +0000294/// \brief Return true if this value refers to a distinct and identifiable
295/// object.
296///
297/// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
298/// special knowledge of ObjC conventions.
John McCalld935e9c2011-06-15 23:37:01 +0000299static bool IsObjCIdentifiedObject(const Value *V) {
300 // Assume that call results and arguments have their own "provenance".
301 // Constants (including GlobalVariables) and Allocas are never
302 // reference-counted.
303 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
304 isa<Argument>(V) || isa<Constant>(V) ||
305 isa<AllocaInst>(V))
306 return true;
307
308 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
309 const Value *Pointer =
310 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
311 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman56e1cef2011-08-22 17:29:11 +0000312 // A constant pointer can't be pointing to an object on the heap. It may
313 // be reference-counted, but it won't be deleted.
314 if (GV->isConstant())
315 return true;
John McCalld935e9c2011-06-15 23:37:01 +0000316 StringRef Name = GV->getName();
317 // These special variables are known to hold values which are not
318 // reference-counted pointers.
319 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
320 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
321 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
322 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
323 Name.startswith("\01l_objc_msgSend_fixup_"))
324 return true;
325 }
326 }
327
328 return false;
329}
330
Michael Gottesman97e3df02013-01-14 00:35:14 +0000331/// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
332/// as it finds a value with multiple uses.
John McCalld935e9c2011-06-15 23:37:01 +0000333static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
334 if (Arg->hasOneUse()) {
335 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
336 return FindSingleUseIdentifiedObject(BC->getOperand(0));
337 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
338 if (GEP->hasAllZeroIndices())
339 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
340 if (IsForwarding(GetBasicInstructionClass(Arg)))
341 return FindSingleUseIdentifiedObject(
342 cast<CallInst>(Arg)->getArgOperand(0));
343 if (!IsObjCIdentifiedObject(Arg))
344 return 0;
345 return Arg;
346 }
347
Dan Gohman41375a32012-05-08 23:39:44 +0000348 // If we found an identifiable object but it has multiple uses, but they are
349 // trivial uses, we can still consider this to be a single-use value.
John McCalld935e9c2011-06-15 23:37:01 +0000350 if (IsObjCIdentifiedObject(Arg)) {
351 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
352 UI != UE; ++UI) {
353 const User *U = *UI;
354 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
355 return 0;
356 }
357
358 return Arg;
359 }
360
361 return 0;
362}
363
Michael Gottesman4385edf2013-01-14 01:47:53 +0000364/// \brief Test whether the given pointer, which is an Objective C block
365/// pointer, does not "escape".
Michael Gottesman97e3df02013-01-14 00:35:14 +0000366///
367/// This differs from regular escape analysis in that a use as an
368/// argument to a call is not considered an escape.
369///
Dan Gohman728db492012-01-13 00:39:07 +0000370static bool DoesObjCBlockEscape(const Value *BlockPtr) {
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000371
372 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
373
Dan Gohman728db492012-01-13 00:39:07 +0000374 // Walk the def-use chains.
375 SmallVector<const Value *, 4> Worklist;
376 Worklist.push_back(BlockPtr);
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000377
378 // Ensure we do not visit any value twice.
379 SmallPtrSet<const Value *, 4> VisitedSet;
380
Dan Gohman728db492012-01-13 00:39:07 +0000381 do {
382 const Value *V = Worklist.pop_back_val();
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000383
384 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
385
Dan Gohman728db492012-01-13 00:39:07 +0000386 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
387 UI != UE; ++UI) {
388 const User *UUser = *UI;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000389
390 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
391
Dan Gohman728db492012-01-13 00:39:07 +0000392 // Special - Use by a call (callee or argument) is not considered
393 // to be an escape.
Dan Gohmane1e352a2012-04-13 18:28:58 +0000394 switch (GetBasicInstructionClass(UUser)) {
395 case IC_StoreWeak:
396 case IC_InitWeak:
397 case IC_StoreStrong:
398 case IC_Autorelease:
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000399 case IC_AutoreleaseRV: {
400 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
401 "Block Escapes!\n");
Dan Gohmane1e352a2012-04-13 18:28:58 +0000402 // These special functions make copies of their pointer arguments.
403 return true;
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000404 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000405 case IC_User:
406 case IC_None:
407 // Use by an instruction which copies the value is an escape if the
408 // result is an escape.
409 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
410 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000411
Michael Gottesmane9145d32013-01-14 19:18:39 +0000412 if (!VisitedSet.insert(UUser)) {
Michael Gottesman4385edf2013-01-14 01:47:53 +0000413 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
414 "if result escapes. Adding to list.\n");
Michael Gottesmanf15c0bb2013-01-13 22:12:06 +0000415 Worklist.push_back(UUser);
416 } else {
417 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
418 }
Dan Gohmane1e352a2012-04-13 18:28:58 +0000419 continue;
420 }
421 // Use by a load is not an escape.
422 if (isa<LoadInst>(UUser))
423 continue;
424 // Use by a store is not an escape if the use is the address.
425 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
426 if (V != SI->getValueOperand())
427 continue;
428 break;
429 default:
430 // Regular calls and other stuff are not considered escapes.
Dan Gohman728db492012-01-13 00:39:07 +0000431 continue;
432 }
Dan Gohmaneb6e0152012-02-13 22:57:02 +0000433 // Otherwise, conservatively assume an escape.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000434 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000435 return true;
436 }
437 } while (!Worklist.empty());
438
439 // No escapes found.
Michael Gottesman1a89fe52013-01-13 07:47:32 +0000440 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
Dan Gohman728db492012-01-13 00:39:07 +0000441 return false;
442}
443
Michael Gottesman97e3df02013-01-14 00:35:14 +0000444/// @}
445///
Michael Gottesman97e3df02013-01-14 00:35:14 +0000446/// \defgroup ARCOpt ARC Optimization.
447/// @{
John McCalld935e9c2011-06-15 23:37:01 +0000448
449// TODO: On code like this:
450//
451// objc_retain(%x)
452// stuff_that_cannot_release()
453// objc_autorelease(%x)
454// stuff_that_cannot_release()
455// objc_retain(%x)
456// stuff_that_cannot_release()
457// objc_autorelease(%x)
458//
459// The second retain and autorelease can be deleted.
460
461// TODO: It should be possible to delete
462// objc_autoreleasePoolPush and objc_autoreleasePoolPop
463// pairs if nothing is actually autoreleased between them. Also, autorelease
464// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
465// after inlining) can be turned into plain release calls.
466
467// TODO: Critical-edge splitting. If the optimial insertion point is
468// a critical edge, the current algorithm has to fail, because it doesn't
469// know how to split edges. It should be possible to make the optimizer
470// think in terms of edges, rather than blocks, and then split critical
471// edges on demand.
472
473// TODO: OptimizeSequences could generalized to be Interprocedural.
474
475// TODO: Recognize that a bunch of other objc runtime calls have
476// non-escaping arguments and non-releasing arguments, and may be
477// non-autoreleasing.
478
479// TODO: Sink autorelease calls as far as possible. Unfortunately we
480// usually can't sink them past other calls, which would be the main
481// case where it would be useful.
482
Dan Gohmanb3894012011-08-19 00:26:36 +0000483// TODO: The pointer returned from objc_loadWeakRetained is retained.
484
485// TODO: Delete release+retain pairs (rare).
Dan Gohmanceaac7c2011-06-20 23:20:43 +0000486
Chandler Carruthed0881b2012-12-03 16:50:05 +0000487#include "llvm/ADT/SmallPtrSet.h"
488#include "llvm/ADT/Statistic.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +0000489#include "llvm/IR/LLVMContext.h"
John McCalld935e9c2011-06-15 23:37:01 +0000490#include "llvm/Support/CFG.h"
John McCalld935e9c2011-06-15 23:37:01 +0000491
492STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
493STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
494STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
495STATISTIC(NumRets, "Number of return value forwarding "
496 "retain+autoreleaes eliminated");
497STATISTIC(NumRRs, "Number of retain+release paths eliminated");
498STATISTIC(NumPeeps, "Number of calls peephole-optimized");
499
500namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000501 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
502 /// techniques, except it uses special ObjC-specific reasoning about pointer
503 /// relationships.
Michael Gottesman12780c2d2013-01-24 21:35:00 +0000504 ///
505 /// In this context ``Provenance'' is defined as the history of an object's
506 /// ownership. Thus ``Provenance Analysis'' is defined by using the notion of
507 /// an ``independent provenance source'' of a pointer to determine whether or
508 /// not two pointers have the same provenance source and thus could
509 /// potentially be related.
John McCalld935e9c2011-06-15 23:37:01 +0000510 class ProvenanceAnalysis {
511 AliasAnalysis *AA;
512
513 typedef std::pair<const Value *, const Value *> ValuePairTy;
514 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
515 CachedResultsTy CachedResults;
516
517 bool relatedCheck(const Value *A, const Value *B);
518 bool relatedSelect(const SelectInst *A, const Value *B);
519 bool relatedPHI(const PHINode *A, const Value *B);
520
Craig Topperb1d83e82012-09-18 02:01:41 +0000521 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
522 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCalld935e9c2011-06-15 23:37:01 +0000523
524 public:
525 ProvenanceAnalysis() {}
526
527 void setAA(AliasAnalysis *aa) { AA = aa; }
528
529 AliasAnalysis *getAA() const { return AA; }
530
531 bool related(const Value *A, const Value *B);
532
533 void clear() {
534 CachedResults.clear();
535 }
536 };
537}
538
539bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
540 // If the values are Selects with the same condition, we can do a more precise
541 // check: just check for relations between the values on corresponding arms.
542 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohmandae33492012-04-27 18:56:31 +0000543 if (A->getCondition() == SB->getCondition())
544 return related(A->getTrueValue(), SB->getTrueValue()) ||
545 related(A->getFalseValue(), SB->getFalseValue());
John McCalld935e9c2011-06-15 23:37:01 +0000546
547 // Check both arms of the Select node individually.
Dan Gohmandae33492012-04-27 18:56:31 +0000548 return related(A->getTrueValue(), B) ||
549 related(A->getFalseValue(), B);
John McCalld935e9c2011-06-15 23:37:01 +0000550}
551
552bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
553 // If the values are PHIs in the same block, we can do a more precise as well
554 // as efficient check: just check for relations between the values on
555 // corresponding edges.
556 if (const PHINode *PNB = dyn_cast<PHINode>(B))
557 if (PNB->getParent() == A->getParent()) {
558 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
559 if (related(A->getIncomingValue(i),
560 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
561 return true;
562 return false;
563 }
564
565 // Check each unique source of the PHI node against B.
566 SmallPtrSet<const Value *, 4> UniqueSrc;
567 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
568 const Value *PV1 = A->getIncomingValue(i);
569 if (UniqueSrc.insert(PV1) && related(PV1, B))
570 return true;
571 }
572
573 // All of the arms checked out.
574 return false;
575}
576
Michael Gottesman97e3df02013-01-14 00:35:14 +0000577/// Test if the value of P, or any value covered by its provenance, is ever
578/// stored within the function (not counting callees).
John McCalld935e9c2011-06-15 23:37:01 +0000579static bool isStoredObjCPointer(const Value *P) {
580 SmallPtrSet<const Value *, 8> Visited;
581 SmallVector<const Value *, 8> Worklist;
582 Worklist.push_back(P);
583 Visited.insert(P);
584 do {
585 P = Worklist.pop_back_val();
586 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
587 UI != UE; ++UI) {
588 const User *Ur = *UI;
589 if (isa<StoreInst>(Ur)) {
590 if (UI.getOperandNo() == 0)
591 // The pointer is stored.
592 return true;
593 // The pointed is stored through.
594 continue;
595 }
596 if (isa<CallInst>(Ur))
597 // The pointer is passed as an argument, ignore this.
598 continue;
599 if (isa<PtrToIntInst>(P))
600 // Assume the worst.
601 return true;
602 if (Visited.insert(Ur))
603 Worklist.push_back(Ur);
604 }
605 } while (!Worklist.empty());
606
607 // Everything checked out.
608 return false;
609}
610
611bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
612 // Skip past provenance pass-throughs.
613 A = GetUnderlyingObjCPtr(A);
614 B = GetUnderlyingObjCPtr(B);
615
616 // Quick check.
617 if (A == B)
618 return true;
619
620 // Ask regular AliasAnalysis, for a first approximation.
621 switch (AA->alias(A, B)) {
622 case AliasAnalysis::NoAlias:
623 return false;
624 case AliasAnalysis::MustAlias:
625 case AliasAnalysis::PartialAlias:
626 return true;
627 case AliasAnalysis::MayAlias:
628 break;
629 }
630
631 bool AIsIdentified = IsObjCIdentifiedObject(A);
632 bool BIsIdentified = IsObjCIdentifiedObject(B);
633
634 // An ObjC-Identified object can't alias a load if it is never locally stored.
635 if (AIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +0000636 // Check for an obvious escape.
637 if (isa<LoadInst>(B))
638 return isStoredObjCPointer(A);
John McCalld935e9c2011-06-15 23:37:01 +0000639 if (BIsIdentified) {
Dan Gohmandf476e52012-09-04 23:16:20 +0000640 // Check for an obvious escape.
641 if (isa<LoadInst>(A))
642 return isStoredObjCPointer(B);
643 // Both pointers are identified and escapes aren't an evident problem.
644 return false;
John McCalld935e9c2011-06-15 23:37:01 +0000645 }
Dan Gohmandf476e52012-09-04 23:16:20 +0000646 } else if (BIsIdentified) {
647 // Check for an obvious escape.
648 if (isa<LoadInst>(A))
John McCalld935e9c2011-06-15 23:37:01 +0000649 return isStoredObjCPointer(B);
650 }
651
652 // Special handling for PHI and Select.
653 if (const PHINode *PN = dyn_cast<PHINode>(A))
654 return relatedPHI(PN, B);
655 if (const PHINode *PN = dyn_cast<PHINode>(B))
656 return relatedPHI(PN, A);
657 if (const SelectInst *S = dyn_cast<SelectInst>(A))
658 return relatedSelect(S, B);
659 if (const SelectInst *S = dyn_cast<SelectInst>(B))
660 return relatedSelect(S, A);
661
662 // Conservative.
663 return true;
664}
665
666bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
667 // Begin by inserting a conservative value into the map. If the insertion
668 // fails, we have the answer already. If it succeeds, leave it there until we
669 // compute the real answer to guard against recursive queries.
670 if (A > B) std::swap(A, B);
671 std::pair<CachedResultsTy::iterator, bool> Pair =
672 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
673 if (!Pair.second)
674 return Pair.first->second;
675
676 bool Result = relatedCheck(A, B);
677 CachedResults[ValuePairTy(A, B)] = Result;
678 return Result;
679}
680
681namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000682 /// \enum Sequence
683 ///
684 /// \brief A sequence of states that a pointer may go through in which an
685 /// objc_retain and objc_release are actually needed.
John McCalld935e9c2011-06-15 23:37:01 +0000686 enum Sequence {
687 S_None,
688 S_Retain, ///< objc_retain(x)
689 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
690 S_Use, ///< any use of x
691 S_Stop, ///< like S_Release, but code motion is stopped
692 S_Release, ///< objc_release(x)
693 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
694 };
695}
696
697static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
698 // The easy cases.
699 if (A == B)
700 return A;
701 if (A == S_None || B == S_None)
702 return S_None;
703
John McCalld935e9c2011-06-15 23:37:01 +0000704 if (A > B) std::swap(A, B);
705 if (TopDown) {
706 // Choose the side which is further along in the sequence.
Dan Gohman12130272011-08-12 00:26:31 +0000707 if ((A == S_Retain || A == S_CanRelease) &&
708 (B == S_CanRelease || B == S_Use))
John McCalld935e9c2011-06-15 23:37:01 +0000709 return B;
710 } else {
711 // Choose the side which is further along in the sequence.
712 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohman12130272011-08-12 00:26:31 +0000713 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCalld935e9c2011-06-15 23:37:01 +0000714 return A;
715 // If both sides are releases, choose the more conservative one.
716 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
717 return A;
718 if (A == S_Release && B == S_MovableRelease)
719 return A;
720 }
721
722 return S_None;
723}
724
725namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000726 /// \brief Unidirectional information about either a
John McCalld935e9c2011-06-15 23:37:01 +0000727 /// retain-decrement-use-release sequence or release-use-decrement-retain
728 /// reverese sequence.
729 struct RRInfo {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000730 /// After an objc_retain, the reference count of the referenced
Dan Gohmanb3894012011-08-19 00:26:36 +0000731 /// object is known to be positive. Similarly, before an objc_release, the
732 /// reference count of the referenced object is known to be positive. If
733 /// there are retain-release pairs in code regions where the retain count
734 /// is known to be positive, they can be eliminated, regardless of any side
735 /// effects between them.
736 ///
737 /// Also, a retain+release pair nested within another retain+release
738 /// pair all on the known same pointer value can be eliminated, regardless
739 /// of any intervening side effects.
740 ///
741 /// KnownSafe is true when either of these conditions is satisfied.
742 bool KnownSafe;
John McCalld935e9c2011-06-15 23:37:01 +0000743
Michael Gottesman97e3df02013-01-14 00:35:14 +0000744 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
745 /// calls).
John McCalld935e9c2011-06-15 23:37:01 +0000746 bool IsRetainBlock;
747
Michael Gottesman97e3df02013-01-14 00:35:14 +0000748 /// True of the objc_release calls are all marked with the "tail" keyword.
John McCalld935e9c2011-06-15 23:37:01 +0000749 bool IsTailCallRelease;
750
Michael Gottesman97e3df02013-01-14 00:35:14 +0000751 /// If the Calls are objc_release calls and they all have a
752 /// clang.imprecise_release tag, this is the metadata tag.
John McCalld935e9c2011-06-15 23:37:01 +0000753 MDNode *ReleaseMetadata;
754
Michael Gottesman97e3df02013-01-14 00:35:14 +0000755 /// For a top-down sequence, the set of objc_retains or
John McCalld935e9c2011-06-15 23:37:01 +0000756 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
757 SmallPtrSet<Instruction *, 2> Calls;
758
Michael Gottesman97e3df02013-01-14 00:35:14 +0000759 /// The set of optimal insert positions for moving calls in the opposite
760 /// sequence.
John McCalld935e9c2011-06-15 23:37:01 +0000761 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
762
763 RRInfo() :
Dan Gohman728db492012-01-13 00:39:07 +0000764 KnownSafe(false), IsRetainBlock(false),
Dan Gohman62079b42012-04-25 00:50:46 +0000765 IsTailCallRelease(false),
John McCalld935e9c2011-06-15 23:37:01 +0000766 ReleaseMetadata(0) {}
767
768 void clear();
769 };
770}
771
772void RRInfo::clear() {
Dan Gohmanb3894012011-08-19 00:26:36 +0000773 KnownSafe = false;
John McCalld935e9c2011-06-15 23:37:01 +0000774 IsRetainBlock = false;
775 IsTailCallRelease = false;
776 ReleaseMetadata = 0;
777 Calls.clear();
778 ReverseInsertPts.clear();
779}
780
781namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000782 /// \brief This class summarizes several per-pointer runtime properties which
783 /// are propogated through the flow graph.
John McCalld935e9c2011-06-15 23:37:01 +0000784 class PtrState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000785 /// True if the reference count is known to be incremented.
Dan Gohman62079b42012-04-25 00:50:46 +0000786 bool KnownPositiveRefCount;
787
Michael Gottesman97e3df02013-01-14 00:35:14 +0000788 /// True of we've seen an opportunity for partial RR elimination, such as
789 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
Dan Gohman62079b42012-04-25 00:50:46 +0000790 bool Partial;
John McCalld935e9c2011-06-15 23:37:01 +0000791
Michael Gottesman97e3df02013-01-14 00:35:14 +0000792 /// The current position in the sequence.
Dan Gohman41375a32012-05-08 23:39:44 +0000793 Sequence Seq : 8;
John McCalld935e9c2011-06-15 23:37:01 +0000794
795 public:
Michael Gottesman97e3df02013-01-14 00:35:14 +0000796 /// Unidirectional information about the current sequence.
797 ///
John McCalld935e9c2011-06-15 23:37:01 +0000798 /// TODO: Encapsulate this better.
799 RRInfo RRI;
800
Dan Gohmandf476e52012-09-04 23:16:20 +0000801 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman41375a32012-05-08 23:39:44 +0000802 Seq(S_None) {}
John McCalld935e9c2011-06-15 23:37:01 +0000803
Dan Gohman62079b42012-04-25 00:50:46 +0000804 void SetKnownPositiveRefCount() {
805 KnownPositiveRefCount = true;
Dan Gohman12130272011-08-12 00:26:31 +0000806 }
807
Dan Gohman62079b42012-04-25 00:50:46 +0000808 void ClearRefCount() {
809 KnownPositiveRefCount = false;
John McCalld935e9c2011-06-15 23:37:01 +0000810 }
811
John McCalld935e9c2011-06-15 23:37:01 +0000812 bool IsKnownIncremented() const {
Dan Gohman62079b42012-04-25 00:50:46 +0000813 return KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000814 }
815
816 void SetSeq(Sequence NewSeq) {
817 Seq = NewSeq;
818 }
819
John McCalld935e9c2011-06-15 23:37:01 +0000820 Sequence GetSeq() const {
821 return Seq;
822 }
823
824 void ClearSequenceProgress() {
Dan Gohman62079b42012-04-25 00:50:46 +0000825 ResetSequenceProgress(S_None);
826 }
827
828 void ResetSequenceProgress(Sequence NewSeq) {
829 Seq = NewSeq;
830 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000831 RRI.clear();
832 }
833
834 void Merge(const PtrState &Other, bool TopDown);
835 };
836}
837
838void
839PtrState::Merge(const PtrState &Other, bool TopDown) {
840 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman62079b42012-04-25 00:50:46 +0000841 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCalld935e9c2011-06-15 23:37:01 +0000842
843 // We can't merge a plain objc_retain with an objc_retainBlock.
844 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
845 Seq = S_None;
846
Dan Gohman1736c142011-10-17 18:48:25 +0000847 // If we're not in a sequence (anymore), drop all associated state.
John McCalld935e9c2011-06-15 23:37:01 +0000848 if (Seq == S_None) {
Dan Gohman62079b42012-04-25 00:50:46 +0000849 Partial = false;
John McCalld935e9c2011-06-15 23:37:01 +0000850 RRI.clear();
Dan Gohman62079b42012-04-25 00:50:46 +0000851 } else if (Partial || Other.Partial) {
Dan Gohman1736c142011-10-17 18:48:25 +0000852 // If we're doing a merge on a path that's previously seen a partial
853 // merge, conservatively drop the sequence, to avoid doing partial
854 // RR elimination. If the branch predicates for the two merge differ,
855 // mixing them is unsafe.
Dan Gohman62079b42012-04-25 00:50:46 +0000856 ClearSequenceProgress();
John McCalld935e9c2011-06-15 23:37:01 +0000857 } else {
858 // Conservatively merge the ReleaseMetadata information.
859 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
860 RRI.ReleaseMetadata = 0;
861
Dan Gohmanb3894012011-08-19 00:26:36 +0000862 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman41375a32012-05-08 23:39:44 +0000863 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
864 Other.RRI.IsTailCallRelease;
John McCalld935e9c2011-06-15 23:37:01 +0000865 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman1736c142011-10-17 18:48:25 +0000866
867 // Merge the insert point sets. If there are any differences,
868 // that makes this a partial merge.
Dan Gohman41375a32012-05-08 23:39:44 +0000869 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman1736c142011-10-17 18:48:25 +0000870 for (SmallPtrSet<Instruction *, 2>::const_iterator
871 I = Other.RRI.ReverseInsertPts.begin(),
872 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman62079b42012-04-25 00:50:46 +0000873 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCalld935e9c2011-06-15 23:37:01 +0000874 }
875}
876
877namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000878 /// \brief Per-BasicBlock state.
John McCalld935e9c2011-06-15 23:37:01 +0000879 class BBState {
Michael Gottesman97e3df02013-01-14 00:35:14 +0000880 /// The number of unique control paths from the entry which can reach this
881 /// block.
John McCalld935e9c2011-06-15 23:37:01 +0000882 unsigned TopDownPathCount;
883
Michael Gottesman97e3df02013-01-14 00:35:14 +0000884 /// The number of unique control paths to exits from this block.
John McCalld935e9c2011-06-15 23:37:01 +0000885 unsigned BottomUpPathCount;
886
Michael Gottesman97e3df02013-01-14 00:35:14 +0000887 /// A type for PerPtrTopDown and PerPtrBottomUp.
John McCalld935e9c2011-06-15 23:37:01 +0000888 typedef MapVector<const Value *, PtrState> MapTy;
889
Michael Gottesman97e3df02013-01-14 00:35:14 +0000890 /// The top-down traversal uses this to record information known about a
891 /// pointer at the bottom of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000892 MapTy PerPtrTopDown;
893
Michael Gottesman97e3df02013-01-14 00:35:14 +0000894 /// The bottom-up traversal uses this to record information known about a
895 /// pointer at the top of each block.
John McCalld935e9c2011-06-15 23:37:01 +0000896 MapTy PerPtrBottomUp;
897
Michael Gottesman97e3df02013-01-14 00:35:14 +0000898 /// Effective predecessors of the current block ignoring ignorable edges and
899 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000900 SmallVector<BasicBlock *, 2> Preds;
Michael Gottesman97e3df02013-01-14 00:35:14 +0000901 /// Effective successors of the current block ignoring ignorable edges and
902 /// ignored backedges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000903 SmallVector<BasicBlock *, 2> Succs;
904
John McCalld935e9c2011-06-15 23:37:01 +0000905 public:
906 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
907
908 typedef MapTy::iterator ptr_iterator;
909 typedef MapTy::const_iterator ptr_const_iterator;
910
911 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
912 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
913 ptr_const_iterator top_down_ptr_begin() const {
914 return PerPtrTopDown.begin();
915 }
916 ptr_const_iterator top_down_ptr_end() const {
917 return PerPtrTopDown.end();
918 }
919
920 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
921 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
922 ptr_const_iterator bottom_up_ptr_begin() const {
923 return PerPtrBottomUp.begin();
924 }
925 ptr_const_iterator bottom_up_ptr_end() const {
926 return PerPtrBottomUp.end();
927 }
928
Michael Gottesman97e3df02013-01-14 00:35:14 +0000929 /// Mark this block as being an entry block, which has one path from the
930 /// entry by definition.
John McCalld935e9c2011-06-15 23:37:01 +0000931 void SetAsEntry() { TopDownPathCount = 1; }
932
Michael Gottesman97e3df02013-01-14 00:35:14 +0000933 /// Mark this block as being an exit block, which has one path to an exit by
934 /// definition.
John McCalld935e9c2011-06-15 23:37:01 +0000935 void SetAsExit() { BottomUpPathCount = 1; }
936
937 PtrState &getPtrTopDownState(const Value *Arg) {
938 return PerPtrTopDown[Arg];
939 }
940
941 PtrState &getPtrBottomUpState(const Value *Arg) {
942 return PerPtrBottomUp[Arg];
943 }
944
945 void clearBottomUpPointers() {
Evan Chenge4df6a22011-08-04 18:40:26 +0000946 PerPtrBottomUp.clear();
John McCalld935e9c2011-06-15 23:37:01 +0000947 }
948
949 void clearTopDownPointers() {
950 PerPtrTopDown.clear();
951 }
952
953 void InitFromPred(const BBState &Other);
954 void InitFromSucc(const BBState &Other);
955 void MergePred(const BBState &Other);
956 void MergeSucc(const BBState &Other);
957
Michael Gottesman97e3df02013-01-14 00:35:14 +0000958 /// Return the number of possible unique paths from an entry to an exit
959 /// which pass through this block. This is only valid after both the
960 /// top-down and bottom-up traversals are complete.
John McCalld935e9c2011-06-15 23:37:01 +0000961 unsigned GetAllPathCount() const {
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000962 assert(TopDownPathCount != 0);
963 assert(BottomUpPathCount != 0);
John McCalld935e9c2011-06-15 23:37:01 +0000964 return TopDownPathCount * BottomUpPathCount;
965 }
Dan Gohman12130272011-08-12 00:26:31 +0000966
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000967 // Specialized CFG utilities.
Dan Gohmandae33492012-04-27 18:56:31 +0000968 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmanc24c66f2012-04-24 22:53:18 +0000969 edge_iterator pred_begin() { return Preds.begin(); }
970 edge_iterator pred_end() { return Preds.end(); }
971 edge_iterator succ_begin() { return Succs.begin(); }
972 edge_iterator succ_end() { return Succs.end(); }
973
974 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
975 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
976
977 bool isExit() const { return Succs.empty(); }
John McCalld935e9c2011-06-15 23:37:01 +0000978 };
979}
980
981void BBState::InitFromPred(const BBState &Other) {
982 PerPtrTopDown = Other.PerPtrTopDown;
983 TopDownPathCount = Other.TopDownPathCount;
984}
985
986void BBState::InitFromSucc(const BBState &Other) {
987 PerPtrBottomUp = Other.PerPtrBottomUp;
988 BottomUpPathCount = Other.BottomUpPathCount;
989}
990
Michael Gottesman97e3df02013-01-14 00:35:14 +0000991/// The top-down traversal uses this to merge information about predecessors to
992/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +0000993void BBState::MergePred(const BBState &Other) {
994 // Other.TopDownPathCount can be 0, in which case it is either dead or a
995 // loop backedge. Loop backedges are special.
996 TopDownPathCount += Other.TopDownPathCount;
997
Michael Gottesman4385edf2013-01-14 01:47:53 +0000998 // Check for overflow. If we have overflow, fall back to conservative
999 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001000 if (TopDownPathCount < Other.TopDownPathCount) {
1001 clearTopDownPointers();
1002 return;
1003 }
1004
John McCalld935e9c2011-06-15 23:37:01 +00001005 // For each entry in the other set, if our set has an entry with the same key,
1006 // merge the entries. Otherwise, copy the entry and merge it with an empty
1007 // entry.
1008 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1009 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1010 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1011 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1012 /*TopDown=*/true);
1013 }
1014
Dan Gohman7e315fc32011-08-11 21:06:32 +00001015 // For each entry in our set, if the other set doesn't have an entry with the
John McCalld935e9c2011-06-15 23:37:01 +00001016 // same key, force it to merge with an empty entry.
1017 for (ptr_iterator MI = top_down_ptr_begin(),
1018 ME = top_down_ptr_end(); MI != ME; ++MI)
1019 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1020 MI->second.Merge(PtrState(), /*TopDown=*/true);
1021}
1022
Michael Gottesman97e3df02013-01-14 00:35:14 +00001023/// The bottom-up traversal uses this to merge information about successors to
1024/// form the initial state for a new block.
John McCalld935e9c2011-06-15 23:37:01 +00001025void BBState::MergeSucc(const BBState &Other) {
1026 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1027 // loop backedge. Loop backedges are special.
1028 BottomUpPathCount += Other.BottomUpPathCount;
1029
Michael Gottesman4385edf2013-01-14 01:47:53 +00001030 // Check for overflow. If we have overflow, fall back to conservative
1031 // behavior.
Dan Gohman7c84dad2012-09-12 20:45:17 +00001032 if (BottomUpPathCount < Other.BottomUpPathCount) {
1033 clearBottomUpPointers();
1034 return;
1035 }
1036
John McCalld935e9c2011-06-15 23:37:01 +00001037 // For each entry in the other set, if our set has an entry with the
1038 // same key, merge the entries. Otherwise, copy the entry and merge
1039 // it with an empty entry.
1040 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1041 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1042 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1043 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1044 /*TopDown=*/false);
1045 }
1046
Dan Gohman7e315fc32011-08-11 21:06:32 +00001047 // For each entry in our set, if the other set doesn't have an entry
John McCalld935e9c2011-06-15 23:37:01 +00001048 // with the same key, force it to merge with an empty entry.
1049 for (ptr_iterator MI = bottom_up_ptr_begin(),
1050 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1051 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1052 MI->second.Merge(PtrState(), /*TopDown=*/false);
1053}
1054
1055namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001056 /// \brief The main ARC optimization pass.
John McCalld935e9c2011-06-15 23:37:01 +00001057 class ObjCARCOpt : public FunctionPass {
1058 bool Changed;
1059 ProvenanceAnalysis PA;
1060
Michael Gottesman97e3df02013-01-14 00:35:14 +00001061 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00001062 bool Run;
1063
Michael Gottesman97e3df02013-01-14 00:35:14 +00001064 /// Declarations for ObjC runtime functions, for use in creating calls to
1065 /// them. These are initialized lazily to avoid cluttering up the Module
1066 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00001067
Michael Gottesman97e3df02013-01-14 00:35:14 +00001068 /// Declaration for ObjC runtime function
1069 /// objc_retainAutoreleasedReturnValue.
1070 Constant *RetainRVCallee;
1071 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1072 Constant *AutoreleaseRVCallee;
1073 /// Declaration for ObjC runtime function objc_release.
1074 Constant *ReleaseCallee;
1075 /// Declaration for ObjC runtime function objc_retain.
1076 Constant *RetainCallee;
1077 /// Declaration for ObjC runtime function objc_retainBlock.
1078 Constant *RetainBlockCallee;
1079 /// Declaration for ObjC runtime function objc_autorelease.
1080 Constant *AutoreleaseCallee;
1081
1082 /// Flags which determine whether each of the interesting runtine functions
1083 /// is in fact used in the current function.
John McCalld935e9c2011-06-15 23:37:01 +00001084 unsigned UsedInThisFunction;
1085
Michael Gottesman97e3df02013-01-14 00:35:14 +00001086 /// The Metadata Kind for clang.imprecise_release metadata.
John McCalld935e9c2011-06-15 23:37:01 +00001087 unsigned ImpreciseReleaseMDKind;
1088
Michael Gottesman97e3df02013-01-14 00:35:14 +00001089 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
Dan Gohmana7107f92011-10-17 22:53:25 +00001090 unsigned CopyOnEscapeMDKind;
1091
Michael Gottesman97e3df02013-01-14 00:35:14 +00001092 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
Dan Gohman0155f302012-02-17 18:59:53 +00001093 unsigned NoObjCARCExceptionsMDKind;
1094
John McCalld935e9c2011-06-15 23:37:01 +00001095 Constant *getRetainRVCallee(Module *M);
1096 Constant *getAutoreleaseRVCallee(Module *M);
1097 Constant *getReleaseCallee(Module *M);
1098 Constant *getRetainCallee(Module *M);
Dan Gohman6320f522011-07-22 22:29:21 +00001099 Constant *getRetainBlockCallee(Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001100 Constant *getAutoreleaseCallee(Module *M);
1101
Dan Gohman728db492012-01-13 00:39:07 +00001102 bool IsRetainBlockOptimizable(const Instruction *Inst);
1103
John McCalld935e9c2011-06-15 23:37:01 +00001104 void OptimizeRetainCall(Function &F, Instruction *Retain);
1105 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
Michael Gottesman556ff612013-01-12 01:25:19 +00001106 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1107 InstructionClass &Class);
John McCalld935e9c2011-06-15 23:37:01 +00001108 void OptimizeIndividualCalls(Function &F);
1109
1110 void CheckForCFGHazards(const BasicBlock *BB,
1111 DenseMap<const BasicBlock *, BBState> &BBStates,
1112 BBState &MyStates) const;
Dan Gohman817a7c62012-03-22 18:24:56 +00001113 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00001114 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00001115 MapVector<Value *, RRInfo> &Retains,
1116 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001117 bool VisitBottomUp(BasicBlock *BB,
1118 DenseMap<const BasicBlock *, BBState> &BBStates,
1119 MapVector<Value *, RRInfo> &Retains);
Dan Gohman817a7c62012-03-22 18:24:56 +00001120 bool VisitInstructionTopDown(Instruction *Inst,
1121 DenseMap<Value *, RRInfo> &Releases,
1122 BBState &MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00001123 bool VisitTopDown(BasicBlock *BB,
1124 DenseMap<const BasicBlock *, BBState> &BBStates,
1125 DenseMap<Value *, RRInfo> &Releases);
1126 bool Visit(Function &F,
1127 DenseMap<const BasicBlock *, BBState> &BBStates,
1128 MapVector<Value *, RRInfo> &Retains,
1129 DenseMap<Value *, RRInfo> &Releases);
1130
1131 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1132 MapVector<Value *, RRInfo> &Retains,
1133 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00001134 SmallVectorImpl<Instruction *> &DeadInsts,
1135 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001136
Michael Gottesman9de6f962013-01-22 21:49:00 +00001137 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1138 MapVector<Value *, RRInfo> &Retains,
1139 DenseMap<Value *, RRInfo> &Releases,
1140 Module *M,
1141 SmallVector<Instruction *, 4> &NewRetains,
1142 SmallVector<Instruction *, 4> &NewReleases,
1143 SmallVector<Instruction *, 8> &DeadInsts,
1144 RRInfo &RetainsToMove,
1145 RRInfo &ReleasesToMove,
1146 Value *Arg,
1147 bool KnownSafe,
1148 bool &AnyPairsCompletelyEliminated);
1149
John McCalld935e9c2011-06-15 23:37:01 +00001150 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1151 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00001152 DenseMap<Value *, RRInfo> &Releases,
1153 Module *M);
John McCalld935e9c2011-06-15 23:37:01 +00001154
1155 void OptimizeWeakCalls(Function &F);
1156
1157 bool OptimizeSequences(Function &F);
1158
1159 void OptimizeReturns(Function &F);
1160
1161 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1162 virtual bool doInitialization(Module &M);
1163 virtual bool runOnFunction(Function &F);
1164 virtual void releaseMemory();
1165
1166 public:
1167 static char ID;
1168 ObjCARCOpt() : FunctionPass(ID) {
1169 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1170 }
1171 };
1172}
1173
1174char ObjCARCOpt::ID = 0;
1175INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1176 "objc-arc", "ObjC ARC optimization", false, false)
1177INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1178INITIALIZE_PASS_END(ObjCARCOpt,
1179 "objc-arc", "ObjC ARC optimization", false, false)
1180
1181Pass *llvm::createObjCARCOptPass() {
1182 return new ObjCARCOpt();
1183}
1184
1185void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1186 AU.addRequired<ObjCARCAliasAnalysis>();
1187 AU.addRequired<AliasAnalysis>();
1188 // ARC optimization doesn't currently split critical edges.
1189 AU.setPreservesCFG();
1190}
1191
Dan Gohman728db492012-01-13 00:39:07 +00001192bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1193 // Without the magic metadata tag, we have to assume this might be an
1194 // objc_retainBlock call inserted to convert a block pointer to an id,
1195 // in which case it really is needed.
1196 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1197 return false;
1198
1199 // If the pointer "escapes" (not including being used in a call),
1200 // the copy may be needed.
1201 if (DoesObjCBlockEscape(Inst))
1202 return false;
1203
1204 // Otherwise, it's not needed.
1205 return true;
1206}
1207
John McCalld935e9c2011-06-15 23:37:01 +00001208Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1209 if (!RetainRVCallee) {
1210 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001211 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001212 Type *Params[] = { I8X };
1213 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001214 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001215 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1216 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001217 RetainRVCallee =
1218 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001219 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001220 }
1221 return RetainRVCallee;
1222}
1223
1224Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1225 if (!AutoreleaseRVCallee) {
1226 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00001227 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00001228 Type *Params[] = { I8X };
1229 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001230 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001231 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1232 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001233 AutoreleaseRVCallee =
1234 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001235 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001236 }
1237 return AutoreleaseRVCallee;
1238}
1239
1240Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1241 if (!ReleaseCallee) {
1242 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001243 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001244 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001245 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1246 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001247 ReleaseCallee =
1248 M->getOrInsertFunction(
1249 "objc_release",
1250 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001251 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001252 }
1253 return ReleaseCallee;
1254}
1255
1256Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1257 if (!RetainCallee) {
1258 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001259 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001260 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001261 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1262 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001263 RetainCallee =
1264 M->getOrInsertFunction(
1265 "objc_retain",
1266 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001267 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001268 }
1269 return RetainCallee;
1270}
1271
Dan Gohman6320f522011-07-22 22:29:21 +00001272Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1273 if (!RetainBlockCallee) {
1274 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001275 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohmanfca43c22011-09-14 18:33:34 +00001276 // objc_retainBlock is not nounwind because it calls user copy constructors
1277 // which could theoretically throw.
Dan Gohman6320f522011-07-22 22:29:21 +00001278 RetainBlockCallee =
1279 M->getOrInsertFunction(
1280 "objc_retainBlock",
1281 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendlinge94d8432012-12-07 23:16:57 +00001282 AttributeSet());
Dan Gohman6320f522011-07-22 22:29:21 +00001283 }
1284 return RetainBlockCallee;
1285}
1286
John McCalld935e9c2011-06-15 23:37:01 +00001287Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1288 if (!AutoreleaseCallee) {
1289 LLVMContext &C = M->getContext();
Dan Gohman41375a32012-05-08 23:39:44 +00001290 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001291 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00001292 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1293 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00001294 AutoreleaseCallee =
1295 M->getOrInsertFunction(
1296 "objc_autorelease",
1297 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001298 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00001299 }
1300 return AutoreleaseCallee;
1301}
1302
Michael Gottesman97e3df02013-01-14 00:35:14 +00001303/// Test whether the given value is possible a reference-counted pointer,
1304/// including tests which utilize AliasAnalysis.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001305static bool IsPotentialRetainableObjPtr(const Value *Op, AliasAnalysis &AA) {
Dan Gohmandf476e52012-09-04 23:16:20 +00001306 // First make the rudimentary check.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001307 if (!IsPotentialRetainableObjPtr(Op))
Dan Gohmandf476e52012-09-04 23:16:20 +00001308 return false;
1309
1310 // Objects in constant memory are not reference-counted.
1311 if (AA.pointsToConstantMemory(Op))
1312 return false;
1313
1314 // Pointers in constant memory are not pointing to reference-counted objects.
1315 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1316 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1317 return false;
1318
1319 // Otherwise assume the worst.
1320 return true;
1321}
1322
Michael Gottesman97e3df02013-01-14 00:35:14 +00001323/// Test whether the given instruction can result in a reference count
1324/// modification (positive or negative) for the pointer's object.
John McCalld935e9c2011-06-15 23:37:01 +00001325static bool
1326CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1327 ProvenanceAnalysis &PA, InstructionClass Class) {
1328 switch (Class) {
1329 case IC_Autorelease:
1330 case IC_AutoreleaseRV:
1331 case IC_User:
1332 // These operations never directly modify a reference count.
1333 return false;
1334 default: break;
1335 }
1336
1337 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1338 assert(CS && "Only calls can alter reference counts!");
1339
1340 // See if AliasAnalysis can help us with the call.
1341 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1342 if (AliasAnalysis::onlyReadsMemory(MRB))
1343 return false;
1344 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1345 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1346 I != E; ++I) {
1347 const Value *Op = *I;
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001348 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00001349 return true;
1350 }
1351 return false;
1352 }
1353
1354 // Assume the worst.
1355 return true;
1356}
1357
Michael Gottesman97e3df02013-01-14 00:35:14 +00001358/// Test whether the given instruction can "use" the given pointer's object in a
1359/// way that requires the reference count to be positive.
John McCalld935e9c2011-06-15 23:37:01 +00001360static bool
1361CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1362 InstructionClass Class) {
1363 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1364 if (Class == IC_Call)
1365 return false;
1366
1367 // Consider various instructions which may have pointer arguments which are
1368 // not "uses".
1369 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1370 // Comparing a pointer with null, or any other constant, isn't really a use,
1371 // because we don't care what the pointer points to, or about the values
1372 // of any other dynamic reference-counted pointers.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001373 if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
John McCalld935e9c2011-06-15 23:37:01 +00001374 return false;
1375 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1376 // For calls, just check the arguments (and not the callee operand).
1377 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1378 OE = CS.arg_end(); OI != OE; ++OI) {
1379 const Value *Op = *OI;
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001380 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00001381 return true;
1382 }
1383 return false;
1384 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1385 // Special-case stores, because we don't care about the stored value, just
1386 // the store address.
1387 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1388 // If we can't tell what the underlying object was, assume there is a
1389 // dependence.
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001390 return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCalld935e9c2011-06-15 23:37:01 +00001391 }
1392
1393 // Check each operand for a match.
1394 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1395 OI != OE; ++OI) {
1396 const Value *Op = *OI;
Michael Gottesman5300cdd2013-01-27 06:19:48 +00001397 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCalld935e9c2011-06-15 23:37:01 +00001398 return true;
1399 }
1400 return false;
1401}
1402
Michael Gottesman97e3df02013-01-14 00:35:14 +00001403/// Test whether the given instruction can autorelease any pointer or cause an
1404/// autoreleasepool pop.
John McCalld935e9c2011-06-15 23:37:01 +00001405static bool
1406CanInterruptRV(InstructionClass Class) {
1407 switch (Class) {
1408 case IC_AutoreleasepoolPop:
1409 case IC_CallOrUser:
1410 case IC_Call:
1411 case IC_Autorelease:
1412 case IC_AutoreleaseRV:
1413 case IC_FusedRetainAutorelease:
1414 case IC_FusedRetainAutoreleaseRV:
1415 return true;
1416 default:
1417 return false;
1418 }
1419}
1420
1421namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00001422 /// \enum DependenceKind
1423 /// \brief Defines different dependence kinds among various ARC constructs.
1424 ///
1425 /// There are several kinds of dependence-like concepts in use here.
1426 ///
John McCalld935e9c2011-06-15 23:37:01 +00001427 enum DependenceKind {
1428 NeedsPositiveRetainCount,
Dan Gohman8478d762012-04-13 00:59:57 +00001429 AutoreleasePoolBoundary,
John McCalld935e9c2011-06-15 23:37:01 +00001430 CanChangeRetainCount,
1431 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1432 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1433 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1434 };
1435}
1436
Michael Gottesman97e3df02013-01-14 00:35:14 +00001437/// Test if there can be dependencies on Inst through Arg. This function only
1438/// tests dependencies relevant for removing pairs of calls.
John McCalld935e9c2011-06-15 23:37:01 +00001439static bool
1440Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1441 ProvenanceAnalysis &PA) {
1442 // If we've reached the definition of Arg, stop.
1443 if (Inst == Arg)
1444 return true;
1445
1446 switch (Flavor) {
1447 case NeedsPositiveRetainCount: {
1448 InstructionClass Class = GetInstructionClass(Inst);
1449 switch (Class) {
1450 case IC_AutoreleasepoolPop:
1451 case IC_AutoreleasepoolPush:
1452 case IC_None:
1453 return false;
1454 default:
1455 return CanUse(Inst, Arg, PA, Class);
1456 }
1457 }
1458
Dan Gohman8478d762012-04-13 00:59:57 +00001459 case AutoreleasePoolBoundary: {
1460 InstructionClass Class = GetInstructionClass(Inst);
1461 switch (Class) {
1462 case IC_AutoreleasepoolPop:
1463 case IC_AutoreleasepoolPush:
1464 // These mark the end and begin of an autorelease pool scope.
1465 return true;
1466 default:
1467 // Nothing else does this.
1468 return false;
1469 }
1470 }
1471
John McCalld935e9c2011-06-15 23:37:01 +00001472 case CanChangeRetainCount: {
1473 InstructionClass Class = GetInstructionClass(Inst);
1474 switch (Class) {
1475 case IC_AutoreleasepoolPop:
1476 // Conservatively assume this can decrement any count.
1477 return true;
1478 case IC_AutoreleasepoolPush:
1479 case IC_None:
1480 return false;
1481 default:
1482 return CanAlterRefCount(Inst, Arg, PA, Class);
1483 }
1484 }
1485
1486 case RetainAutoreleaseDep:
1487 switch (GetBasicInstructionClass(Inst)) {
1488 case IC_AutoreleasepoolPop:
Dan Gohman8478d762012-04-13 00:59:57 +00001489 case IC_AutoreleasepoolPush:
John McCalld935e9c2011-06-15 23:37:01 +00001490 // Don't merge an objc_autorelease with an objc_retain inside a different
1491 // autoreleasepool scope.
1492 return true;
1493 case IC_Retain:
1494 case IC_RetainRV:
1495 // Check for a retain of the same pointer for merging.
1496 return GetObjCArg(Inst) == Arg;
1497 default:
1498 // Nothing else matters for objc_retainAutorelease formation.
1499 return false;
1500 }
John McCalld935e9c2011-06-15 23:37:01 +00001501
1502 case RetainAutoreleaseRVDep: {
1503 InstructionClass Class = GetBasicInstructionClass(Inst);
1504 switch (Class) {
1505 case IC_Retain:
1506 case IC_RetainRV:
1507 // Check for a retain of the same pointer for merging.
1508 return GetObjCArg(Inst) == Arg;
1509 default:
1510 // Anything that can autorelease interrupts
1511 // retainAutoreleaseReturnValue formation.
1512 return CanInterruptRV(Class);
1513 }
John McCalld935e9c2011-06-15 23:37:01 +00001514 }
1515
1516 case RetainRVDep:
1517 return CanInterruptRV(GetBasicInstructionClass(Inst));
1518 }
1519
1520 llvm_unreachable("Invalid dependence flavor");
John McCalld935e9c2011-06-15 23:37:01 +00001521}
1522
Michael Gottesman97e3df02013-01-14 00:35:14 +00001523/// Walk up the CFG from StartPos (which is in StartBB) and find local and
1524/// non-local dependencies on Arg.
1525///
John McCalld935e9c2011-06-15 23:37:01 +00001526/// TODO: Cache results?
1527static void
1528FindDependencies(DependenceKind Flavor,
1529 const Value *Arg,
1530 BasicBlock *StartBB, Instruction *StartInst,
1531 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1532 SmallPtrSet<const BasicBlock *, 4> &Visited,
1533 ProvenanceAnalysis &PA) {
1534 BasicBlock::iterator StartPos = StartInst;
1535
1536 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1537 Worklist.push_back(std::make_pair(StartBB, StartPos));
1538 do {
1539 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1540 Worklist.pop_back_val();
1541 BasicBlock *LocalStartBB = Pair.first;
1542 BasicBlock::iterator LocalStartPos = Pair.second;
1543 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1544 for (;;) {
1545 if (LocalStartPos == StartBBBegin) {
1546 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1547 if (PI == PE)
1548 // If we've reached the function entry, produce a null dependence.
1549 DependingInstructions.insert(0);
1550 else
1551 // Add the predecessors to the worklist.
1552 do {
1553 BasicBlock *PredBB = *PI;
1554 if (Visited.insert(PredBB))
1555 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1556 } while (++PI != PE);
1557 break;
1558 }
1559
1560 Instruction *Inst = --LocalStartPos;
1561 if (Depends(Flavor, Inst, Arg, PA)) {
1562 DependingInstructions.insert(Inst);
1563 break;
1564 }
1565 }
1566 } while (!Worklist.empty());
1567
1568 // Determine whether the original StartBB post-dominates all of the blocks we
1569 // visited. If not, insert a sentinal indicating that most optimizations are
1570 // not safe.
1571 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1572 E = Visited.end(); I != E; ++I) {
1573 const BasicBlock *BB = *I;
1574 if (BB == StartBB)
1575 continue;
1576 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1577 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1578 const BasicBlock *Succ = *SI;
1579 if (Succ != StartBB && !Visited.count(Succ)) {
1580 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1581 return;
1582 }
1583 }
1584 }
1585}
1586
1587static bool isNullOrUndef(const Value *V) {
1588 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1589}
1590
1591static bool isNoopInstruction(const Instruction *I) {
1592 return isa<BitCastInst>(I) ||
1593 (isa<GetElementPtrInst>(I) &&
1594 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1595}
1596
Michael Gottesman97e3df02013-01-14 00:35:14 +00001597/// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1598/// return value.
John McCalld935e9c2011-06-15 23:37:01 +00001599void
1600ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohmandae33492012-04-27 18:56:31 +00001601 ImmutableCallSite CS(GetObjCArg(Retain));
1602 const Instruction *Call = CS.getInstruction();
John McCalld935e9c2011-06-15 23:37:01 +00001603 if (!Call) return;
1604 if (Call->getParent() != Retain->getParent()) return;
1605
1606 // Check that the call is next to the retain.
Dan Gohmandae33492012-04-27 18:56:31 +00001607 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001608 ++I;
1609 while (isNoopInstruction(I)) ++I;
1610 if (&*I != Retain)
1611 return;
1612
1613 // Turn it to an objc_retainAutoreleasedReturnValue..
1614 Changed = true;
1615 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001616
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001617 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
Michael Gottesman9f1be682013-01-12 03:45:49 +00001618 "objc_retain => objc_retainAutoreleasedReturnValue"
1619 " since the operand is a return value.\n"
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001620 " Old: "
1621 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001622
John McCalld935e9c2011-06-15 23:37:01 +00001623 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
Michael Gottesman1e00ac62013-01-04 21:30:38 +00001624
1625 DEBUG(dbgs() << " New: "
1626 << *Retain << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001627}
1628
Michael Gottesman97e3df02013-01-14 00:35:14 +00001629/// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1630/// not a return value. Or, if it can be paired with an
1631/// objc_autoreleaseReturnValue, delete the pair and return true.
John McCalld935e9c2011-06-15 23:37:01 +00001632bool
1633ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001634 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohmandae33492012-04-27 18:56:31 +00001635 const Value *Arg = GetObjCArg(RetainRV);
1636 ImmutableCallSite CS(Arg);
1637 if (const Instruction *Call = CS.getInstruction()) {
John McCalld935e9c2011-06-15 23:37:01 +00001638 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohmandae33492012-04-27 18:56:31 +00001639 BasicBlock::const_iterator I = Call;
John McCalld935e9c2011-06-15 23:37:01 +00001640 ++I;
1641 while (isNoopInstruction(I)) ++I;
1642 if (&*I == RetainRV)
1643 return false;
Dan Gohmandae33492012-04-27 18:56:31 +00001644 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001645 BasicBlock *RetainRVParent = RetainRV->getParent();
1646 if (II->getNormalDest() == RetainRVParent) {
Dan Gohmandae33492012-04-27 18:56:31 +00001647 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001648 while (isNoopInstruction(I)) ++I;
1649 if (&*I == RetainRV)
1650 return false;
1651 }
John McCalld935e9c2011-06-15 23:37:01 +00001652 }
Dan Gohmane3ed2b02012-03-23 18:09:00 +00001653 }
John McCalld935e9c2011-06-15 23:37:01 +00001654
1655 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1656 // pointer. In this case, we can delete the pair.
1657 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1658 if (I != Begin) {
1659 do --I; while (I != Begin && isNoopInstruction(I));
1660 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1661 GetObjCArg(I) == Arg) {
1662 Changed = true;
1663 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001664
Michael Gottesman5c32ce92013-01-05 17:55:35 +00001665 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
1666 << " Erasing " << *RetainRV
1667 << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001668
John McCalld935e9c2011-06-15 23:37:01 +00001669 EraseInstruction(I);
1670 EraseInstruction(RetainRV);
1671 return true;
1672 }
1673 }
1674
1675 // Turn it to a plain objc_retain.
1676 Changed = true;
1677 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00001678
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001679 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1680 "objc_retainAutoreleasedReturnValue => "
1681 "objc_retain since the operand is not a return value.\n"
1682 " Old: "
1683 << *RetainRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001684
John McCalld935e9c2011-06-15 23:37:01 +00001685 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
Michael Gottesmandef07bb2013-01-05 17:55:42 +00001686
1687 DEBUG(dbgs() << " New: "
1688 << *RetainRV << "\n");
1689
John McCalld935e9c2011-06-15 23:37:01 +00001690 return false;
1691}
1692
Michael Gottesman97e3df02013-01-14 00:35:14 +00001693/// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1694/// used as a return value.
John McCalld935e9c2011-06-15 23:37:01 +00001695void
Michael Gottesman556ff612013-01-12 01:25:19 +00001696ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1697 InstructionClass &Class) {
John McCalld935e9c2011-06-15 23:37:01 +00001698 // Check for a return of the pointer value.
1699 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman10a18d52011-08-12 00:36:31 +00001700 SmallVector<const Value *, 2> Users;
1701 Users.push_back(Ptr);
1702 do {
1703 Ptr = Users.pop_back_val();
1704 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1705 UI != UE; ++UI) {
1706 const User *I = *UI;
1707 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1708 return;
1709 if (isa<BitCastInst>(I))
1710 Users.push_back(I);
1711 }
1712 } while (!Users.empty());
John McCalld935e9c2011-06-15 23:37:01 +00001713
1714 Changed = true;
1715 ++NumPeeps;
Michael Gottesman1bf69082013-01-06 21:07:11 +00001716
1717 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1718 "objc_autoreleaseReturnValue => "
1719 "objc_autorelease since its operand is not used as a return "
1720 "value.\n"
1721 " Old: "
1722 << *AutoreleaseRV << "\n");
1723
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001724 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1725 AutoreleaseRVCI->
John McCalld935e9c2011-06-15 23:37:01 +00001726 setCalledFunction(getAutoreleaseCallee(F.getParent()));
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001727 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
Michael Gottesman556ff612013-01-12 01:25:19 +00001728 Class = IC_Autorelease;
Michael Gottesman10426b52013-01-07 21:26:07 +00001729
Michael Gottesman1bf69082013-01-06 21:07:11 +00001730 DEBUG(dbgs() << " New: "
1731 << *AutoreleaseRV << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001732
John McCalld935e9c2011-06-15 23:37:01 +00001733}
1734
Michael Gottesman97e3df02013-01-14 00:35:14 +00001735/// Visit each call, one at a time, and make simplifications without doing any
1736/// additional analysis.
John McCalld935e9c2011-06-15 23:37:01 +00001737void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1738 // Reset all the flags in preparation for recomputing them.
1739 UsedInThisFunction = 0;
1740
1741 // Visit all objc_* calls in F.
1742 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1743 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00001744
John McCalld935e9c2011-06-15 23:37:01 +00001745 InstructionClass Class = GetBasicInstructionClass(Inst);
1746
Michael Gottesmand359e062013-01-18 03:08:39 +00001747 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
1748 << Class << "; " << *Inst << "\n");
Michael Gottesman782e3442013-01-17 18:32:34 +00001749
John McCalld935e9c2011-06-15 23:37:01 +00001750 switch (Class) {
1751 default: break;
1752
1753 // Delete no-op casts. These function calls have special semantics, but
1754 // the semantics are entirely implemented via lowering in the front-end,
1755 // so by the time they reach the optimizer, they are just no-op calls
1756 // which return their argument.
1757 //
1758 // There are gray areas here, as the ability to cast reference-counted
1759 // pointers to raw void* and back allows code to break ARC assumptions,
1760 // however these are currently considered to be unimportant.
1761 case IC_NoopCast:
1762 Changed = true;
1763 ++NumNoops;
Michael Gottesmandc042f02013-01-06 21:07:15 +00001764 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
1765 " " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001766 EraseInstruction(Inst);
1767 continue;
1768
1769 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1770 case IC_StoreWeak:
1771 case IC_LoadWeak:
1772 case IC_LoadWeakRetained:
1773 case IC_InitWeak:
1774 case IC_DestroyWeak: {
1775 CallInst *CI = cast<CallInst>(Inst);
1776 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001777 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001778 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001779 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1780 Constant::getNullValue(Ty),
1781 CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00001782 llvm::Value *NewValue = UndefValue::get(CI->getType());
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001783 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1784 "pointer-to-weak-pointer is undefined behavior.\n"
1785 " Old = " << *CI <<
1786 "\n New = " <<
Michael Gottesman10426b52013-01-07 21:26:07 +00001787 *NewValue << "\n");
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001788 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001789 CI->eraseFromParent();
1790 continue;
1791 }
1792 break;
1793 }
1794 case IC_CopyWeak:
1795 case IC_MoveWeak: {
1796 CallInst *CI = cast<CallInst>(Inst);
1797 if (isNullOrUndef(CI->getArgOperand(0)) ||
1798 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohman670f9372012-04-13 18:57:48 +00001799 Changed = true;
Chris Lattner229907c2011-07-18 04:54:35 +00001800 Type *Ty = CI->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001801 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1802 Constant::getNullValue(Ty),
1803 CI);
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001804
1805 llvm::Value *NewValue = UndefValue::get(CI->getType());
1806 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1807 "pointer-to-weak-pointer is undefined behavior.\n"
1808 " Old = " << *CI <<
1809 "\n New = " <<
1810 *NewValue << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001811
Michael Gottesmanfec61c02013-01-06 21:54:30 +00001812 CI->replaceAllUsesWith(NewValue);
John McCalld935e9c2011-06-15 23:37:01 +00001813 CI->eraseFromParent();
1814 continue;
1815 }
1816 break;
1817 }
1818 case IC_Retain:
1819 OptimizeRetainCall(F, Inst);
1820 break;
1821 case IC_RetainRV:
1822 if (OptimizeRetainRVCall(F, Inst))
1823 continue;
1824 break;
1825 case IC_AutoreleaseRV:
Michael Gottesman556ff612013-01-12 01:25:19 +00001826 OptimizeAutoreleaseRVCall(F, Inst, Class);
John McCalld935e9c2011-06-15 23:37:01 +00001827 break;
1828 }
1829
1830 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1831 if (IsAutorelease(Class) && Inst->use_empty()) {
1832 CallInst *Call = cast<CallInst>(Inst);
1833 const Value *Arg = Call->getArgOperand(0);
1834 Arg = FindSingleUseIdentifiedObject(Arg);
1835 if (Arg) {
1836 Changed = true;
1837 ++NumAutoreleases;
1838
1839 // Create the declaration lazily.
1840 LLVMContext &C = Inst->getContext();
1841 CallInst *NewCall =
1842 CallInst::Create(getReleaseCallee(F.getParent()),
1843 Call->getArgOperand(0), "", Call);
1844 NewCall->setMetadata(ImpreciseReleaseMDKind,
1845 MDNode::get(C, ArrayRef<Value *>()));
Michael Gottesman10426b52013-01-07 21:26:07 +00001846
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001847 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
1848 "objc_autorelease(x) with objc_release(x) since x is "
1849 "otherwise unused.\n"
Michael Gottesman4bf6e752013-01-06 22:56:54 +00001850 " Old: " << *Call <<
Michael Gottesmana6a1dad2013-01-06 22:56:50 +00001851 "\n New: " <<
1852 *NewCall << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00001853
John McCalld935e9c2011-06-15 23:37:01 +00001854 EraseInstruction(Call);
1855 Inst = NewCall;
1856 Class = IC_Release;
1857 }
1858 }
1859
1860 // For functions which can never be passed stack arguments, add
1861 // a tail keyword.
1862 if (IsAlwaysTail(Class)) {
1863 Changed = true;
Michael Gottesman2d763312013-01-06 23:39:09 +00001864 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
1865 " to function since it can never be passed stack args: " << *Inst <<
1866 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001867 cast<CallInst>(Inst)->setTailCall();
1868 }
1869
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001870 // Ensure that functions that can never have a "tail" keyword due to the
1871 // semantics of ARC truly do not do so.
1872 if (IsNeverTail(Class)) {
1873 Changed = true;
Michael Gottesman4385edf2013-01-14 01:47:53 +00001874 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
1875 "keyword from function: " << *Inst <<
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00001876 "\n");
1877 cast<CallInst>(Inst)->setTailCall(false);
1878 }
1879
John McCalld935e9c2011-06-15 23:37:01 +00001880 // Set nounwind as needed.
1881 if (IsNoThrow(Class)) {
1882 Changed = true;
Michael Gottesman8800a512013-01-06 23:39:13 +00001883 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
1884 " class. Setting nounwind on: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001885 cast<CallInst>(Inst)->setDoesNotThrow();
1886 }
1887
1888 if (!IsNoopOnNull(Class)) {
1889 UsedInThisFunction |= 1 << Class;
1890 continue;
1891 }
1892
1893 const Value *Arg = GetObjCArg(Inst);
1894
1895 // ARC calls with null are no-ops. Delete them.
1896 if (isNullOrUndef(Arg)) {
1897 Changed = true;
1898 ++NumNoops;
Michael Gottesman5b970e12013-01-07 00:04:52 +00001899 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
1900 " null are no-ops. Erasing: " << *Inst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001901 EraseInstruction(Inst);
1902 continue;
1903 }
1904
1905 // Keep track of which of retain, release, autorelease, and retain_block
1906 // are actually present in this function.
1907 UsedInThisFunction |= 1 << Class;
1908
1909 // If Arg is a PHI, and one or more incoming values to the
1910 // PHI are null, and the call is control-equivalent to the PHI, and there
1911 // are no relevant side effects between the PHI and the call, the call
1912 // could be pushed up to just those paths with non-null incoming values.
1913 // For now, don't bother splitting critical edges for this.
1914 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1915 Worklist.push_back(std::make_pair(Inst, Arg));
1916 do {
1917 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1918 Inst = Pair.first;
1919 Arg = Pair.second;
1920
1921 const PHINode *PN = dyn_cast<PHINode>(Arg);
1922 if (!PN) continue;
1923
1924 // Determine if the PHI has any null operands, or any incoming
1925 // critical edges.
1926 bool HasNull = false;
1927 bool HasCriticalEdges = false;
1928 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1929 Value *Incoming =
1930 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1931 if (isNullOrUndef(Incoming))
1932 HasNull = true;
1933 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1934 .getNumSuccessors() != 1) {
1935 HasCriticalEdges = true;
1936 break;
1937 }
1938 }
1939 // If we have null operands and no critical edges, optimize.
1940 if (!HasCriticalEdges && HasNull) {
1941 SmallPtrSet<Instruction *, 4> DependingInstructions;
1942 SmallPtrSet<const BasicBlock *, 4> Visited;
1943
1944 // Check that there is nothing that cares about the reference
1945 // count between the call and the phi.
Dan Gohman8478d762012-04-13 00:59:57 +00001946 switch (Class) {
1947 case IC_Retain:
1948 case IC_RetainBlock:
1949 // These can always be moved up.
1950 break;
1951 case IC_Release:
Dan Gohman41375a32012-05-08 23:39:44 +00001952 // These can't be moved across things that care about the retain
1953 // count.
Dan Gohman8478d762012-04-13 00:59:57 +00001954 FindDependencies(NeedsPositiveRetainCount, Arg,
1955 Inst->getParent(), Inst,
1956 DependingInstructions, Visited, PA);
1957 break;
1958 case IC_Autorelease:
1959 // These can't be moved across autorelease pool scope boundaries.
1960 FindDependencies(AutoreleasePoolBoundary, Arg,
1961 Inst->getParent(), Inst,
1962 DependingInstructions, Visited, PA);
1963 break;
1964 case IC_RetainRV:
1965 case IC_AutoreleaseRV:
1966 // Don't move these; the RV optimization depends on the autoreleaseRV
1967 // being tail called, and the retainRV being immediately after a call
1968 // (which might still happen if we get lucky with codegen layout, but
1969 // it's not worth taking the chance).
1970 continue;
1971 default:
1972 llvm_unreachable("Invalid dependence flavor");
1973 }
1974
John McCalld935e9c2011-06-15 23:37:01 +00001975 if (DependingInstructions.size() == 1 &&
1976 *DependingInstructions.begin() == PN) {
1977 Changed = true;
1978 ++NumPartialNoops;
1979 // Clone the call into each predecessor that has a non-null value.
1980 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattner229907c2011-07-18 04:54:35 +00001981 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCalld935e9c2011-06-15 23:37:01 +00001982 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1983 Value *Incoming =
1984 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1985 if (!isNullOrUndef(Incoming)) {
1986 CallInst *Clone = cast<CallInst>(CInst->clone());
1987 Value *Op = PN->getIncomingValue(i);
1988 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1989 if (Op->getType() != ParamTy)
1990 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1991 Clone->setArgOperand(0, Op);
1992 Clone->insertBefore(InsertPos);
Michael Gottesmanc189a392013-01-09 19:23:24 +00001993
1994 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
1995 << *CInst << "\n"
1996 " And inserting "
1997 "clone at " << *InsertPos << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00001998 Worklist.push_back(std::make_pair(Clone, Incoming));
1999 }
2000 }
2001 // Erase the original call.
Michael Gottesmanc189a392013-01-09 19:23:24 +00002002 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002003 EraseInstruction(CInst);
2004 continue;
2005 }
2006 }
2007 } while (!Worklist.empty());
2008 }
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00002009 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
John McCalld935e9c2011-06-15 23:37:01 +00002010}
2011
Michael Gottesman97e3df02013-01-14 00:35:14 +00002012/// Check for critical edges, loop boundaries, irreducible control flow, or
2013/// other CFG structures where moving code across the edge would result in it
2014/// being executed more.
John McCalld935e9c2011-06-15 23:37:01 +00002015void
2016ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2017 DenseMap<const BasicBlock *, BBState> &BBStates,
2018 BBState &MyStates) const {
2019 // If any top-down local-use or possible-dec has a succ which is earlier in
2020 // the sequence, forget it.
Dan Gohman55b06742012-03-02 01:13:53 +00002021 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCalld935e9c2011-06-15 23:37:01 +00002022 E = MyStates.top_down_ptr_end(); I != E; ++I)
2023 switch (I->second.GetSeq()) {
2024 default: break;
2025 case S_Use: {
2026 const Value *Arg = I->first;
2027 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2028 bool SomeSuccHasSame = false;
2029 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002030 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002031 succ_const_iterator SI(TI), SE(TI, false);
2032
Dan Gohman0155f302012-02-17 18:59:53 +00002033 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002034 Sequence SuccSSeq = S_None;
2035 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002036 // If VisitBottomUp has pointer information for this successor, take
2037 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002038 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2039 BBStates.find(*SI);
2040 assert(BBI != BBStates.end());
2041 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2042 SuccSSeq = SuccS.GetSeq();
2043 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002044 switch (SuccSSeq) {
John McCalld935e9c2011-06-15 23:37:01 +00002045 case S_None:
Dan Gohman12130272011-08-12 00:26:31 +00002046 case S_CanRelease: {
Dan Gohman362eb692012-03-02 01:26:46 +00002047 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002048 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002049 break;
2050 }
Dan Gohman12130272011-08-12 00:26:31 +00002051 continue;
2052 }
John McCalld935e9c2011-06-15 23:37:01 +00002053 case S_Use:
2054 SomeSuccHasSame = true;
2055 break;
2056 case S_Stop:
2057 case S_Release:
2058 case S_MovableRelease:
Dan Gohman362eb692012-03-02 01:26:46 +00002059 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002060 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002061 break;
2062 case S_Retain:
2063 llvm_unreachable("bottom-up pointer in retain state!");
2064 }
Dan Gohman12130272011-08-12 00:26:31 +00002065 }
John McCalld935e9c2011-06-15 23:37:01 +00002066 // If the state at the other end of any of the successor edges
2067 // matches the current state, require all edges to match. This
2068 // guards against loops in the middle of a sequence.
2069 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002070 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002071 break;
John McCalld935e9c2011-06-15 23:37:01 +00002072 }
2073 case S_CanRelease: {
2074 const Value *Arg = I->first;
2075 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2076 bool SomeSuccHasSame = false;
2077 bool AllSuccsHaveSame = true;
Dan Gohman55b06742012-03-02 01:13:53 +00002078 PtrState &S = I->second;
Dan Gohman0155f302012-02-17 18:59:53 +00002079 succ_const_iterator SI(TI), SE(TI, false);
2080
Dan Gohman0155f302012-02-17 18:59:53 +00002081 for (; SI != SE; ++SI) {
Dan Gohman362eb692012-03-02 01:26:46 +00002082 Sequence SuccSSeq = S_None;
2083 bool SuccSRRIKnownSafe = false;
Dan Gohman41375a32012-05-08 23:39:44 +00002084 // If VisitBottomUp has pointer information for this successor, take
2085 // what we know about it.
Dan Gohmandae33492012-04-27 18:56:31 +00002086 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2087 BBStates.find(*SI);
2088 assert(BBI != BBStates.end());
2089 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2090 SuccSSeq = SuccS.GetSeq();
2091 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman362eb692012-03-02 01:26:46 +00002092 switch (SuccSSeq) {
Dan Gohman12130272011-08-12 00:26:31 +00002093 case S_None: {
Dan Gohman362eb692012-03-02 01:26:46 +00002094 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohman12130272011-08-12 00:26:31 +00002095 S.ClearSequenceProgress();
Dan Gohman362eb692012-03-02 01:26:46 +00002096 break;
2097 }
Dan Gohman12130272011-08-12 00:26:31 +00002098 continue;
2099 }
John McCalld935e9c2011-06-15 23:37:01 +00002100 case S_CanRelease:
2101 SomeSuccHasSame = true;
2102 break;
2103 case S_Stop:
2104 case S_Release:
2105 case S_MovableRelease:
2106 case S_Use:
Dan Gohman362eb692012-03-02 01:26:46 +00002107 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohman12130272011-08-12 00:26:31 +00002108 AllSuccsHaveSame = false;
John McCalld935e9c2011-06-15 23:37:01 +00002109 break;
2110 case S_Retain:
2111 llvm_unreachable("bottom-up pointer in retain state!");
2112 }
Dan Gohman12130272011-08-12 00:26:31 +00002113 }
John McCalld935e9c2011-06-15 23:37:01 +00002114 // If the state at the other end of any of the successor edges
2115 // matches the current state, require all edges to match. This
2116 // guards against loops in the middle of a sequence.
2117 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohman12130272011-08-12 00:26:31 +00002118 S.ClearSequenceProgress();
Dan Gohman044437062011-12-12 18:13:53 +00002119 break;
John McCalld935e9c2011-06-15 23:37:01 +00002120 }
2121 }
2122}
2123
2124bool
Dan Gohman817a7c62012-03-22 18:24:56 +00002125ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohman5c70fad2012-03-23 17:47:54 +00002126 BasicBlock *BB,
Dan Gohman817a7c62012-03-22 18:24:56 +00002127 MapVector<Value *, RRInfo> &Retains,
2128 BBState &MyStates) {
2129 bool NestingDetected = false;
2130 InstructionClass Class = GetInstructionClass(Inst);
2131 const Value *Arg = 0;
2132
2133 switch (Class) {
2134 case IC_Release: {
2135 Arg = GetObjCArg(Inst);
2136
2137 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2138
2139 // If we see two releases in a row on the same pointer. If so, make
2140 // a note, and we'll cicle back to revisit it after we've
2141 // hopefully eliminated the second release, which may allow us to
2142 // eliminate the first release too.
2143 // Theoretically we could implement removal of nested retain+release
2144 // pairs by making PtrState hold a stack of states, but this is
2145 // simple and avoids adding overhead for the non-nested case.
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002146 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2147 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2148 "releases (i.e. a release pair)\n");
Dan Gohman817a7c62012-03-22 18:24:56 +00002149 NestingDetected = true;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002150 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002151
Dan Gohman817a7c62012-03-22 18:24:56 +00002152 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman62079b42012-04-25 00:50:46 +00002153 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohman817a7c62012-03-22 18:24:56 +00002154 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohmandf476e52012-09-04 23:16:20 +00002155 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohman817a7c62012-03-22 18:24:56 +00002156 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2157 S.RRI.Calls.insert(Inst);
2158
Dan Gohmandf476e52012-09-04 23:16:20 +00002159 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002160 break;
2161 }
2162 case IC_RetainBlock:
2163 // An objc_retainBlock call with just a use may need to be kept,
2164 // because it may be copying a block from the stack to the heap.
2165 if (!IsRetainBlockOptimizable(Inst))
2166 break;
2167 // FALLTHROUGH
2168 case IC_Retain:
2169 case IC_RetainRV: {
2170 Arg = GetObjCArg(Inst);
2171
2172 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman62079b42012-04-25 00:50:46 +00002173 S.SetKnownPositiveRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002174
2175 switch (S.GetSeq()) {
2176 case S_Stop:
2177 case S_Release:
2178 case S_MovableRelease:
2179 case S_Use:
2180 S.RRI.ReverseInsertPts.clear();
2181 // FALL THROUGH
2182 case S_CanRelease:
2183 // Don't do retain+release tracking for IC_RetainRV, because it's
2184 // better to let it remain as the first instruction after a call.
2185 if (Class != IC_RetainRV) {
2186 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2187 Retains[Inst] = S.RRI;
2188 }
2189 S.ClearSequenceProgress();
2190 break;
2191 case S_None:
2192 break;
2193 case S_Retain:
2194 llvm_unreachable("bottom-up pointer in retain state!");
2195 }
2196 return NestingDetected;
2197 }
2198 case IC_AutoreleasepoolPop:
2199 // Conservatively, clear MyStates for all known pointers.
2200 MyStates.clearBottomUpPointers();
2201 return NestingDetected;
2202 case IC_AutoreleasepoolPush:
2203 case IC_None:
2204 // These are irrelevant.
2205 return NestingDetected;
2206 default:
2207 break;
2208 }
2209
2210 // Consider any other possible effects of this instruction on each
2211 // pointer being tracked.
2212 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2213 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2214 const Value *Ptr = MI->first;
2215 if (Ptr == Arg)
2216 continue; // Handled above.
2217 PtrState &S = MI->second;
2218 Sequence Seq = S.GetSeq();
2219
2220 // Check for possible releases.
2221 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00002222 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002223 switch (Seq) {
2224 case S_Use:
2225 S.SetSeq(S_CanRelease);
2226 continue;
2227 case S_CanRelease:
2228 case S_Release:
2229 case S_MovableRelease:
2230 case S_Stop:
2231 case S_None:
2232 break;
2233 case S_Retain:
2234 llvm_unreachable("bottom-up pointer in retain state!");
2235 }
2236 }
2237
2238 // Check for possible direct uses.
2239 switch (Seq) {
2240 case S_Release:
2241 case S_MovableRelease:
2242 if (CanUse(Inst, Ptr, PA, Class)) {
2243 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002244 // If this is an invoke instruction, we're scanning it as part of
2245 // one of its successor blocks, since we can't insert code after it
2246 // in its own block, and we don't want to split critical edges.
2247 if (isa<InvokeInst>(Inst))
2248 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2249 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002250 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002251 S.SetSeq(S_Use);
2252 } else if (Seq == S_Release &&
2253 (Class == IC_User || Class == IC_CallOrUser)) {
2254 // Non-movable releases depend on any possible objc pointer use.
2255 S.SetSeq(S_Stop);
2256 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohman5c70fad2012-03-23 17:47:54 +00002257 // As above; handle invoke specially.
2258 if (isa<InvokeInst>(Inst))
2259 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2260 else
Francois Pichet4b9ab742012-03-24 01:36:37 +00002261 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohman817a7c62012-03-22 18:24:56 +00002262 }
2263 break;
2264 case S_Stop:
2265 if (CanUse(Inst, Ptr, PA, Class))
2266 S.SetSeq(S_Use);
2267 break;
2268 case S_CanRelease:
2269 case S_Use:
2270 case S_None:
2271 break;
2272 case S_Retain:
2273 llvm_unreachable("bottom-up pointer in retain state!");
2274 }
2275 }
2276
2277 return NestingDetected;
2278}
2279
2280bool
John McCalld935e9c2011-06-15 23:37:01 +00002281ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2282 DenseMap<const BasicBlock *, BBState> &BBStates,
2283 MapVector<Value *, RRInfo> &Retains) {
2284 bool NestingDetected = false;
2285 BBState &MyStates = BBStates[BB];
2286
2287 // Merge the states from each successor to compute the initial state
2288 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002289 BBState::edge_iterator SI(MyStates.succ_begin()),
2290 SE(MyStates.succ_end());
2291 if (SI != SE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002292 const BasicBlock *Succ = *SI;
2293 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2294 assert(I != BBStates.end());
2295 MyStates.InitFromSucc(I->second);
2296 ++SI;
2297 for (; SI != SE; ++SI) {
2298 Succ = *SI;
2299 I = BBStates.find(Succ);
2300 assert(I != BBStates.end());
2301 MyStates.MergeSucc(I->second);
2302 }
Dan Gohman0155f302012-02-17 18:59:53 +00002303 }
John McCalld935e9c2011-06-15 23:37:01 +00002304
2305 // Visit all the instructions, bottom-up.
2306 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2307 Instruction *Inst = llvm::prior(I);
Dan Gohman5c70fad2012-03-23 17:47:54 +00002308
2309 // Invoke instructions are visited as part of their successors (below).
2310 if (isa<InvokeInst>(Inst))
2311 continue;
2312
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002313 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2314
Dan Gohman5c70fad2012-03-23 17:47:54 +00002315 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2316 }
2317
Dan Gohmandae33492012-04-27 18:56:31 +00002318 // If there's a predecessor with an invoke, visit the invoke as if it were
2319 // part of this block, since we can't insert code after an invoke in its own
2320 // block, and we don't want to split critical edges.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002321 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2322 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002323 BasicBlock *Pred = *PI;
Dan Gohmandae33492012-04-27 18:56:31 +00002324 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2325 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohman817a7c62012-03-22 18:24:56 +00002326 }
John McCalld935e9c2011-06-15 23:37:01 +00002327
Dan Gohman817a7c62012-03-22 18:24:56 +00002328 return NestingDetected;
2329}
John McCalld935e9c2011-06-15 23:37:01 +00002330
Dan Gohman817a7c62012-03-22 18:24:56 +00002331bool
2332ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2333 DenseMap<Value *, RRInfo> &Releases,
2334 BBState &MyStates) {
2335 bool NestingDetected = false;
2336 InstructionClass Class = GetInstructionClass(Inst);
2337 const Value *Arg = 0;
John McCalld935e9c2011-06-15 23:37:01 +00002338
Dan Gohman817a7c62012-03-22 18:24:56 +00002339 switch (Class) {
2340 case IC_RetainBlock:
2341 // An objc_retainBlock call with just a use may need to be kept,
2342 // because it may be copying a block from the stack to the heap.
2343 if (!IsRetainBlockOptimizable(Inst))
2344 break;
2345 // FALLTHROUGH
2346 case IC_Retain:
2347 case IC_RetainRV: {
2348 Arg = GetObjCArg(Inst);
2349
2350 PtrState &S = MyStates.getPtrTopDownState(Arg);
2351
2352 // Don't do retain+release tracking for IC_RetainRV, because it's
2353 // better to let it remain as the first instruction after a call.
2354 if (Class != IC_RetainRV) {
2355 // If we see two retains in a row on the same pointer. If so, make
John McCalld935e9c2011-06-15 23:37:01 +00002356 // a note, and we'll cicle back to revisit it after we've
Dan Gohman817a7c62012-03-22 18:24:56 +00002357 // hopefully eliminated the second retain, which may allow us to
2358 // eliminate the first retain too.
John McCalld935e9c2011-06-15 23:37:01 +00002359 // Theoretically we could implement removal of nested retain+release
2360 // pairs by making PtrState hold a stack of states, but this is
2361 // simple and avoids adding overhead for the non-nested case.
Dan Gohman817a7c62012-03-22 18:24:56 +00002362 if (S.GetSeq() == S_Retain)
John McCalld935e9c2011-06-15 23:37:01 +00002363 NestingDetected = true;
2364
Dan Gohman62079b42012-04-25 00:50:46 +00002365 S.ResetSequenceProgress(S_Retain);
Dan Gohman817a7c62012-03-22 18:24:56 +00002366 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmandf476e52012-09-04 23:16:20 +00002367 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCalld935e9c2011-06-15 23:37:01 +00002368 S.RRI.Calls.insert(Inst);
John McCalld935e9c2011-06-15 23:37:01 +00002369 }
John McCalld935e9c2011-06-15 23:37:01 +00002370
Dan Gohmandf476e52012-09-04 23:16:20 +00002371 S.SetKnownPositiveRefCount();
Dan Gohmanf64ff8e2012-07-23 19:27:31 +00002372
2373 // A retain can be a potential use; procede to the generic checking
2374 // code below.
2375 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002376 }
2377 case IC_Release: {
2378 Arg = GetObjCArg(Inst);
2379
2380 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohmandf476e52012-09-04 23:16:20 +00002381 S.ClearRefCount();
Dan Gohman817a7c62012-03-22 18:24:56 +00002382
2383 switch (S.GetSeq()) {
2384 case S_Retain:
2385 case S_CanRelease:
2386 S.RRI.ReverseInsertPts.clear();
2387 // FALL THROUGH
2388 case S_Use:
2389 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2390 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2391 Releases[Inst] = S.RRI;
2392 S.ClearSequenceProgress();
2393 break;
2394 case S_None:
2395 break;
2396 case S_Stop:
2397 case S_Release:
2398 case S_MovableRelease:
2399 llvm_unreachable("top-down pointer in release state!");
2400 }
2401 break;
2402 }
2403 case IC_AutoreleasepoolPop:
2404 // Conservatively, clear MyStates for all known pointers.
2405 MyStates.clearTopDownPointers();
2406 return NestingDetected;
2407 case IC_AutoreleasepoolPush:
2408 case IC_None:
2409 // These are irrelevant.
2410 return NestingDetected;
2411 default:
2412 break;
2413 }
2414
2415 // Consider any other possible effects of this instruction on each
2416 // pointer being tracked.
2417 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2418 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2419 const Value *Ptr = MI->first;
2420 if (Ptr == Arg)
2421 continue; // Handled above.
2422 PtrState &S = MI->second;
2423 Sequence Seq = S.GetSeq();
2424
2425 // Check for possible releases.
2426 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman62079b42012-04-25 00:50:46 +00002427 S.ClearRefCount();
John McCalld935e9c2011-06-15 23:37:01 +00002428 switch (Seq) {
Dan Gohman817a7c62012-03-22 18:24:56 +00002429 case S_Retain:
2430 S.SetSeq(S_CanRelease);
2431 assert(S.RRI.ReverseInsertPts.empty());
2432 S.RRI.ReverseInsertPts.insert(Inst);
2433
2434 // One call can't cause a transition from S_Retain to S_CanRelease
2435 // and S_CanRelease to S_Use. If we've made the first transition,
2436 // we're done.
2437 continue;
John McCalld935e9c2011-06-15 23:37:01 +00002438 case S_Use:
Dan Gohman817a7c62012-03-22 18:24:56 +00002439 case S_CanRelease:
John McCalld935e9c2011-06-15 23:37:01 +00002440 case S_None:
2441 break;
Dan Gohman817a7c62012-03-22 18:24:56 +00002442 case S_Stop:
2443 case S_Release:
2444 case S_MovableRelease:
2445 llvm_unreachable("top-down pointer in release state!");
John McCalld935e9c2011-06-15 23:37:01 +00002446 }
2447 }
Dan Gohman817a7c62012-03-22 18:24:56 +00002448
2449 // Check for possible direct uses.
2450 switch (Seq) {
2451 case S_CanRelease:
2452 if (CanUse(Inst, Ptr, PA, Class))
2453 S.SetSeq(S_Use);
2454 break;
2455 case S_Retain:
2456 case S_Use:
2457 case S_None:
2458 break;
2459 case S_Stop:
2460 case S_Release:
2461 case S_MovableRelease:
2462 llvm_unreachable("top-down pointer in release state!");
2463 }
John McCalld935e9c2011-06-15 23:37:01 +00002464 }
2465
2466 return NestingDetected;
2467}
2468
2469bool
2470ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2471 DenseMap<const BasicBlock *, BBState> &BBStates,
2472 DenseMap<Value *, RRInfo> &Releases) {
2473 bool NestingDetected = false;
2474 BBState &MyStates = BBStates[BB];
2475
2476 // Merge the states from each predecessor to compute the initial state
2477 // for the current block.
Dan Gohman10c82ce2012-08-27 18:31:36 +00002478 BBState::edge_iterator PI(MyStates.pred_begin()),
2479 PE(MyStates.pred_end());
2480 if (PI != PE) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002481 const BasicBlock *Pred = *PI;
2482 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2483 assert(I != BBStates.end());
2484 MyStates.InitFromPred(I->second);
2485 ++PI;
2486 for (; PI != PE; ++PI) {
2487 Pred = *PI;
2488 I = BBStates.find(Pred);
2489 assert(I != BBStates.end());
2490 MyStates.MergePred(I->second);
2491 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002492 }
John McCalld935e9c2011-06-15 23:37:01 +00002493
2494 // Visit all the instructions, top-down.
2495 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2496 Instruction *Inst = I;
Michael Gottesmanaf2113f2013-01-13 07:00:51 +00002497
2498 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
2499
Dan Gohman817a7c62012-03-22 18:24:56 +00002500 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCalld935e9c2011-06-15 23:37:01 +00002501 }
2502
2503 CheckForCFGHazards(BB, BBStates, MyStates);
2504 return NestingDetected;
2505}
2506
Dan Gohmana53a12c2011-12-12 19:42:25 +00002507static void
2508ComputePostOrders(Function &F,
2509 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002510 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2511 unsigned NoObjCARCExceptionsMDKind,
2512 DenseMap<const BasicBlock *, BBState> &BBStates) {
Michael Gottesman97e3df02013-01-14 00:35:14 +00002513 /// The visited set, for doing DFS walks.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002514 SmallPtrSet<BasicBlock *, 16> Visited;
2515
2516 // Do DFS, computing the PostOrder.
2517 SmallPtrSet<BasicBlock *, 16> OnStack;
2518 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002519
2520 // Functions always have exactly one entry block, and we don't have
2521 // any other block that we treat like an entry block.
Dan Gohmana53a12c2011-12-12 19:42:25 +00002522 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman41375a32012-05-08 23:39:44 +00002523 BBState &MyStates = BBStates[EntryBB];
2524 MyStates.SetAsEntry();
2525 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2526 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002527 Visited.insert(EntryBB);
2528 OnStack.insert(EntryBB);
2529 do {
2530 dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002531 BasicBlock *CurrBB = SuccStack.back().first;
2532 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2533 succ_iterator SE(TI, false);
Dan Gohman41375a32012-05-08 23:39:44 +00002534
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002535 while (SuccStack.back().second != SE) {
2536 BasicBlock *SuccBB = *SuccStack.back().second++;
2537 if (Visited.insert(SuccBB)) {
Dan Gohman41375a32012-05-08 23:39:44 +00002538 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2539 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002540 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman41375a32012-05-08 23:39:44 +00002541 BBState &SuccStates = BBStates[SuccBB];
2542 SuccStates.addPred(CurrBB);
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002543 OnStack.insert(SuccBB);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002544 goto dfs_next_succ;
2545 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002546
2547 if (!OnStack.count(SuccBB)) {
2548 BBStates[CurrBB].addSucc(SuccBB);
2549 BBStates[SuccBB].addPred(CurrBB);
2550 }
Dan Gohmana53a12c2011-12-12 19:42:25 +00002551 }
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002552 OnStack.erase(CurrBB);
2553 PostOrder.push_back(CurrBB);
2554 SuccStack.pop_back();
Dan Gohmana53a12c2011-12-12 19:42:25 +00002555 } while (!SuccStack.empty());
2556
2557 Visited.clear();
2558
Dan Gohmana53a12c2011-12-12 19:42:25 +00002559 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002560 // Functions may have many exits, and there also blocks which we treat
2561 // as exits due to ignored edges.
2562 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2563 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2564 BasicBlock *ExitBB = I;
2565 BBState &MyStates = BBStates[ExitBB];
2566 if (!MyStates.isExit())
2567 continue;
2568
Dan Gohmandae33492012-04-27 18:56:31 +00002569 MyStates.SetAsExit();
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002570
2571 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002572 Visited.insert(ExitBB);
2573 while (!PredStack.empty()) {
2574 reverse_dfs_next_succ:
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002575 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2576 while (PredStack.back().second != PE) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002577 BasicBlock *BB = *PredStack.back().second++;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002578 if (Visited.insert(BB)) {
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002579 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohmana53a12c2011-12-12 19:42:25 +00002580 goto reverse_dfs_next_succ;
2581 }
2582 }
2583 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2584 }
2585 }
2586}
2587
Michael Gottesman97e3df02013-01-14 00:35:14 +00002588// Visit the function both top-down and bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002589bool
2590ObjCARCOpt::Visit(Function &F,
2591 DenseMap<const BasicBlock *, BBState> &BBStates,
2592 MapVector<Value *, RRInfo> &Retains,
2593 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmana53a12c2011-12-12 19:42:25 +00002594
2595 // Use reverse-postorder traversals, because we magically know that loops
2596 // will be well behaved, i.e. they won't repeatedly call retain on a single
2597 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2598 // class here because we want the reverse-CFG postorder to consider each
2599 // function exit point, and we want to ignore selected cycle edges.
2600 SmallVector<BasicBlock *, 16> PostOrder;
2601 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmanc24c66f2012-04-24 22:53:18 +00002602 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2603 NoObjCARCExceptionsMDKind,
2604 BBStates);
Dan Gohmana53a12c2011-12-12 19:42:25 +00002605
2606 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCalld935e9c2011-06-15 23:37:01 +00002607 bool BottomUpNestingDetected = false;
Dan Gohmanc57b58c2011-08-18 21:27:42 +00002608 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohmana53a12c2011-12-12 19:42:25 +00002609 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2610 I != E; ++I)
2611 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCalld935e9c2011-06-15 23:37:01 +00002612
Dan Gohmana53a12c2011-12-12 19:42:25 +00002613 // Use reverse-postorder for top-down.
John McCalld935e9c2011-06-15 23:37:01 +00002614 bool TopDownNestingDetected = false;
Dan Gohmana53a12c2011-12-12 19:42:25 +00002615 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2616 PostOrder.rbegin(), E = PostOrder.rend();
2617 I != E; ++I)
2618 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCalld935e9c2011-06-15 23:37:01 +00002619
2620 return TopDownNestingDetected && BottomUpNestingDetected;
2621}
2622
Michael Gottesman97e3df02013-01-14 00:35:14 +00002623/// Move the calls in RetainsToMove and ReleasesToMove.
John McCalld935e9c2011-06-15 23:37:01 +00002624void ObjCARCOpt::MoveCalls(Value *Arg,
2625 RRInfo &RetainsToMove,
2626 RRInfo &ReleasesToMove,
2627 MapVector<Value *, RRInfo> &Retains,
2628 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman6320f522011-07-22 22:29:21 +00002629 SmallVectorImpl<Instruction *> &DeadInsts,
2630 Module *M) {
Chris Lattner229907c2011-07-18 04:54:35 +00002631 Type *ArgTy = Arg->getType();
Dan Gohman6320f522011-07-22 22:29:21 +00002632 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCalld935e9c2011-06-15 23:37:01 +00002633
2634 // Insert the new retain and release calls.
2635 for (SmallPtrSet<Instruction *, 2>::const_iterator
2636 PI = ReleasesToMove.ReverseInsertPts.begin(),
2637 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2638 Instruction *InsertPt = *PI;
2639 Value *MyArg = ArgTy == ParamTy ? Arg :
2640 new BitCastInst(Arg, ParamTy, "", InsertPt);
2641 CallInst *Call =
2642 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman6320f522011-07-22 22:29:21 +00002643 getRetainBlockCallee(M) : getRetainCallee(M),
John McCalld935e9c2011-06-15 23:37:01 +00002644 MyArg, "", InsertPt);
2645 Call->setDoesNotThrow();
Dan Gohman728db492012-01-13 00:39:07 +00002646 if (RetainsToMove.IsRetainBlock)
Dan Gohmana7107f92011-10-17 22:53:25 +00002647 Call->setMetadata(CopyOnEscapeMDKind,
2648 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman728db492012-01-13 00:39:07 +00002649 else
John McCalld935e9c2011-06-15 23:37:01 +00002650 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002651
2652 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
2653 << "\n"
2654 " At insertion point: " << *InsertPt
2655 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002656 }
2657 for (SmallPtrSet<Instruction *, 2>::const_iterator
2658 PI = RetainsToMove.ReverseInsertPts.begin(),
2659 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman5c70fad2012-03-23 17:47:54 +00002660 Instruction *InsertPt = *PI;
2661 Value *MyArg = ArgTy == ParamTy ? Arg :
2662 new BitCastInst(Arg, ParamTy, "", InsertPt);
2663 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2664 "", InsertPt);
2665 // Attach a clang.imprecise_release metadata tag, if appropriate.
2666 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2667 Call->setMetadata(ImpreciseReleaseMDKind, M);
2668 Call->setDoesNotThrow();
2669 if (ReleasesToMove.IsTailCallRelease)
2670 Call->setTailCall();
Michael Gottesmanc189a392013-01-09 19:23:24 +00002671
2672 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2673 << "\n"
2674 " At insertion point: " << *InsertPt
2675 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002676 }
2677
2678 // Delete the original retain and release calls.
2679 for (SmallPtrSet<Instruction *, 2>::const_iterator
2680 AI = RetainsToMove.Calls.begin(),
2681 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2682 Instruction *OrigRetain = *AI;
2683 Retains.blot(OrigRetain);
2684 DeadInsts.push_back(OrigRetain);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002685 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2686 "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002687 }
2688 for (SmallPtrSet<Instruction *, 2>::const_iterator
2689 AI = ReleasesToMove.Calls.begin(),
2690 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2691 Instruction *OrigRelease = *AI;
2692 Releases.erase(OrigRelease);
2693 DeadInsts.push_back(OrigRelease);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002694 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2695 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00002696 }
2697}
2698
Michael Gottesman9de6f962013-01-22 21:49:00 +00002699bool
2700ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2701 &BBStates,
2702 MapVector<Value *, RRInfo> &Retains,
2703 DenseMap<Value *, RRInfo> &Releases,
2704 Module *M,
2705 SmallVector<Instruction *, 4> &NewRetains,
2706 SmallVector<Instruction *, 4> &NewReleases,
2707 SmallVector<Instruction *, 8> &DeadInsts,
2708 RRInfo &RetainsToMove,
2709 RRInfo &ReleasesToMove,
2710 Value *Arg,
2711 bool KnownSafe,
2712 bool &AnyPairsCompletelyEliminated) {
2713 // If a pair happens in a region where it is known that the reference count
2714 // is already incremented, we can similarly ignore possible decrements.
2715 bool KnownSafeTD = true, KnownSafeBU = true;
2716
2717 // Connect the dots between the top-down-collected RetainsToMove and
2718 // bottom-up-collected ReleasesToMove to form sets of related calls.
2719 // This is an iterative process so that we connect multiple releases
2720 // to multiple retains if needed.
2721 unsigned OldDelta = 0;
2722 unsigned NewDelta = 0;
2723 unsigned OldCount = 0;
2724 unsigned NewCount = 0;
2725 bool FirstRelease = true;
2726 bool FirstRetain = true;
2727 for (;;) {
2728 for (SmallVectorImpl<Instruction *>::const_iterator
2729 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2730 Instruction *NewRetain = *NI;
2731 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2732 assert(It != Retains.end());
2733 const RRInfo &NewRetainRRI = It->second;
2734 KnownSafeTD &= NewRetainRRI.KnownSafe;
2735 for (SmallPtrSet<Instruction *, 2>::const_iterator
2736 LI = NewRetainRRI.Calls.begin(),
2737 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2738 Instruction *NewRetainRelease = *LI;
2739 DenseMap<Value *, RRInfo>::const_iterator Jt =
2740 Releases.find(NewRetainRelease);
2741 if (Jt == Releases.end())
2742 return false;
2743 const RRInfo &NewRetainReleaseRRI = Jt->second;
2744 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2745 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2746 OldDelta -=
2747 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2748
2749 // Merge the ReleaseMetadata and IsTailCallRelease values.
2750 if (FirstRelease) {
2751 ReleasesToMove.ReleaseMetadata =
2752 NewRetainReleaseRRI.ReleaseMetadata;
2753 ReleasesToMove.IsTailCallRelease =
2754 NewRetainReleaseRRI.IsTailCallRelease;
2755 FirstRelease = false;
2756 } else {
2757 if (ReleasesToMove.ReleaseMetadata !=
2758 NewRetainReleaseRRI.ReleaseMetadata)
2759 ReleasesToMove.ReleaseMetadata = 0;
2760 if (ReleasesToMove.IsTailCallRelease !=
2761 NewRetainReleaseRRI.IsTailCallRelease)
2762 ReleasesToMove.IsTailCallRelease = false;
2763 }
2764
2765 // Collect the optimal insertion points.
2766 if (!KnownSafe)
2767 for (SmallPtrSet<Instruction *, 2>::const_iterator
2768 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2769 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2770 RI != RE; ++RI) {
2771 Instruction *RIP = *RI;
2772 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2773 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2774 }
2775 NewReleases.push_back(NewRetainRelease);
2776 }
2777 }
2778 }
2779 NewRetains.clear();
2780 if (NewReleases.empty()) break;
2781
2782 // Back the other way.
2783 for (SmallVectorImpl<Instruction *>::const_iterator
2784 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2785 Instruction *NewRelease = *NI;
2786 DenseMap<Value *, RRInfo>::const_iterator It =
2787 Releases.find(NewRelease);
2788 assert(It != Releases.end());
2789 const RRInfo &NewReleaseRRI = It->second;
2790 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2791 for (SmallPtrSet<Instruction *, 2>::const_iterator
2792 LI = NewReleaseRRI.Calls.begin(),
2793 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2794 Instruction *NewReleaseRetain = *LI;
2795 MapVector<Value *, RRInfo>::const_iterator Jt =
2796 Retains.find(NewReleaseRetain);
2797 if (Jt == Retains.end())
2798 return false;
2799 const RRInfo &NewReleaseRetainRRI = Jt->second;
2800 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2801 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2802 unsigned PathCount =
2803 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2804 OldDelta += PathCount;
2805 OldCount += PathCount;
2806
2807 // Merge the IsRetainBlock values.
2808 if (FirstRetain) {
2809 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2810 FirstRetain = false;
2811 } else if (ReleasesToMove.IsRetainBlock !=
2812 NewReleaseRetainRRI.IsRetainBlock)
2813 // It's not possible to merge the sequences if one uses
2814 // objc_retain and the other uses objc_retainBlock.
2815 return false;
2816
2817 // Collect the optimal insertion points.
2818 if (!KnownSafe)
2819 for (SmallPtrSet<Instruction *, 2>::const_iterator
2820 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2821 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2822 RI != RE; ++RI) {
2823 Instruction *RIP = *RI;
2824 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2825 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2826 NewDelta += PathCount;
2827 NewCount += PathCount;
2828 }
2829 }
2830 NewRetains.push_back(NewReleaseRetain);
2831 }
2832 }
2833 }
2834 NewReleases.clear();
2835 if (NewRetains.empty()) break;
2836 }
2837
2838 // If the pointer is known incremented or nested, we can safely delete the
2839 // pair regardless of what's between them.
2840 if (KnownSafeTD || KnownSafeBU) {
2841 RetainsToMove.ReverseInsertPts.clear();
2842 ReleasesToMove.ReverseInsertPts.clear();
2843 NewCount = 0;
2844 } else {
2845 // Determine whether the new insertion points we computed preserve the
2846 // balance of retain and release calls through the program.
2847 // TODO: If the fully aggressive solution isn't valid, try to find a
2848 // less aggressive solution which is.
2849 if (NewDelta != 0)
2850 return false;
2851 }
2852
2853 // Determine whether the original call points are balanced in the retain and
2854 // release calls through the program. If not, conservatively don't touch
2855 // them.
2856 // TODO: It's theoretically possible to do code motion in this case, as
2857 // long as the existing imbalances are maintained.
2858 if (OldDelta != 0)
2859 return false;
2860
2861 Changed = true;
2862 assert(OldCount != 0 && "Unreachable code?");
2863 NumRRs += OldCount - NewCount;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002864 // Set to true if we completely removed any RR pairs.
Michael Gottesman8b5515f2013-01-22 21:53:43 +00002865 AnyPairsCompletelyEliminated = NewCount == 0;
Michael Gottesman9de6f962013-01-22 21:49:00 +00002866
2867 // We can move calls!
2868 return true;
2869}
2870
Michael Gottesman97e3df02013-01-14 00:35:14 +00002871/// Identify pairings between the retains and releases, and delete and/or move
2872/// them.
John McCalld935e9c2011-06-15 23:37:01 +00002873bool
2874ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2875 &BBStates,
2876 MapVector<Value *, RRInfo> &Retains,
Dan Gohman6320f522011-07-22 22:29:21 +00002877 DenseMap<Value *, RRInfo> &Releases,
2878 Module *M) {
John McCalld935e9c2011-06-15 23:37:01 +00002879 bool AnyPairsCompletelyEliminated = false;
2880 RRInfo RetainsToMove;
2881 RRInfo ReleasesToMove;
2882 SmallVector<Instruction *, 4> NewRetains;
2883 SmallVector<Instruction *, 4> NewReleases;
2884 SmallVector<Instruction *, 8> DeadInsts;
2885
Dan Gohman670f9372012-04-13 18:57:48 +00002886 // Visit each retain.
John McCalld935e9c2011-06-15 23:37:01 +00002887 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman2053a5d2011-09-29 22:25:23 +00002888 E = Retains.end(); I != E; ++I) {
2889 Value *V = I->first;
John McCalld935e9c2011-06-15 23:37:01 +00002890 if (!V) continue; // blotted
2891
2892 Instruction *Retain = cast<Instruction>(V);
Michael Gottesmanc189a392013-01-09 19:23:24 +00002893
2894 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
2895 << "\n");
2896
John McCalld935e9c2011-06-15 23:37:01 +00002897 Value *Arg = GetObjCArg(Retain);
2898
Dan Gohman728db492012-01-13 00:39:07 +00002899 // If the object being released is in static or stack storage, we know it's
John McCalld935e9c2011-06-15 23:37:01 +00002900 // not being managed by ObjC reference counting, so we can delete pairs
2901 // regardless of what possible decrements or uses lie between them.
Dan Gohman728db492012-01-13 00:39:07 +00002902 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman41375a32012-05-08 23:39:44 +00002903
Dan Gohman56e1cef2011-08-22 17:29:11 +00002904 // A constant pointer can't be pointing to an object on the heap. It may
2905 // be reference-counted, but it won't be deleted.
2906 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2907 if (const GlobalVariable *GV =
2908 dyn_cast<GlobalVariable>(
2909 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2910 if (GV->isConstant())
2911 KnownSafe = true;
2912
John McCalld935e9c2011-06-15 23:37:01 +00002913 // Connect the dots between the top-down-collected RetainsToMove and
2914 // bottom-up-collected ReleasesToMove to form sets of related calls.
John McCalld935e9c2011-06-15 23:37:01 +00002915 NewRetains.push_back(Retain);
Michael Gottesman9de6f962013-01-22 21:49:00 +00002916 bool PerformMoveCalls =
2917 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2918 NewReleases, DeadInsts, RetainsToMove,
2919 ReleasesToMove, Arg, KnownSafe,
2920 AnyPairsCompletelyEliminated);
John McCalld935e9c2011-06-15 23:37:01 +00002921
Michael Gottesman9de6f962013-01-22 21:49:00 +00002922 if (PerformMoveCalls) {
2923 // Ok, everything checks out and we're all set. Let's move/delete some
2924 // code!
2925 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2926 Retains, Releases, DeadInsts, M);
John McCalld935e9c2011-06-15 23:37:01 +00002927 }
2928
Michael Gottesman9de6f962013-01-22 21:49:00 +00002929 // Clean up state for next retain.
John McCalld935e9c2011-06-15 23:37:01 +00002930 NewReleases.clear();
2931 NewRetains.clear();
2932 RetainsToMove.clear();
2933 ReleasesToMove.clear();
2934 }
2935
2936 // Now that we're done moving everything, we can delete the newly dead
2937 // instructions, as we no longer need them as insert points.
2938 while (!DeadInsts.empty())
2939 EraseInstruction(DeadInsts.pop_back_val());
2940
2941 return AnyPairsCompletelyEliminated;
2942}
2943
Michael Gottesman97e3df02013-01-14 00:35:14 +00002944/// Weak pointer optimizations.
John McCalld935e9c2011-06-15 23:37:01 +00002945void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2946 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2947 // itself because it uses AliasAnalysis and we need to do provenance
2948 // queries instead.
2949 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2950 Instruction *Inst = &*I++;
Michael Gottesman3f146e22013-01-01 16:05:48 +00002951
Michael Gottesman9f848ae2013-01-04 21:29:57 +00002952 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
Michael Gottesman3f146e22013-01-01 16:05:48 +00002953 "\n");
2954
John McCalld935e9c2011-06-15 23:37:01 +00002955 InstructionClass Class = GetBasicInstructionClass(Inst);
2956 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2957 continue;
2958
2959 // Delete objc_loadWeak calls with no users.
2960 if (Class == IC_LoadWeak && Inst->use_empty()) {
2961 Inst->eraseFromParent();
2962 continue;
2963 }
2964
2965 // TODO: For now, just look for an earlier available version of this value
2966 // within the same block. Theoretically, we could do memdep-style non-local
2967 // analysis too, but that would want caching. A better approach would be to
2968 // use the technique that EarlyCSE uses.
2969 inst_iterator Current = llvm::prior(I);
2970 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2971 for (BasicBlock::iterator B = CurrentBB->begin(),
2972 J = Current.getInstructionIterator();
2973 J != B; --J) {
2974 Instruction *EarlierInst = &*llvm::prior(J);
2975 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2976 switch (EarlierClass) {
2977 case IC_LoadWeak:
2978 case IC_LoadWeakRetained: {
2979 // If this is loading from the same pointer, replace this load's value
2980 // with that one.
2981 CallInst *Call = cast<CallInst>(Inst);
2982 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2983 Value *Arg = Call->getArgOperand(0);
2984 Value *EarlierArg = EarlierCall->getArgOperand(0);
2985 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2986 case AliasAnalysis::MustAlias:
2987 Changed = true;
2988 // If the load has a builtin retain, insert a plain retain for it.
2989 if (Class == IC_LoadWeakRetained) {
2990 CallInst *CI =
2991 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2992 "", Call);
2993 CI->setTailCall();
2994 }
2995 // Zap the fully redundant load.
2996 Call->replaceAllUsesWith(EarlierCall);
2997 Call->eraseFromParent();
2998 goto clobbered;
2999 case AliasAnalysis::MayAlias:
3000 case AliasAnalysis::PartialAlias:
3001 goto clobbered;
3002 case AliasAnalysis::NoAlias:
3003 break;
3004 }
3005 break;
3006 }
3007 case IC_StoreWeak:
3008 case IC_InitWeak: {
3009 // If this is storing to the same pointer and has the same size etc.
3010 // replace this load's value with the stored value.
3011 CallInst *Call = cast<CallInst>(Inst);
3012 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3013 Value *Arg = Call->getArgOperand(0);
3014 Value *EarlierArg = EarlierCall->getArgOperand(0);
3015 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3016 case AliasAnalysis::MustAlias:
3017 Changed = true;
3018 // If the load has a builtin retain, insert a plain retain for it.
3019 if (Class == IC_LoadWeakRetained) {
3020 CallInst *CI =
3021 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3022 "", Call);
3023 CI->setTailCall();
3024 }
3025 // Zap the fully redundant load.
3026 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3027 Call->eraseFromParent();
3028 goto clobbered;
3029 case AliasAnalysis::MayAlias:
3030 case AliasAnalysis::PartialAlias:
3031 goto clobbered;
3032 case AliasAnalysis::NoAlias:
3033 break;
3034 }
3035 break;
3036 }
3037 case IC_MoveWeak:
3038 case IC_CopyWeak:
3039 // TOOD: Grab the copied value.
3040 goto clobbered;
3041 case IC_AutoreleasepoolPush:
3042 case IC_None:
3043 case IC_User:
3044 // Weak pointers are only modified through the weak entry points
3045 // (and arbitrary calls, which could call the weak entry points).
3046 break;
3047 default:
3048 // Anything else could modify the weak pointer.
3049 goto clobbered;
3050 }
3051 }
3052 clobbered:;
3053 }
3054
3055 // Then, for each destroyWeak with an alloca operand, check to see if
3056 // the alloca and all its users can be zapped.
3057 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3058 Instruction *Inst = &*I++;
3059 InstructionClass Class = GetBasicInstructionClass(Inst);
3060 if (Class != IC_DestroyWeak)
3061 continue;
3062
3063 CallInst *Call = cast<CallInst>(Inst);
3064 Value *Arg = Call->getArgOperand(0);
3065 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3066 for (Value::use_iterator UI = Alloca->use_begin(),
3067 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohmandae33492012-04-27 18:56:31 +00003068 const Instruction *UserInst = cast<Instruction>(*UI);
John McCalld935e9c2011-06-15 23:37:01 +00003069 switch (GetBasicInstructionClass(UserInst)) {
3070 case IC_InitWeak:
3071 case IC_StoreWeak:
3072 case IC_DestroyWeak:
3073 continue;
3074 default:
3075 goto done;
3076 }
3077 }
3078 Changed = true;
3079 for (Value::use_iterator UI = Alloca->use_begin(),
3080 UE = Alloca->use_end(); UI != UE; ) {
3081 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohman14862c32012-05-18 22:17:29 +00003082 switch (GetBasicInstructionClass(UserInst)) {
3083 case IC_InitWeak:
3084 case IC_StoreWeak:
3085 // These functions return their second argument.
3086 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3087 break;
3088 case IC_DestroyWeak:
3089 // No return value.
3090 break;
3091 default:
Dan Gohman9c97eea02012-05-21 17:41:28 +00003092 llvm_unreachable("alloca really is used!");
Dan Gohman14862c32012-05-18 22:17:29 +00003093 }
John McCalld935e9c2011-06-15 23:37:01 +00003094 UserInst->eraseFromParent();
3095 }
3096 Alloca->eraseFromParent();
3097 done:;
3098 }
3099 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003100
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003101 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003102
John McCalld935e9c2011-06-15 23:37:01 +00003103}
3104
Michael Gottesman97e3df02013-01-14 00:35:14 +00003105/// Identify program paths which execute sequences of retains and releases which
3106/// can be eliminated.
John McCalld935e9c2011-06-15 23:37:01 +00003107bool ObjCARCOpt::OptimizeSequences(Function &F) {
3108 /// Releases, Retains - These are used to store the results of the main flow
3109 /// analysis. These use Value* as the key instead of Instruction* so that the
3110 /// map stays valid when we get around to rewriting code and calls get
3111 /// replaced by arguments.
3112 DenseMap<Value *, RRInfo> Releases;
3113 MapVector<Value *, RRInfo> Retains;
3114
Michael Gottesman97e3df02013-01-14 00:35:14 +00003115 /// This is used during the traversal of the function to track the
John McCalld935e9c2011-06-15 23:37:01 +00003116 /// states for each identified object at each block.
3117 DenseMap<const BasicBlock *, BBState> BBStates;
3118
3119 // Analyze the CFG of the function, and all instructions.
3120 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3121
3122 // Transform.
Dan Gohman6320f522011-07-22 22:29:21 +00003123 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3124 NestingDetected;
John McCalld935e9c2011-06-15 23:37:01 +00003125}
3126
Michael Gottesman97e3df02013-01-14 00:35:14 +00003127/// Look for this pattern:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003128/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003129/// %call = call i8* @something(...)
3130/// %2 = call i8* @objc_retain(i8* %call)
3131/// %3 = call i8* @objc_autorelease(i8* %2)
3132/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003133/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003134/// And delete the retain and autorelease.
3135///
3136/// Otherwise if it's just this:
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003137/// \code
John McCalld935e9c2011-06-15 23:37:01 +00003138/// %3 = call i8* @objc_autorelease(i8* %2)
3139/// ret i8* %3
Dmitri Gribenko5485acd2012-09-14 14:57:36 +00003140/// \endcode
John McCalld935e9c2011-06-15 23:37:01 +00003141/// convert the autorelease to autoreleaseRV.
3142void ObjCARCOpt::OptimizeReturns(Function &F) {
3143 if (!F.getReturnType()->isPointerTy())
3144 return;
3145
3146 SmallPtrSet<Instruction *, 4> DependingInstructions;
3147 SmallPtrSet<const BasicBlock *, 4> Visited;
3148 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3149 BasicBlock *BB = FI;
3150 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman3f146e22013-01-01 16:05:48 +00003151
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003152 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003153
John McCalld935e9c2011-06-15 23:37:01 +00003154 if (!Ret) continue;
3155
3156 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3157 FindDependencies(NeedsPositiveRetainCount, Arg,
3158 BB, Ret, DependingInstructions, Visited, PA);
3159 if (DependingInstructions.size() != 1)
3160 goto next_block;
3161
3162 {
3163 CallInst *Autorelease =
3164 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3165 if (!Autorelease)
3166 goto next_block;
Dan Gohman41375a32012-05-08 23:39:44 +00003167 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCalld935e9c2011-06-15 23:37:01 +00003168 if (!IsAutorelease(AutoreleaseClass))
3169 goto next_block;
3170 if (GetObjCArg(Autorelease) != Arg)
3171 goto next_block;
3172
3173 DependingInstructions.clear();
3174 Visited.clear();
3175
3176 // Check that there is nothing that can affect the reference
3177 // count between the autorelease and the retain.
3178 FindDependencies(CanChangeRetainCount, Arg,
3179 BB, Autorelease, DependingInstructions, Visited, PA);
3180 if (DependingInstructions.size() != 1)
3181 goto next_block;
3182
3183 {
3184 CallInst *Retain =
3185 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3186
3187 // Check that we found a retain with the same argument.
3188 if (!Retain ||
3189 !IsRetain(GetBasicInstructionClass(Retain)) ||
3190 GetObjCArg(Retain) != Arg)
3191 goto next_block;
3192
3193 DependingInstructions.clear();
3194 Visited.clear();
3195
3196 // Convert the autorelease to an autoreleaseRV, since it's
3197 // returning the value.
3198 if (AutoreleaseClass == IC_Autorelease) {
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003199 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3200 "=> autoreleaseRV since it's returning a value.\n"
3201 " In: " << *Autorelease
3202 << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003203 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
Michael Gottesmana6cb0182013-01-10 02:03:50 +00003204 DEBUG(dbgs() << " Out: " << *Autorelease
3205 << "\n");
Michael Gottesmanc9656fa2013-01-12 01:25:15 +00003206 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
John McCalld935e9c2011-06-15 23:37:01 +00003207 AutoreleaseClass = IC_AutoreleaseRV;
3208 }
3209
3210 // Check that there is nothing that can affect the reference
3211 // count between the retain and the call.
Dan Gohman4ac148d2011-09-29 22:27:34 +00003212 // Note that Retain need not be in BB.
3213 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCalld935e9c2011-06-15 23:37:01 +00003214 DependingInstructions, Visited, PA);
3215 if (DependingInstructions.size() != 1)
3216 goto next_block;
3217
3218 {
3219 CallInst *Call =
3220 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3221
3222 // Check that the pointer is the return value of the call.
3223 if (!Call || Arg != Call)
3224 goto next_block;
3225
3226 // Check that the call is a regular call.
3227 InstructionClass Class = GetBasicInstructionClass(Call);
3228 if (Class != IC_CallOrUser && Class != IC_Call)
3229 goto next_block;
3230
3231 // If so, we can zap the retain and autorelease.
3232 Changed = true;
3233 ++NumRets;
Michael Gottesmand61a3b22013-01-07 00:04:56 +00003234 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3235 << "\n Erasing: "
3236 << *Autorelease << "\n");
John McCalld935e9c2011-06-15 23:37:01 +00003237 EraseInstruction(Retain);
3238 EraseInstruction(Autorelease);
3239 }
3240 }
3241 }
3242
3243 next_block:
3244 DependingInstructions.clear();
3245 Visited.clear();
3246 }
Michael Gottesman10426b52013-01-07 21:26:07 +00003247
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003248 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003249
John McCalld935e9c2011-06-15 23:37:01 +00003250}
3251
3252bool ObjCARCOpt::doInitialization(Module &M) {
3253 if (!EnableARCOpts)
3254 return false;
3255
Dan Gohman670f9372012-04-13 18:57:48 +00003256 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003257 Run = ModuleHasARC(M);
3258 if (!Run)
3259 return false;
3260
John McCalld935e9c2011-06-15 23:37:01 +00003261 // Identify the imprecise release metadata kind.
3262 ImpreciseReleaseMDKind =
3263 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana7107f92011-10-17 22:53:25 +00003264 CopyOnEscapeMDKind =
3265 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohman0155f302012-02-17 18:59:53 +00003266 NoObjCARCExceptionsMDKind =
3267 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCalld935e9c2011-06-15 23:37:01 +00003268
John McCalld935e9c2011-06-15 23:37:01 +00003269 // Intuitively, objc_retain and others are nocapture, however in practice
3270 // they are not, because they return their argument value. And objc_release
Dan Gohmandae33492012-04-27 18:56:31 +00003271 // calls finalizers which can have arbitrary side effects.
John McCalld935e9c2011-06-15 23:37:01 +00003272
3273 // These are initialized lazily.
3274 RetainRVCallee = 0;
3275 AutoreleaseRVCallee = 0;
3276 ReleaseCallee = 0;
3277 RetainCallee = 0;
Dan Gohman6320f522011-07-22 22:29:21 +00003278 RetainBlockCallee = 0;
John McCalld935e9c2011-06-15 23:37:01 +00003279 AutoreleaseCallee = 0;
3280
3281 return false;
3282}
3283
3284bool ObjCARCOpt::runOnFunction(Function &F) {
3285 if (!EnableARCOpts)
3286 return false;
3287
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003288 // If nothing in the Module uses ARC, don't do anything.
3289 if (!Run)
3290 return false;
3291
John McCalld935e9c2011-06-15 23:37:01 +00003292 Changed = false;
3293
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003294 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3295
John McCalld935e9c2011-06-15 23:37:01 +00003296 PA.setAA(&getAnalysis<AliasAnalysis>());
3297
3298 // This pass performs several distinct transformations. As a compile-time aid
3299 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3300 // library functions aren't declared.
3301
3302 // Preliminary optimizations. This also computs UsedInThisFunction.
3303 OptimizeIndividualCalls(F);
3304
3305 // Optimizations for weak pointers.
3306 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3307 (1 << IC_LoadWeakRetained) |
3308 (1 << IC_StoreWeak) |
3309 (1 << IC_InitWeak) |
3310 (1 << IC_CopyWeak) |
3311 (1 << IC_MoveWeak) |
3312 (1 << IC_DestroyWeak)))
3313 OptimizeWeakCalls(F);
3314
3315 // Optimizations for retain+release pairs.
3316 if (UsedInThisFunction & ((1 << IC_Retain) |
3317 (1 << IC_RetainRV) |
3318 (1 << IC_RetainBlock)))
3319 if (UsedInThisFunction & (1 << IC_Release))
3320 // Run OptimizeSequences until it either stops making changes or
3321 // no retain+release pair nesting is detected.
3322 while (OptimizeSequences(F)) {}
3323
3324 // Optimizations if objc_autorelease is used.
Dan Gohman41375a32012-05-08 23:39:44 +00003325 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3326 (1 << IC_AutoreleaseRV)))
John McCalld935e9c2011-06-15 23:37:01 +00003327 OptimizeReturns(F);
3328
Michael Gottesmanb24bdef2013-01-12 02:57:16 +00003329 DEBUG(dbgs() << "\n");
3330
John McCalld935e9c2011-06-15 23:37:01 +00003331 return Changed;
3332}
3333
3334void ObjCARCOpt::releaseMemory() {
3335 PA.clear();
3336}
3337
Michael Gottesman97e3df02013-01-14 00:35:14 +00003338/// @}
3339///
3340/// \defgroup ARCContract ARC Contraction.
3341/// @{
John McCalld935e9c2011-06-15 23:37:01 +00003342
3343// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3344// dominated by single calls.
3345
John McCalld935e9c2011-06-15 23:37:01 +00003346#include "llvm/Analysis/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +00003347#include "llvm/IR/InlineAsm.h"
3348#include "llvm/IR/Operator.h"
John McCalld935e9c2011-06-15 23:37:01 +00003349
3350STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3351
3352namespace {
Michael Gottesman97e3df02013-01-14 00:35:14 +00003353 /// \brief Late ARC optimizations
3354 ///
3355 /// These change the IR in a way that makes it difficult to be analyzed by
3356 /// ObjCARCOpt, so it's run late.
John McCalld935e9c2011-06-15 23:37:01 +00003357 class ObjCARCContract : public FunctionPass {
3358 bool Changed;
3359 AliasAnalysis *AA;
3360 DominatorTree *DT;
3361 ProvenanceAnalysis PA;
3362
Michael Gottesman97e3df02013-01-14 00:35:14 +00003363 /// A flag indicating whether this optimization pass should run.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003364 bool Run;
3365
Michael Gottesman97e3df02013-01-14 00:35:14 +00003366 /// Declarations for ObjC runtime functions, for use in creating calls to
3367 /// them. These are initialized lazily to avoid cluttering up the Module
3368 /// with unused declarations.
John McCalld935e9c2011-06-15 23:37:01 +00003369
Michael Gottesman97e3df02013-01-14 00:35:14 +00003370 /// Declaration for objc_storeStrong().
3371 Constant *StoreStrongCallee;
3372 /// Declaration for objc_retainAutorelease().
3373 Constant *RetainAutoreleaseCallee;
3374 /// Declaration for objc_retainAutoreleaseReturnValue().
3375 Constant *RetainAutoreleaseRVCallee;
3376
3377 /// The inline asm string to insert between calls and RetainRV calls to make
3378 /// the optimization work on targets which need it.
John McCalld935e9c2011-06-15 23:37:01 +00003379 const MDString *RetainRVMarker;
3380
Michael Gottesman97e3df02013-01-14 00:35:14 +00003381 /// The set of inserted objc_storeStrong calls. If at the end of walking the
3382 /// function we have found no alloca instructions, these calls can be marked
3383 /// "tail".
Dan Gohman41375a32012-05-08 23:39:44 +00003384 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman8ee108b2012-01-19 19:14:36 +00003385
John McCalld935e9c2011-06-15 23:37:01 +00003386 Constant *getStoreStrongCallee(Module *M);
3387 Constant *getRetainAutoreleaseCallee(Module *M);
3388 Constant *getRetainAutoreleaseRVCallee(Module *M);
3389
3390 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3391 InstructionClass Class,
3392 SmallPtrSet<Instruction *, 4>
3393 &DependingInstructions,
3394 SmallPtrSet<const BasicBlock *, 4>
3395 &Visited);
3396
3397 void ContractRelease(Instruction *Release,
3398 inst_iterator &Iter);
3399
3400 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3401 virtual bool doInitialization(Module &M);
3402 virtual bool runOnFunction(Function &F);
3403
3404 public:
3405 static char ID;
3406 ObjCARCContract() : FunctionPass(ID) {
3407 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3408 }
3409 };
3410}
3411
3412char ObjCARCContract::ID = 0;
3413INITIALIZE_PASS_BEGIN(ObjCARCContract,
3414 "objc-arc-contract", "ObjC ARC contraction", false, false)
3415INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3416INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3417INITIALIZE_PASS_END(ObjCARCContract,
3418 "objc-arc-contract", "ObjC ARC contraction", false, false)
3419
3420Pass *llvm::createObjCARCContractPass() {
3421 return new ObjCARCContract();
3422}
3423
3424void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3425 AU.addRequired<AliasAnalysis>();
3426 AU.addRequired<DominatorTree>();
3427 AU.setPreservesCFG();
3428}
3429
3430Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3431 if (!StoreStrongCallee) {
3432 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00003433 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3434 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman41375a32012-05-08 23:39:44 +00003435 Type *Params[] = { I8XX, I8X };
John McCalld935e9c2011-06-15 23:37:01 +00003436
Bill Wendling09175b32013-01-22 21:15:51 +00003437 AttributeSet Attr = AttributeSet()
3438 .addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3439 Attribute::NoUnwind)
3440 .addAttribute(M->getContext(), 1, Attribute::NoCapture);
John McCalld935e9c2011-06-15 23:37:01 +00003441
3442 StoreStrongCallee =
3443 M->getOrInsertFunction(
3444 "objc_storeStrong",
3445 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling09175b32013-01-22 21:15:51 +00003446 Attr);
John McCalld935e9c2011-06-15 23:37:01 +00003447 }
3448 return StoreStrongCallee;
3449}
3450
3451Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3452 if (!RetainAutoreleaseCallee) {
3453 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00003454 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00003455 Type *Params[] = { I8X };
3456 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003457 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00003458 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3459 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00003460 RetainAutoreleaseCallee =
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003461 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00003462 }
3463 return RetainAutoreleaseCallee;
3464}
3465
3466Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3467 if (!RetainAutoreleaseRVCallee) {
3468 LLVMContext &C = M->getContext();
Jay Foadb804a2b2011-07-12 14:06:48 +00003469 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman41375a32012-05-08 23:39:44 +00003470 Type *Params[] = { I8X };
3471 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003472 AttributeSet Attribute =
Bill Wendling09175b32013-01-22 21:15:51 +00003473 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3474 Attribute::NoUnwind);
John McCalld935e9c2011-06-15 23:37:01 +00003475 RetainAutoreleaseRVCallee =
3476 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00003477 Attribute);
John McCalld935e9c2011-06-15 23:37:01 +00003478 }
3479 return RetainAutoreleaseRVCallee;
3480}
3481
Michael Gottesman97e3df02013-01-14 00:35:14 +00003482/// Merge an autorelease with a retain into a fused call.
John McCalld935e9c2011-06-15 23:37:01 +00003483bool
3484ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3485 InstructionClass Class,
3486 SmallPtrSet<Instruction *, 4>
3487 &DependingInstructions,
3488 SmallPtrSet<const BasicBlock *, 4>
3489 &Visited) {
3490 const Value *Arg = GetObjCArg(Autorelease);
3491
3492 // Check that there are no instructions between the retain and the autorelease
3493 // (such as an autorelease_pop) which may change the count.
3494 CallInst *Retain = 0;
3495 if (Class == IC_AutoreleaseRV)
3496 FindDependencies(RetainAutoreleaseRVDep, Arg,
3497 Autorelease->getParent(), Autorelease,
3498 DependingInstructions, Visited, PA);
3499 else
3500 FindDependencies(RetainAutoreleaseDep, Arg,
3501 Autorelease->getParent(), Autorelease,
3502 DependingInstructions, Visited, PA);
3503
3504 Visited.clear();
3505 if (DependingInstructions.size() != 1) {
3506 DependingInstructions.clear();
3507 return false;
3508 }
3509
3510 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3511 DependingInstructions.clear();
3512
3513 if (!Retain ||
3514 GetBasicInstructionClass(Retain) != IC_Retain ||
3515 GetObjCArg(Retain) != Arg)
3516 return false;
3517
3518 Changed = true;
3519 ++NumPeeps;
Michael Gottesman10426b52013-01-07 21:26:07 +00003520
Michael Gottesmanadd08472013-01-07 00:31:26 +00003521 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
3522 "retain/autorelease. Erasing: " << *Autorelease << "\n"
3523 " Old Retain: "
3524 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003525
John McCalld935e9c2011-06-15 23:37:01 +00003526 if (Class == IC_AutoreleaseRV)
3527 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3528 else
3529 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
Michael Gottesman10426b52013-01-07 21:26:07 +00003530
Michael Gottesmanadd08472013-01-07 00:31:26 +00003531 DEBUG(dbgs() << " New Retain: "
3532 << *Retain << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003533
John McCalld935e9c2011-06-15 23:37:01 +00003534 EraseInstruction(Autorelease);
3535 return true;
3536}
3537
Michael Gottesman97e3df02013-01-14 00:35:14 +00003538/// Attempt to merge an objc_release with a store, load, and objc_retain to form
3539/// an objc_storeStrong. This can be a little tricky because the instructions
3540/// don't always appear in order, and there may be unrelated intervening
3541/// instructions.
John McCalld935e9c2011-06-15 23:37:01 +00003542void ObjCARCContract::ContractRelease(Instruction *Release,
3543 inst_iterator &Iter) {
3544 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman7c5dc122011-09-12 20:23:13 +00003545 if (!Load || !Load->isSimple()) return;
John McCalld935e9c2011-06-15 23:37:01 +00003546
3547 // For now, require everything to be in one basic block.
3548 BasicBlock *BB = Release->getParent();
3549 if (Load->getParent() != BB) return;
3550
Dan Gohman61708d32012-05-08 23:34:08 +00003551 // Walk down to find the store and the release, which may be in either order.
Dan Gohmanf8b19d02012-05-09 23:08:33 +00003552 BasicBlock::iterator I = Load, End = BB->end();
John McCalld935e9c2011-06-15 23:37:01 +00003553 ++I;
3554 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman61708d32012-05-08 23:34:08 +00003555 StoreInst *Store = 0;
3556 bool SawRelease = false;
3557 for (; !Store || !SawRelease; ++I) {
Dan Gohmanf8b19d02012-05-09 23:08:33 +00003558 if (I == End)
3559 return;
3560
Dan Gohman61708d32012-05-08 23:34:08 +00003561 Instruction *Inst = I;
3562 if (Inst == Release) {
3563 SawRelease = true;
3564 continue;
3565 }
3566
3567 InstructionClass Class = GetBasicInstructionClass(Inst);
3568
3569 // Unrelated retains are harmless.
3570 if (IsRetain(Class))
3571 continue;
3572
3573 if (Store) {
3574 // The store is the point where we're going to put the objc_storeStrong,
3575 // so make sure there are no uses after it.
3576 if (CanUse(Inst, Load, PA, Class))
3577 return;
3578 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3579 // We are moving the load down to the store, so check for anything
3580 // else which writes to the memory between the load and the store.
3581 Store = dyn_cast<StoreInst>(Inst);
3582 if (!Store || !Store->isSimple()) return;
3583 if (Store->getPointerOperand() != Loc.Ptr) return;
3584 }
3585 }
John McCalld935e9c2011-06-15 23:37:01 +00003586
3587 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3588
3589 // Walk up to find the retain.
3590 I = Store;
3591 BasicBlock::iterator Begin = BB->begin();
3592 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3593 --I;
3594 Instruction *Retain = I;
3595 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3596 if (GetObjCArg(Retain) != New) return;
3597
3598 Changed = true;
3599 ++NumStoreStrongs;
3600
3601 LLVMContext &C = Release->getContext();
Chris Lattner229907c2011-07-18 04:54:35 +00003602 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3603 Type *I8XX = PointerType::getUnqual(I8X);
John McCalld935e9c2011-06-15 23:37:01 +00003604
3605 Value *Args[] = { Load->getPointerOperand(), New };
3606 if (Args[0]->getType() != I8XX)
3607 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3608 if (Args[1]->getType() != I8X)
3609 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3610 CallInst *StoreStrong =
3611 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foad5bd375a2011-07-15 08:37:34 +00003612 Args, "", Store);
John McCalld935e9c2011-06-15 23:37:01 +00003613 StoreStrong->setDoesNotThrow();
3614 StoreStrong->setDebugLoc(Store->getDebugLoc());
3615
Dan Gohman8ee108b2012-01-19 19:14:36 +00003616 // We can't set the tail flag yet, because we haven't yet determined
3617 // whether there are any escaping allocas. Remember this call, so that
3618 // we can set the tail flag once we know it's safe.
3619 StoreStrongCalls.insert(StoreStrong);
3620
John McCalld935e9c2011-06-15 23:37:01 +00003621 if (&*Iter == Store) ++Iter;
3622 Store->eraseFromParent();
3623 Release->eraseFromParent();
3624 EraseInstruction(Retain);
3625 if (Load->use_empty())
3626 Load->eraseFromParent();
3627}
3628
3629bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohman670f9372012-04-13 18:57:48 +00003630 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003631 Run = ModuleHasARC(M);
3632 if (!Run)
3633 return false;
3634
John McCalld935e9c2011-06-15 23:37:01 +00003635 // These are initialized lazily.
3636 StoreStrongCallee = 0;
3637 RetainAutoreleaseCallee = 0;
3638 RetainAutoreleaseRVCallee = 0;
3639
3640 // Initialize RetainRVMarker.
3641 RetainRVMarker = 0;
3642 if (NamedMDNode *NMD =
3643 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3644 if (NMD->getNumOperands() == 1) {
3645 const MDNode *N = NMD->getOperand(0);
3646 if (N->getNumOperands() == 1)
3647 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3648 RetainRVMarker = S;
3649 }
3650
3651 return false;
3652}
3653
3654bool ObjCARCContract::runOnFunction(Function &F) {
3655 if (!EnableARCOpts)
3656 return false;
3657
Dan Gohmanceaac7c2011-06-20 23:20:43 +00003658 // If nothing in the Module uses ARC, don't do anything.
3659 if (!Run)
3660 return false;
3661
John McCalld935e9c2011-06-15 23:37:01 +00003662 Changed = false;
3663 AA = &getAnalysis<AliasAnalysis>();
3664 DT = &getAnalysis<DominatorTree>();
3665
3666 PA.setAA(&getAnalysis<AliasAnalysis>());
3667
Dan Gohman8ee108b2012-01-19 19:14:36 +00003668 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3669 // keyword. Be conservative if the function has variadic arguments.
3670 // It seems that functions which "return twice" are also unsafe for the
3671 // "tail" argument, because they are setjmp, which could need to
3672 // return to an earlier stack state.
Dan Gohman41375a32012-05-08 23:39:44 +00003673 bool TailOkForStoreStrongs = !F.isVarArg() &&
3674 !F.callsFunctionThatReturnsTwice();
Dan Gohman8ee108b2012-01-19 19:14:36 +00003675
John McCalld935e9c2011-06-15 23:37:01 +00003676 // For ObjC library calls which return their argument, replace uses of the
3677 // argument with uses of the call return value, if it dominates the use. This
3678 // reduces register pressure.
3679 SmallPtrSet<Instruction *, 4> DependingInstructions;
3680 SmallPtrSet<const BasicBlock *, 4> Visited;
3681 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3682 Instruction *Inst = &*I++;
Michael Gottesman10426b52013-01-07 21:26:07 +00003683
Michael Gottesman3f146e22013-01-01 16:05:48 +00003684 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003685
John McCalld935e9c2011-06-15 23:37:01 +00003686 // Only these library routines return their argument. In particular,
3687 // objc_retainBlock does not necessarily return its argument.
3688 InstructionClass Class = GetBasicInstructionClass(Inst);
3689 switch (Class) {
3690 case IC_Retain:
3691 case IC_FusedRetainAutorelease:
3692 case IC_FusedRetainAutoreleaseRV:
3693 break;
3694 case IC_Autorelease:
3695 case IC_AutoreleaseRV:
3696 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3697 continue;
3698 break;
3699 case IC_RetainRV: {
3700 // If we're compiling for a target which needs a special inline-asm
3701 // marker to do the retainAutoreleasedReturnValue optimization,
3702 // insert it now.
3703 if (!RetainRVMarker)
3704 break;
3705 BasicBlock::iterator BBI = Inst;
Dan Gohman5f725cd2012-06-25 19:47:37 +00003706 BasicBlock *InstParent = Inst->getParent();
3707
3708 // Step up to see if the call immediately precedes the RetainRV call.
3709 // If it's an invoke, we have to cross a block boundary. And we have
3710 // to carefully dodge no-op instructions.
3711 do {
3712 if (&*BBI == InstParent->begin()) {
3713 BasicBlock *Pred = InstParent->getSinglePredecessor();
3714 if (!Pred)
3715 goto decline_rv_optimization;
3716 BBI = Pred->getTerminator();
3717 break;
3718 }
3719 --BBI;
3720 } while (isNoopInstruction(BBI));
3721
John McCalld935e9c2011-06-15 23:37:01 +00003722 if (&*BBI == GetObjCArg(Inst)) {
Michael Gottesman00d1f962013-01-03 07:32:41 +00003723 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
Michael Gottesman9f848ae2013-01-04 21:29:57 +00003724 "retainAutoreleasedReturnValue optimization.\n");
Dan Gohman670f9372012-04-13 18:57:48 +00003725 Changed = true;
John McCalld935e9c2011-06-15 23:37:01 +00003726 InlineAsm *IA =
3727 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3728 /*isVarArg=*/false),
3729 RetainRVMarker->getString(),
3730 /*Constraints=*/"", /*hasSideEffects=*/true);
3731 CallInst::Create(IA, "", Inst);
3732 }
Dan Gohman5f725cd2012-06-25 19:47:37 +00003733 decline_rv_optimization:
John McCalld935e9c2011-06-15 23:37:01 +00003734 break;
3735 }
3736 case IC_InitWeak: {
3737 // objc_initWeak(p, null) => *p = null
3738 CallInst *CI = cast<CallInst>(Inst);
3739 if (isNullOrUndef(CI->getArgOperand(1))) {
3740 Value *Null =
3741 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3742 Changed = true;
3743 new StoreInst(Null, CI->getArgOperand(0), CI);
Michael Gottesman10426b52013-01-07 21:26:07 +00003744
Michael Gottesman416dc002013-01-03 07:32:53 +00003745 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
3746 << " New = " << *Null << "\n");
Michael Gottesman10426b52013-01-07 21:26:07 +00003747
John McCalld935e9c2011-06-15 23:37:01 +00003748 CI->replaceAllUsesWith(Null);
3749 CI->eraseFromParent();
3750 }
3751 continue;
3752 }
3753 case IC_Release:
3754 ContractRelease(Inst, I);
3755 continue;
Dan Gohman8ee108b2012-01-19 19:14:36 +00003756 case IC_User:
3757 // Be conservative if the function has any alloca instructions.
3758 // Technically we only care about escaping alloca instructions,
3759 // but this is sufficient to handle some interesting cases.
3760 if (isa<AllocaInst>(Inst))
3761 TailOkForStoreStrongs = false;
3762 continue;
John McCalld935e9c2011-06-15 23:37:01 +00003763 default:
3764 continue;
3765 }
3766
Michael Gottesman50ae5b22013-01-03 08:09:27 +00003767 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
Michael Gottesman3f146e22013-01-01 16:05:48 +00003768
John McCalld935e9c2011-06-15 23:37:01 +00003769 // Don't use GetObjCArg because we don't want to look through bitcasts
3770 // and such; to do the replacement, the argument must have type i8*.
3771 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3772 for (;;) {
3773 // If we're compiling bugpointed code, don't get in trouble.
3774 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3775 break;
3776 // Look through the uses of the pointer.
3777 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3778 UI != UE; ) {
3779 Use &U = UI.getUse();
3780 unsigned OperandNo = UI.getOperandNo();
3781 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohman670f9372012-04-13 18:57:48 +00003782
3783 // If the call's return value dominates a use of the call's argument
3784 // value, rewrite the use to use the return value. We check for
3785 // reachability here because an unreachable call is considered to
3786 // trivially dominate itself, which would lead us to rewriting its
3787 // argument in terms of its return value, which would lead to
3788 // infinite loops in GetObjCArg.
Dan Gohman41375a32012-05-08 23:39:44 +00003789 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00003790 Changed = true;
3791 Instruction *Replacement = Inst;
3792 Type *UseTy = U.get()->getType();
Dan Gohmande8d2c42012-04-13 01:08:28 +00003793 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindolaf5892782012-03-15 15:52:59 +00003794 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman41375a32012-05-08 23:39:44 +00003795 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
3796 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindolaf5892782012-03-15 15:52:59 +00003797 if (Replacement->getType() != UseTy)
3798 Replacement = new BitCastInst(Replacement, UseTy, "",
3799 &BB->back());
Dan Gohman670f9372012-04-13 18:57:48 +00003800 // While we're here, rewrite all edges for this PHI, rather
3801 // than just one use at a time, to minimize the number of
3802 // bitcasts we emit.
Dan Gohmandae33492012-04-27 18:56:31 +00003803 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindolaf5892782012-03-15 15:52:59 +00003804 if (PHI->getIncomingBlock(i) == BB) {
3805 // Keep the UI iterator valid.
3806 if (&PHI->getOperandUse(
3807 PHINode::getOperandNumForIncomingValue(i)) ==
3808 &UI.getUse())
3809 ++UI;
3810 PHI->setIncomingValue(i, Replacement);
3811 }
3812 } else {
3813 if (Replacement->getType() != UseTy)
Dan Gohmande8d2c42012-04-13 01:08:28 +00003814 Replacement = new BitCastInst(Replacement, UseTy, "",
3815 cast<Instruction>(U.getUser()));
Rafael Espindolaf5892782012-03-15 15:52:59 +00003816 U.set(Replacement);
John McCalld935e9c2011-06-15 23:37:01 +00003817 }
Rafael Espindolaf5892782012-03-15 15:52:59 +00003818 }
John McCalld935e9c2011-06-15 23:37:01 +00003819 }
3820
Dan Gohmandae33492012-04-27 18:56:31 +00003821 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCalld935e9c2011-06-15 23:37:01 +00003822 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3823 Arg = BI->getOperand(0);
3824 else if (isa<GEPOperator>(Arg) &&
3825 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3826 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3827 else if (isa<GlobalAlias>(Arg) &&
3828 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3829 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3830 else
3831 break;
3832 }
3833 }
3834
Dan Gohman8ee108b2012-01-19 19:14:36 +00003835 // If this function has no escaping allocas or suspicious vararg usage,
3836 // objc_storeStrong calls can be marked with the "tail" keyword.
3837 if (TailOkForStoreStrongs)
Dan Gohman41375a32012-05-08 23:39:44 +00003838 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman8ee108b2012-01-19 19:14:36 +00003839 E = StoreStrongCalls.end(); I != E; ++I)
3840 (*I)->setTailCall();
3841 StoreStrongCalls.clear();
3842
John McCalld935e9c2011-06-15 23:37:01 +00003843 return Changed;
3844}
Michael Gottesman97e3df02013-01-14 00:35:14 +00003845
3846/// @}
3847///