blob: fea03b5f5b569316fc48238c1587c79ce6b0de16 [file] [log] [blame]
John McCall9fbd3182011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines ObjC ARC optimizations. ARC stands for
11// Automatic Reference Counting and is a system for managing reference counts
12// for objects in Objective C.
13//
14// The optimizations performed include elimination of redundant, partially
15// redundant, and inconsequential reference count operations, elimination of
16// redundant weak pointer operations, pattern-matching and replacement of
17// low-level operations into higher-level operations, and numerous minor
18// simplifications.
19//
20// This file also defines a simple ARC-aware AliasAnalysis.
21//
22// WARNING: This file knows about certain library functions. It recognizes them
23// by name, and hardwires knowedge 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//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "objc-arc"
32#include "llvm/Function.h"
33#include "llvm/Intrinsics.h"
34#include "llvm/GlobalVariable.h"
35#include "llvm/DerivedTypes.h"
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +000036#include "llvm/Module.h"
John McCall9fbd3182011-06-15 23:37:01 +000037#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/Transforms/Utils/Local.h"
39#include "llvm/Support/CallSite.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/STLExtras.h"
44using namespace llvm;
45
46// A handy option to enable/disable all optimizations in this file.
47static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
48
49//===----------------------------------------------------------------------===//
50// Misc. Utilities
51//===----------------------------------------------------------------------===//
52
53namespace {
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
56 /// blot operation.
57 template<class KeyT, class ValueT>
58 class MapVector {
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
61 MapTy Map;
62
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
65 VectorTy Vector;
66
67 public:
68 typedef typename VectorTy::iterator iterator;
69 typedef typename VectorTy::const_iterator const_iterator;
70 iterator begin() { return Vector.begin(); }
71 iterator end() { return Vector.end(); }
72 const_iterator begin() const { return Vector.begin(); }
73 const_iterator end() const { return Vector.end(); }
74
75#ifdef XDEBUG
76 ~MapVector() {
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
79 I != E; ++I) {
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
82 }
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
85 assert(!I->first ||
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
88 }
89#endif
90
91 ValueT &operator[](KeyT Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
94 if (Pair.second) {
95 Pair.first->second = Vector.size();
96 Vector.push_back(std::make_pair(Arg, ValueT()));
97 return Vector.back().second;
98 }
99 return Vector[Pair.first->second].second;
100 }
101
102 std::pair<iterator, bool>
103 insert(const std::pair<KeyT, ValueT> &InsertPair) {
104 std::pair<typename MapTy::iterator, bool> Pair =
105 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
106 if (Pair.second) {
107 Pair.first->second = Vector.size();
108 Vector.push_back(InsertPair);
109 return std::make_pair(llvm::prior(Vector.end()), true);
110 }
111 return std::make_pair(Vector.begin() + Pair.first->second, false);
112 }
113
114 const_iterator find(KeyT Key) const {
115 typename MapTy::const_iterator It = Map.find(Key);
116 if (It == Map.end()) return Vector.end();
117 return Vector.begin() + It->second;
118 }
119
120 /// blot - This is similar to erase, but instead of removing the element
121 /// from the vector, it just zeros out the key in the vector. This leaves
122 /// iterators intact, but clients must be prepared for zeroed-out keys when
123 /// iterating.
124 void blot(KeyT Key) {
125 typename MapTy::iterator It = Map.find(Key);
126 if (It == Map.end()) return;
127 Vector[It->second].first = KeyT();
128 Map.erase(It);
129 }
130
131 void clear() {
132 Map.clear();
133 Vector.clear();
134 }
135 };
136}
137
138//===----------------------------------------------------------------------===//
139// ARC Utilities.
140//===----------------------------------------------------------------------===//
141
142namespace {
143 /// InstructionClass - A simple classification for instructions.
144 enum InstructionClass {
145 IC_Retain, ///< objc_retain
146 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
147 IC_RetainBlock, ///< objc_retainBlock
148 IC_Release, ///< objc_release
149 IC_Autorelease, ///< objc_autorelease
150 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
151 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
152 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
153 IC_NoopCast, ///< objc_retainedObject, etc.
154 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
155 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
156 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
157 IC_StoreWeak, ///< objc_storeWeak (primitive)
158 IC_InitWeak, ///< objc_initWeak (derived)
159 IC_LoadWeak, ///< objc_loadWeak (derived)
160 IC_MoveWeak, ///< objc_moveWeak (derived)
161 IC_CopyWeak, ///< objc_copyWeak (derived)
162 IC_DestroyWeak, ///< objc_destroyWeak (derived)
163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
164 IC_Call, ///< could call objc_release
165 IC_User, ///< could "use" a pointer
166 IC_None ///< anything else
167 };
168}
169
170/// IsPotentialUse - Test whether the given value is possible a
171/// reference-counted pointer.
172static bool IsPotentialUse(const Value *Op) {
173 // Pointers to static or stack storage are not reference-counted pointers.
174 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
175 return false;
176 // Special arguments are not reference-counted.
177 if (const Argument *Arg = dyn_cast<Argument>(Op))
178 if (Arg->hasByValAttr() ||
179 Arg->hasNestAttr() ||
180 Arg->hasStructRetAttr())
181 return false;
182 // Only consider values with pointer types, and not function pointers.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000183 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
John McCall9fbd3182011-06-15 23:37:01 +0000184 if (!Ty || isa<FunctionType>(Ty->getElementType()))
185 return false;
186 // Conservatively assume anything else is a potential use.
187 return true;
188}
189
190/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
191/// of construct CS is.
192static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
193 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
194 I != E; ++I)
195 if (IsPotentialUse(*I))
196 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
197
198 return CS.onlyReadsMemory() ? IC_None : IC_Call;
199}
200
201/// GetFunctionClass - Determine if F is one of the special known Functions.
202/// If it isn't, return IC_CallOrUser.
203static InstructionClass GetFunctionClass(const Function *F) {
204 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
205
206 // No arguments.
207 if (AI == AE)
208 return StringSwitch<InstructionClass>(F->getName())
209 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
210 .Default(IC_CallOrUser);
211
212 // One argument.
213 const Argument *A0 = AI++;
214 if (AI == AE)
215 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000216 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
217 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000218 // Argument is i8*.
219 if (ETy->isIntegerTy(8))
220 return StringSwitch<InstructionClass>(F->getName())
221 .Case("objc_retain", IC_Retain)
222 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
223 .Case("objc_retainBlock", IC_RetainBlock)
224 .Case("objc_release", IC_Release)
225 .Case("objc_autorelease", IC_Autorelease)
226 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
227 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
228 .Case("objc_retainedObject", IC_NoopCast)
229 .Case("objc_unretainedObject", IC_NoopCast)
230 .Case("objc_unretainedPointer", IC_NoopCast)
231 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
232 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
233 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
234 .Default(IC_CallOrUser);
235
236 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000237 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000238 if (Pte->getElementType()->isIntegerTy(8))
239 return StringSwitch<InstructionClass>(F->getName())
240 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
241 .Case("objc_loadWeak", IC_LoadWeak)
242 .Case("objc_destroyWeak", IC_DestroyWeak)
243 .Default(IC_CallOrUser);
244 }
245
246 // Two arguments, first is i8**.
247 const Argument *A1 = AI++;
248 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000249 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
250 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000251 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000252 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
253 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000254 // Second argument is i8*
255 if (ETy1->isIntegerTy(8))
256 return StringSwitch<InstructionClass>(F->getName())
257 .Case("objc_storeWeak", IC_StoreWeak)
258 .Case("objc_initWeak", IC_InitWeak)
259 .Default(IC_CallOrUser);
260 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000261 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000262 if (Pte1->getElementType()->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_moveWeak", IC_MoveWeak)
265 .Case("objc_copyWeak", IC_CopyWeak)
266 .Default(IC_CallOrUser);
267 }
268
269 // Anything else.
270 return IC_CallOrUser;
271}
272
273/// GetInstructionClass - Determine what kind of construct V is.
274static InstructionClass GetInstructionClass(const Value *V) {
275 if (const Instruction *I = dyn_cast<Instruction>(V)) {
276 // Any instruction other than bitcast and gep with a pointer operand have a
277 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
278 // to a subsequent use, rather than using it themselves, in this sense.
279 // As a short cut, several other opcodes are known to have no pointer
280 // operands of interest. And ret is never followed by a release, so it's
281 // not interesting to examine.
282 switch (I->getOpcode()) {
283 case Instruction::Call: {
284 const CallInst *CI = cast<CallInst>(I);
285 // Check for calls to special functions.
286 if (const Function *F = CI->getCalledFunction()) {
287 InstructionClass Class = GetFunctionClass(F);
288 if (Class != IC_CallOrUser)
289 return Class;
290
291 // None of the intrinsic functions do objc_release. For intrinsics, the
292 // only question is whether or not they may be users.
293 switch (F->getIntrinsicID()) {
294 case 0: break;
295 case Intrinsic::bswap: case Intrinsic::ctpop:
296 case Intrinsic::ctlz: case Intrinsic::cttz:
297 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
298 case Intrinsic::stacksave: case Intrinsic::stackrestore:
299 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
300 // Don't let dbg info affect our results.
301 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
302 // Short cut: Some intrinsics obviously don't use ObjC pointers.
303 return IC_None;
304 default:
305 for (Function::const_arg_iterator AI = F->arg_begin(),
306 AE = F->arg_end(); AI != AE; ++AI)
307 if (IsPotentialUse(AI))
308 return IC_User;
309 return IC_None;
310 }
311 }
312 return GetCallSiteClass(CI);
313 }
314 case Instruction::Invoke:
315 return GetCallSiteClass(cast<InvokeInst>(I));
316 case Instruction::BitCast:
317 case Instruction::GetElementPtr:
318 case Instruction::Select: case Instruction::PHI:
319 case Instruction::Ret: case Instruction::Br:
320 case Instruction::Switch: case Instruction::IndirectBr:
321 case Instruction::Alloca: case Instruction::VAArg:
322 case Instruction::Add: case Instruction::FAdd:
323 case Instruction::Sub: case Instruction::FSub:
324 case Instruction::Mul: case Instruction::FMul:
325 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
326 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
327 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
328 case Instruction::And: case Instruction::Or: case Instruction::Xor:
329 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
330 case Instruction::IntToPtr: case Instruction::FCmp:
331 case Instruction::FPTrunc: case Instruction::FPExt:
332 case Instruction::FPToUI: case Instruction::FPToSI:
333 case Instruction::UIToFP: case Instruction::SIToFP:
334 case Instruction::InsertElement: case Instruction::ExtractElement:
335 case Instruction::ShuffleVector:
336 case Instruction::ExtractValue:
337 break;
338 case Instruction::ICmp:
339 // Comparing a pointer with null, or any other constant, isn't an
340 // interesting use, because we don't care what the pointer points to, or
341 // about the values of any other dynamic reference-counted pointers.
342 if (IsPotentialUse(I->getOperand(1)))
343 return IC_User;
344 break;
345 default:
346 // For anything else, check all the operands.
347 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
348 OI != OE; ++OI)
349 if (IsPotentialUse(*OI))
350 return IC_User;
351 }
352 }
353
354 // Otherwise, it's totally inert for ARC purposes.
355 return IC_None;
356}
357
358/// GetBasicInstructionClass - Determine what kind of construct V is. This is
359/// similar to GetInstructionClass except that it only detects objc runtine
360/// calls. This allows it to be faster.
361static InstructionClass GetBasicInstructionClass(const Value *V) {
362 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
363 if (const Function *F = CI->getCalledFunction())
364 return GetFunctionClass(F);
365 // Otherwise, be conservative.
366 return IC_CallOrUser;
367 }
368
369 // Otherwise, be conservative.
370 return IC_User;
371}
372
373/// IsRetain - Test if the the given class is objc_retain or
374/// equivalent.
375static bool IsRetain(InstructionClass Class) {
376 return Class == IC_Retain ||
377 Class == IC_RetainRV;
378}
379
380/// IsAutorelease - Test if the the given class is objc_autorelease or
381/// equivalent.
382static bool IsAutorelease(InstructionClass Class) {
383 return Class == IC_Autorelease ||
384 Class == IC_AutoreleaseRV;
385}
386
387/// IsForwarding - Test if the given class represents instructions which return
388/// their argument verbatim.
389static bool IsForwarding(InstructionClass Class) {
390 // objc_retainBlock technically doesn't always return its argument
391 // verbatim, but it doesn't matter for our purposes here.
392 return Class == IC_Retain ||
393 Class == IC_RetainRV ||
394 Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV ||
396 Class == IC_RetainBlock ||
397 Class == IC_NoopCast;
398}
399
400/// IsNoopOnNull - Test if the given class represents instructions which do
401/// nothing if passed a null pointer.
402static bool IsNoopOnNull(InstructionClass Class) {
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Release ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock;
409}
410
411/// IsAlwaysTail - Test if the given class represents instructions which are
412/// always safe to mark with the "tail" keyword.
413static bool IsAlwaysTail(InstructionClass Class) {
414 // IC_RetainBlock may be given a stack argument.
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV;
419}
420
421/// IsNoThrow - Test if the given class represents instructions which are always
422/// safe to mark with the nounwind attribute..
423static bool IsNoThrow(InstructionClass Class) {
424 return Class == IC_Retain ||
425 Class == IC_RetainRV ||
426 Class == IC_RetainBlock ||
427 Class == IC_Release ||
428 Class == IC_Autorelease ||
429 Class == IC_AutoreleaseRV ||
430 Class == IC_AutoreleasepoolPush ||
431 Class == IC_AutoreleasepoolPop;
432}
433
434/// EraseInstruction - Erase the given instruction. ObjC calls return their
435/// argument verbatim, so if it's such a call and the return value has users,
436/// replace them with the argument value.
437static void EraseInstruction(Instruction *CI) {
438 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
439
440 bool Unused = CI->use_empty();
441
442 if (!Unused) {
443 // Replace the return value with the argument.
444 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
445 "Can't delete non-forwarding instruction with users!");
446 CI->replaceAllUsesWith(OldArg);
447 }
448
449 CI->eraseFromParent();
450
451 if (Unused)
452 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
453}
454
455/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
456/// also knows how to look through objc_retain and objc_autorelease calls, which
457/// we know to return their argument verbatim.
458static const Value *GetUnderlyingObjCPtr(const Value *V) {
459 for (;;) {
460 V = GetUnderlyingObject(V);
461 if (!IsForwarding(GetBasicInstructionClass(V)))
462 break;
463 V = cast<CallInst>(V)->getArgOperand(0);
464 }
465
466 return V;
467}
468
469/// StripPointerCastsAndObjCCalls - This is a wrapper around
470/// Value::stripPointerCasts which also knows how to look through objc_retain
471/// and objc_autorelease calls, which we know to return their argument verbatim.
472static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
473 for (;;) {
474 V = V->stripPointerCasts();
475 if (!IsForwarding(GetBasicInstructionClass(V)))
476 break;
477 V = cast<CallInst>(V)->getArgOperand(0);
478 }
479 return V;
480}
481
482/// StripPointerCastsAndObjCCalls - This is a wrapper around
483/// Value::stripPointerCasts which also knows how to look through objc_retain
484/// and objc_autorelease calls, which we know to return their argument verbatim.
485static Value *StripPointerCastsAndObjCCalls(Value *V) {
486 for (;;) {
487 V = V->stripPointerCasts();
488 if (!IsForwarding(GetBasicInstructionClass(V)))
489 break;
490 V = cast<CallInst>(V)->getArgOperand(0);
491 }
492 return V;
493}
494
495/// GetObjCArg - Assuming the given instruction is one of the special calls such
496/// as objc_retain or objc_release, return the argument value, stripped of no-op
497/// casts and forwarding calls.
498static Value *GetObjCArg(Value *Inst) {
499 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
500}
501
502/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
503/// isObjCIdentifiedObject, except that it uses special knowledge of
504/// ObjC conventions...
505static bool IsObjCIdentifiedObject(const Value *V) {
506 // Assume that call results and arguments have their own "provenance".
507 // Constants (including GlobalVariables) and Allocas are never
508 // reference-counted.
509 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
510 isa<Argument>(V) || isa<Constant>(V) ||
511 isa<AllocaInst>(V))
512 return true;
513
514 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
515 const Value *Pointer =
516 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
517 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
518 StringRef Name = GV->getName();
519 // These special variables are known to hold values which are not
520 // reference-counted pointers.
521 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
522 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
523 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
524 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
525 Name.startswith("\01l_objc_msgSend_fixup_"))
526 return true;
527 }
528 }
529
530 return false;
531}
532
533/// FindSingleUseIdentifiedObject - This is similar to
534/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
535/// with multiple uses.
536static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
537 if (Arg->hasOneUse()) {
538 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
539 return FindSingleUseIdentifiedObject(BC->getOperand(0));
540 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
541 if (GEP->hasAllZeroIndices())
542 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
543 if (IsForwarding(GetBasicInstructionClass(Arg)))
544 return FindSingleUseIdentifiedObject(
545 cast<CallInst>(Arg)->getArgOperand(0));
546 if (!IsObjCIdentifiedObject(Arg))
547 return 0;
548 return Arg;
549 }
550
551 // If we found an identifiable object but it has multiple uses, but they
552 // are trivial uses, we can still consider this to be a single-use
553 // value.
554 if (IsObjCIdentifiedObject(Arg)) {
555 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
556 UI != UE; ++UI) {
557 const User *U = *UI;
558 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
559 return 0;
560 }
561
562 return Arg;
563 }
564
565 return 0;
566}
567
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000568/// ModuleHasARC - Test if the given module looks interesting to run ARC
569/// optimization on.
570static bool ModuleHasARC(const Module &M) {
571 return
572 M.getNamedValue("objc_retain") ||
573 M.getNamedValue("objc_release") ||
574 M.getNamedValue("objc_autorelease") ||
575 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
576 M.getNamedValue("objc_retainBlock") ||
577 M.getNamedValue("objc_autoreleaseReturnValue") ||
578 M.getNamedValue("objc_autoreleasePoolPush") ||
579 M.getNamedValue("objc_loadWeakRetained") ||
580 M.getNamedValue("objc_loadWeak") ||
581 M.getNamedValue("objc_destroyWeak") ||
582 M.getNamedValue("objc_storeWeak") ||
583 M.getNamedValue("objc_initWeak") ||
584 M.getNamedValue("objc_moveWeak") ||
585 M.getNamedValue("objc_copyWeak") ||
586 M.getNamedValue("objc_retainedObject") ||
587 M.getNamedValue("objc_unretainedObject") ||
588 M.getNamedValue("objc_unretainedPointer");
589}
590
John McCall9fbd3182011-06-15 23:37:01 +0000591//===----------------------------------------------------------------------===//
592// ARC AliasAnalysis.
593//===----------------------------------------------------------------------===//
594
595#include "llvm/Pass.h"
596#include "llvm/Analysis/AliasAnalysis.h"
597#include "llvm/Analysis/Passes.h"
598
599namespace {
600 /// ObjCARCAliasAnalysis - This is a simple alias analysis
601 /// implementation that uses knowledge of ARC constructs to answer queries.
602 ///
603 /// TODO: This class could be generalized to know about other ObjC-specific
604 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
605 /// even though their offsets are dynamic.
606 class ObjCARCAliasAnalysis : public ImmutablePass,
607 public AliasAnalysis {
608 public:
609 static char ID; // Class identification, replacement for typeinfo
610 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
611 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
612 }
613
614 private:
615 virtual void initializePass() {
616 InitializeAliasAnalysis(this);
617 }
618
619 /// getAdjustedAnalysisPointer - This method is used when a pass implements
620 /// an analysis interface through multiple inheritance. If needed, it
621 /// should override this to adjust the this pointer as needed for the
622 /// specified pass info.
623 virtual void *getAdjustedAnalysisPointer(const void *PI) {
624 if (PI == &AliasAnalysis::ID)
625 return (AliasAnalysis*)this;
626 return this;
627 }
628
629 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
630 virtual AliasResult alias(const Location &LocA, const Location &LocB);
631 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
632 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
633 virtual ModRefBehavior getModRefBehavior(const Function *F);
634 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
635 const Location &Loc);
636 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
637 ImmutableCallSite CS2);
638 };
639} // End of anonymous namespace
640
641// Register this pass...
642char ObjCARCAliasAnalysis::ID = 0;
643INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
644 "ObjC-ARC-Based Alias Analysis", false, true, false)
645
646ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
647 return new ObjCARCAliasAnalysis();
648}
649
650void
651ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
652 AU.setPreservesAll();
653 AliasAnalysis::getAnalysisUsage(AU);
654}
655
656AliasAnalysis::AliasResult
657ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
658 if (!EnableARCOpts)
659 return AliasAnalysis::alias(LocA, LocB);
660
661 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
662 // precise alias query.
663 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
664 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
665 AliasResult Result =
666 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
667 Location(SB, LocB.Size, LocB.TBAATag));
668 if (Result != MayAlias)
669 return Result;
670
671 // If that failed, climb to the underlying object, including climbing through
672 // ObjC-specific no-ops, and try making an imprecise alias query.
673 const Value *UA = GetUnderlyingObjCPtr(SA);
674 const Value *UB = GetUnderlyingObjCPtr(SB);
675 if (UA != SA || UB != SB) {
676 Result = AliasAnalysis::alias(Location(UA), Location(UB));
677 // We can't use MustAlias or PartialAlias results here because
678 // GetUnderlyingObjCPtr may return an offsetted pointer value.
679 if (Result == NoAlias)
680 return NoAlias;
681 }
682
683 // If that failed, fail. We don't need to chain here, since that's covered
684 // by the earlier precise query.
685 return MayAlias;
686}
687
688bool
689ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
690 bool OrLocal) {
691 if (!EnableARCOpts)
692 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
693
694 // First, strip off no-ops, including ObjC-specific no-ops, and try making
695 // a precise alias query.
696 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
697 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
698 OrLocal))
699 return true;
700
701 // If that failed, climb to the underlying object, including climbing through
702 // ObjC-specific no-ops, and try making an imprecise alias query.
703 const Value *U = GetUnderlyingObjCPtr(S);
704 if (U != S)
705 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
706
707 // If that failed, fail. We don't need to chain here, since that's covered
708 // by the earlier precise query.
709 return false;
710}
711
712AliasAnalysis::ModRefBehavior
713ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
714 // We have nothing to do. Just chain to the next AliasAnalysis.
715 return AliasAnalysis::getModRefBehavior(CS);
716}
717
718AliasAnalysis::ModRefBehavior
719ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
720 if (!EnableARCOpts)
721 return AliasAnalysis::getModRefBehavior(F);
722
723 switch (GetFunctionClass(F)) {
724 case IC_NoopCast:
725 return DoesNotAccessMemory;
726 default:
727 break;
728 }
729
730 return AliasAnalysis::getModRefBehavior(F);
731}
732
733AliasAnalysis::ModRefResult
734ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
735 if (!EnableARCOpts)
736 return AliasAnalysis::getModRefInfo(CS, Loc);
737
738 switch (GetBasicInstructionClass(CS.getInstruction())) {
739 case IC_Retain:
740 case IC_RetainRV:
741 case IC_RetainBlock:
742 case IC_Autorelease:
743 case IC_AutoreleaseRV:
744 case IC_NoopCast:
745 case IC_AutoreleasepoolPush:
746 case IC_FusedRetainAutorelease:
747 case IC_FusedRetainAutoreleaseRV:
748 // These functions don't access any memory visible to the compiler.
749 return NoModRef;
750 default:
751 break;
752 }
753
754 return AliasAnalysis::getModRefInfo(CS, Loc);
755}
756
757AliasAnalysis::ModRefResult
758ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
759 ImmutableCallSite CS2) {
760 // TODO: Theoretically we could check for dependencies between objc_* calls
761 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
762 return AliasAnalysis::getModRefInfo(CS1, CS2);
763}
764
765//===----------------------------------------------------------------------===//
766// ARC expansion.
767//===----------------------------------------------------------------------===//
768
769#include "llvm/Support/InstIterator.h"
770#include "llvm/Transforms/Scalar.h"
771
772namespace {
773 /// ObjCARCExpand - Early ARC transformations.
774 class ObjCARCExpand : public FunctionPass {
775 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000776 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000777 virtual bool runOnFunction(Function &F);
778
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000779 /// Run - A flag indicating whether this optimization pass should run.
780 bool Run;
781
John McCall9fbd3182011-06-15 23:37:01 +0000782 public:
783 static char ID;
784 ObjCARCExpand() : FunctionPass(ID) {
785 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
786 }
787 };
788}
789
790char ObjCARCExpand::ID = 0;
791INITIALIZE_PASS(ObjCARCExpand,
792 "objc-arc-expand", "ObjC ARC expansion", false, false)
793
794Pass *llvm::createObjCARCExpandPass() {
795 return new ObjCARCExpand();
796}
797
798void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
799 AU.setPreservesCFG();
800}
801
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000802bool ObjCARCExpand::doInitialization(Module &M) {
803 Run = ModuleHasARC(M);
804 return false;
805}
806
John McCall9fbd3182011-06-15 23:37:01 +0000807bool ObjCARCExpand::runOnFunction(Function &F) {
808 if (!EnableARCOpts)
809 return false;
810
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000811 // If nothing in the Module uses ARC, don't do anything.
812 if (!Run)
813 return false;
814
John McCall9fbd3182011-06-15 23:37:01 +0000815 bool Changed = false;
816
817 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
818 Instruction *Inst = &*I;
819
820 switch (GetBasicInstructionClass(Inst)) {
821 case IC_Retain:
822 case IC_RetainRV:
823 case IC_Autorelease:
824 case IC_AutoreleaseRV:
825 case IC_FusedRetainAutorelease:
826 case IC_FusedRetainAutoreleaseRV:
827 // These calls return their argument verbatim, as a low-level
828 // optimization. However, this makes high-level optimizations
829 // harder. Undo any uses of this optimization that the front-end
830 // emitted here. We'll redo them in a later pass.
831 Changed = true;
832 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
833 break;
834 default:
835 break;
836 }
837 }
838
839 return Changed;
840}
841
842//===----------------------------------------------------------------------===//
843// ARC optimization.
844//===----------------------------------------------------------------------===//
845
846// TODO: On code like this:
847//
848// objc_retain(%x)
849// stuff_that_cannot_release()
850// objc_autorelease(%x)
851// stuff_that_cannot_release()
852// objc_retain(%x)
853// stuff_that_cannot_release()
854// objc_autorelease(%x)
855//
856// The second retain and autorelease can be deleted.
857
858// TODO: It should be possible to delete
859// objc_autoreleasePoolPush and objc_autoreleasePoolPop
860// pairs if nothing is actually autoreleased between them. Also, autorelease
861// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
862// after inlining) can be turned into plain release calls.
863
864// TODO: Critical-edge splitting. If the optimial insertion point is
865// a critical edge, the current algorithm has to fail, because it doesn't
866// know how to split edges. It should be possible to make the optimizer
867// think in terms of edges, rather than blocks, and then split critical
868// edges on demand.
869
870// TODO: OptimizeSequences could generalized to be Interprocedural.
871
872// TODO: Recognize that a bunch of other objc runtime calls have
873// non-escaping arguments and non-releasing arguments, and may be
874// non-autoreleasing.
875
876// TODO: Sink autorelease calls as far as possible. Unfortunately we
877// usually can't sink them past other calls, which would be the main
878// case where it would be useful.
879
Dan Gohmane6d5e882011-08-19 00:26:36 +0000880// TODO: The pointer returned from objc_loadWeakRetained is retained.
881
882// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000883
John McCall9fbd3182011-06-15 23:37:01 +0000884#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +0000885#include "llvm/Constants.h"
886#include "llvm/LLVMContext.h"
887#include "llvm/Support/ErrorHandling.h"
888#include "llvm/Support/CFG.h"
889#include "llvm/ADT/PostOrderIterator.h"
890#include "llvm/ADT/Statistic.h"
891
892STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
893STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
894STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
895STATISTIC(NumRets, "Number of return value forwarding "
896 "retain+autoreleaes eliminated");
897STATISTIC(NumRRs, "Number of retain+release paths eliminated");
898STATISTIC(NumPeeps, "Number of calls peephole-optimized");
899
900namespace {
901 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
902 /// uses many of the same techniques, except it uses special ObjC-specific
903 /// reasoning about pointer relationships.
904 class ProvenanceAnalysis {
905 AliasAnalysis *AA;
906
907 typedef std::pair<const Value *, const Value *> ValuePairTy;
908 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
909 CachedResultsTy CachedResults;
910
911 bool relatedCheck(const Value *A, const Value *B);
912 bool relatedSelect(const SelectInst *A, const Value *B);
913 bool relatedPHI(const PHINode *A, const Value *B);
914
915 // Do not implement.
916 void operator=(const ProvenanceAnalysis &);
917 ProvenanceAnalysis(const ProvenanceAnalysis &);
918
919 public:
920 ProvenanceAnalysis() {}
921
922 void setAA(AliasAnalysis *aa) { AA = aa; }
923
924 AliasAnalysis *getAA() const { return AA; }
925
926 bool related(const Value *A, const Value *B);
927
928 void clear() {
929 CachedResults.clear();
930 }
931 };
932}
933
934bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
935 // If the values are Selects with the same condition, we can do a more precise
936 // check: just check for relations between the values on corresponding arms.
937 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
938 if (A->getCondition() == SB->getCondition()) {
939 if (related(A->getTrueValue(), SB->getTrueValue()))
940 return true;
941 if (related(A->getFalseValue(), SB->getFalseValue()))
942 return true;
943 return false;
944 }
945
946 // Check both arms of the Select node individually.
947 if (related(A->getTrueValue(), B))
948 return true;
949 if (related(A->getFalseValue(), B))
950 return true;
951
952 // The arms both checked out.
953 return false;
954}
955
956bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
957 // If the values are PHIs in the same block, we can do a more precise as well
958 // as efficient check: just check for relations between the values on
959 // corresponding edges.
960 if (const PHINode *PNB = dyn_cast<PHINode>(B))
961 if (PNB->getParent() == A->getParent()) {
962 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
963 if (related(A->getIncomingValue(i),
964 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
965 return true;
966 return false;
967 }
968
969 // Check each unique source of the PHI node against B.
970 SmallPtrSet<const Value *, 4> UniqueSrc;
971 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
972 const Value *PV1 = A->getIncomingValue(i);
973 if (UniqueSrc.insert(PV1) && related(PV1, B))
974 return true;
975 }
976
977 // All of the arms checked out.
978 return false;
979}
980
981/// isStoredObjCPointer - Test if the value of P, or any value covered by its
982/// provenance, is ever stored within the function (not counting callees).
983static bool isStoredObjCPointer(const Value *P) {
984 SmallPtrSet<const Value *, 8> Visited;
985 SmallVector<const Value *, 8> Worklist;
986 Worklist.push_back(P);
987 Visited.insert(P);
988 do {
989 P = Worklist.pop_back_val();
990 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
991 UI != UE; ++UI) {
992 const User *Ur = *UI;
993 if (isa<StoreInst>(Ur)) {
994 if (UI.getOperandNo() == 0)
995 // The pointer is stored.
996 return true;
997 // The pointed is stored through.
998 continue;
999 }
1000 if (isa<CallInst>(Ur))
1001 // The pointer is passed as an argument, ignore this.
1002 continue;
1003 if (isa<PtrToIntInst>(P))
1004 // Assume the worst.
1005 return true;
1006 if (Visited.insert(Ur))
1007 Worklist.push_back(Ur);
1008 }
1009 } while (!Worklist.empty());
1010
1011 // Everything checked out.
1012 return false;
1013}
1014
1015bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1016 // Skip past provenance pass-throughs.
1017 A = GetUnderlyingObjCPtr(A);
1018 B = GetUnderlyingObjCPtr(B);
1019
1020 // Quick check.
1021 if (A == B)
1022 return true;
1023
1024 // Ask regular AliasAnalysis, for a first approximation.
1025 switch (AA->alias(A, B)) {
1026 case AliasAnalysis::NoAlias:
1027 return false;
1028 case AliasAnalysis::MustAlias:
1029 case AliasAnalysis::PartialAlias:
1030 return true;
1031 case AliasAnalysis::MayAlias:
1032 break;
1033 }
1034
1035 bool AIsIdentified = IsObjCIdentifiedObject(A);
1036 bool BIsIdentified = IsObjCIdentifiedObject(B);
1037
1038 // An ObjC-Identified object can't alias a load if it is never locally stored.
1039 if (AIsIdentified) {
1040 if (BIsIdentified) {
1041 // If both pointers have provenance, they can be directly compared.
1042 if (A != B)
1043 return false;
1044 } else {
1045 if (isa<LoadInst>(B))
1046 return isStoredObjCPointer(A);
1047 }
1048 } else {
1049 if (BIsIdentified && isa<LoadInst>(A))
1050 return isStoredObjCPointer(B);
1051 }
1052
1053 // Special handling for PHI and Select.
1054 if (const PHINode *PN = dyn_cast<PHINode>(A))
1055 return relatedPHI(PN, B);
1056 if (const PHINode *PN = dyn_cast<PHINode>(B))
1057 return relatedPHI(PN, A);
1058 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1059 return relatedSelect(S, B);
1060 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1061 return relatedSelect(S, A);
1062
1063 // Conservative.
1064 return true;
1065}
1066
1067bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1068 // Begin by inserting a conservative value into the map. If the insertion
1069 // fails, we have the answer already. If it succeeds, leave it there until we
1070 // compute the real answer to guard against recursive queries.
1071 if (A > B) std::swap(A, B);
1072 std::pair<CachedResultsTy::iterator, bool> Pair =
1073 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1074 if (!Pair.second)
1075 return Pair.first->second;
1076
1077 bool Result = relatedCheck(A, B);
1078 CachedResults[ValuePairTy(A, B)] = Result;
1079 return Result;
1080}
1081
1082namespace {
1083 // Sequence - A sequence of states that a pointer may go through in which an
1084 // objc_retain and objc_release are actually needed.
1085 enum Sequence {
1086 S_None,
1087 S_Retain, ///< objc_retain(x)
1088 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1089 S_Use, ///< any use of x
1090 S_Stop, ///< like S_Release, but code motion is stopped
1091 S_Release, ///< objc_release(x)
1092 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1093 };
1094}
1095
1096static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1097 // The easy cases.
1098 if (A == B)
1099 return A;
1100 if (A == S_None || B == S_None)
1101 return S_None;
1102
John McCall9fbd3182011-06-15 23:37:01 +00001103 if (A > B) std::swap(A, B);
1104 if (TopDown) {
1105 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001106 if ((A == S_Retain || A == S_CanRelease) &&
1107 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001108 return B;
1109 } else {
1110 // Choose the side which is further along in the sequence.
1111 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001112 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001113 return A;
1114 // If both sides are releases, choose the more conservative one.
1115 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1116 return A;
1117 if (A == S_Release && B == S_MovableRelease)
1118 return A;
1119 }
1120
1121 return S_None;
1122}
1123
1124namespace {
1125 /// RRInfo - Unidirectional information about either a
1126 /// retain-decrement-use-release sequence or release-use-decrement-retain
1127 /// reverese sequence.
1128 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001129 /// KnownSafe - After an objc_retain, the reference count of the referenced
1130 /// object is known to be positive. Similarly, before an objc_release, the
1131 /// reference count of the referenced object is known to be positive. If
1132 /// there are retain-release pairs in code regions where the retain count
1133 /// is known to be positive, they can be eliminated, regardless of any side
1134 /// effects between them.
1135 ///
1136 /// Also, a retain+release pair nested within another retain+release
1137 /// pair all on the known same pointer value can be eliminated, regardless
1138 /// of any intervening side effects.
1139 ///
1140 /// KnownSafe is true when either of these conditions is satisfied.
1141 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001142
1143 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1144 /// opposed to objc_retain calls).
1145 bool IsRetainBlock;
1146
1147 /// IsTailCallRelease - True of the objc_release calls are all marked
1148 /// with the "tail" keyword.
1149 bool IsTailCallRelease;
1150
1151 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1152 /// a clang.imprecise_release tag, this is the metadata tag.
1153 MDNode *ReleaseMetadata;
1154
1155 /// Calls - For a top-down sequence, the set of objc_retains or
1156 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1157 SmallPtrSet<Instruction *, 2> Calls;
1158
1159 /// ReverseInsertPts - The set of optimal insert positions for
1160 /// moving calls in the opposite sequence.
1161 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1162
1163 RRInfo() :
Dan Gohmane6d5e882011-08-19 00:26:36 +00001164 KnownSafe(false), IsRetainBlock(false), IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001165 ReleaseMetadata(0) {}
1166
1167 void clear();
1168 };
1169}
1170
1171void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001172 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001173 IsRetainBlock = false;
1174 IsTailCallRelease = false;
1175 ReleaseMetadata = 0;
1176 Calls.clear();
1177 ReverseInsertPts.clear();
1178}
1179
1180namespace {
1181 /// PtrState - This class summarizes several per-pointer runtime properties
1182 /// which are propogated through the flow graph.
1183 class PtrState {
1184 /// RefCount - The known minimum number of reference count increments.
1185 unsigned RefCount;
1186
Dan Gohmane6d5e882011-08-19 00:26:36 +00001187 /// NestCount - The known minimum level of retain+release nesting.
1188 unsigned NestCount;
1189
John McCall9fbd3182011-06-15 23:37:01 +00001190 /// Seq - The current position in the sequence.
1191 Sequence Seq;
1192
1193 public:
1194 /// RRI - Unidirectional information about the current sequence.
1195 /// TODO: Encapsulate this better.
1196 RRInfo RRI;
1197
Dan Gohmane6d5e882011-08-19 00:26:36 +00001198 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001199
Dan Gohmana7f7db22011-08-12 00:26:31 +00001200 void SetAtLeastOneRefCount() {
1201 if (RefCount == 0) RefCount = 1;
1202 }
1203
John McCall9fbd3182011-06-15 23:37:01 +00001204 void IncrementRefCount() {
1205 if (RefCount != UINT_MAX) ++RefCount;
1206 }
1207
1208 void DecrementRefCount() {
1209 if (RefCount != 0) --RefCount;
1210 }
1211
John McCall9fbd3182011-06-15 23:37:01 +00001212 bool IsKnownIncremented() const {
1213 return RefCount > 0;
1214 }
1215
Dan Gohmane6d5e882011-08-19 00:26:36 +00001216 void IncrementNestCount() {
1217 if (NestCount != UINT_MAX) ++NestCount;
1218 }
1219
1220 void DecrementNestCount() {
1221 if (NestCount != 0) --NestCount;
1222 }
1223
1224 bool IsKnownNested() const {
1225 return NestCount > 0;
1226 }
1227
John McCall9fbd3182011-06-15 23:37:01 +00001228 void SetSeq(Sequence NewSeq) {
1229 Seq = NewSeq;
1230 }
1231
1232 void SetSeqToRelease(MDNode *M) {
1233 if (Seq == S_None || Seq == S_Use) {
1234 Seq = M ? S_MovableRelease : S_Release;
1235 RRI.ReleaseMetadata = M;
1236 } else if (Seq != S_MovableRelease || RRI.ReleaseMetadata != M) {
1237 Seq = S_Release;
1238 RRI.ReleaseMetadata = 0;
1239 }
1240 }
1241
1242 Sequence GetSeq() const {
1243 return Seq;
1244 }
1245
1246 void ClearSequenceProgress() {
1247 Seq = S_None;
1248 RRI.clear();
1249 }
1250
1251 void Merge(const PtrState &Other, bool TopDown);
1252 };
1253}
1254
1255void
1256PtrState::Merge(const PtrState &Other, bool TopDown) {
1257 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1258 RefCount = std::min(RefCount, Other.RefCount);
Dan Gohmane6d5e882011-08-19 00:26:36 +00001259 NestCount = std::min(NestCount, Other.NestCount);
John McCall9fbd3182011-06-15 23:37:01 +00001260
1261 // We can't merge a plain objc_retain with an objc_retainBlock.
1262 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1263 Seq = S_None;
1264
1265 if (Seq == S_None) {
1266 RRI.clear();
1267 } else {
1268 // Conservatively merge the ReleaseMetadata information.
1269 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1270 RRI.ReleaseMetadata = 0;
1271
Dan Gohmane6d5e882011-08-19 00:26:36 +00001272 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001273 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1274 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1275 RRI.ReverseInsertPts.insert(Other.RRI.ReverseInsertPts.begin(),
1276 Other.RRI.ReverseInsertPts.end());
1277 }
1278}
1279
1280namespace {
1281 /// BBState - Per-BasicBlock state.
1282 class BBState {
1283 /// TopDownPathCount - The number of unique control paths from the entry
1284 /// which can reach this block.
1285 unsigned TopDownPathCount;
1286
1287 /// BottomUpPathCount - The number of unique control paths to exits
1288 /// from this block.
1289 unsigned BottomUpPathCount;
1290
1291 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1292 typedef MapVector<const Value *, PtrState> MapTy;
1293
1294 /// PerPtrTopDown - The top-down traversal uses this to record information
1295 /// known about a pointer at the bottom of each block.
1296 MapTy PerPtrTopDown;
1297
1298 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1299 /// known about a pointer at the top of each block.
1300 MapTy PerPtrBottomUp;
1301
1302 public:
1303 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1304
1305 typedef MapTy::iterator ptr_iterator;
1306 typedef MapTy::const_iterator ptr_const_iterator;
1307
1308 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1309 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1310 ptr_const_iterator top_down_ptr_begin() const {
1311 return PerPtrTopDown.begin();
1312 }
1313 ptr_const_iterator top_down_ptr_end() const {
1314 return PerPtrTopDown.end();
1315 }
1316
1317 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1318 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1319 ptr_const_iterator bottom_up_ptr_begin() const {
1320 return PerPtrBottomUp.begin();
1321 }
1322 ptr_const_iterator bottom_up_ptr_end() const {
1323 return PerPtrBottomUp.end();
1324 }
1325
1326 /// SetAsEntry - Mark this block as being an entry block, which has one
1327 /// path from the entry by definition.
1328 void SetAsEntry() { TopDownPathCount = 1; }
1329
1330 /// SetAsExit - Mark this block as being an exit block, which has one
1331 /// path to an exit by definition.
1332 void SetAsExit() { BottomUpPathCount = 1; }
1333
1334 PtrState &getPtrTopDownState(const Value *Arg) {
1335 return PerPtrTopDown[Arg];
1336 }
1337
1338 PtrState &getPtrBottomUpState(const Value *Arg) {
1339 return PerPtrBottomUp[Arg];
1340 }
1341
1342 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001343 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001344 }
1345
1346 void clearTopDownPointers() {
1347 PerPtrTopDown.clear();
1348 }
1349
1350 void InitFromPred(const BBState &Other);
1351 void InitFromSucc(const BBState &Other);
1352 void MergePred(const BBState &Other);
1353 void MergeSucc(const BBState &Other);
1354
1355 /// GetAllPathCount - Return the number of possible unique paths from an
1356 /// entry to an exit which pass through this block. This is only valid
1357 /// after both the top-down and bottom-up traversals are complete.
1358 unsigned GetAllPathCount() const {
1359 return TopDownPathCount * BottomUpPathCount;
1360 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001361
1362 /// IsVisitedTopDown - Test whether the block for this BBState has been
1363 /// visited by the top-down portion of the algorithm.
1364 bool isVisitedTopDown() const {
1365 return TopDownPathCount != 0;
1366 }
John McCall9fbd3182011-06-15 23:37:01 +00001367 };
1368}
1369
1370void BBState::InitFromPred(const BBState &Other) {
1371 PerPtrTopDown = Other.PerPtrTopDown;
1372 TopDownPathCount = Other.TopDownPathCount;
1373}
1374
1375void BBState::InitFromSucc(const BBState &Other) {
1376 PerPtrBottomUp = Other.PerPtrBottomUp;
1377 BottomUpPathCount = Other.BottomUpPathCount;
1378}
1379
1380/// MergePred - The top-down traversal uses this to merge information about
1381/// predecessors to form the initial state for a new block.
1382void BBState::MergePred(const BBState &Other) {
1383 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1384 // loop backedge. Loop backedges are special.
1385 TopDownPathCount += Other.TopDownPathCount;
1386
1387 // For each entry in the other set, if our set has an entry with the same key,
1388 // merge the entries. Otherwise, copy the entry and merge it with an empty
1389 // entry.
1390 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1391 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1392 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1393 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1394 /*TopDown=*/true);
1395 }
1396
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001397 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001398 // same key, force it to merge with an empty entry.
1399 for (ptr_iterator MI = top_down_ptr_begin(),
1400 ME = top_down_ptr_end(); MI != ME; ++MI)
1401 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1402 MI->second.Merge(PtrState(), /*TopDown=*/true);
1403}
1404
1405/// MergeSucc - The bottom-up traversal uses this to merge information about
1406/// successors to form the initial state for a new block.
1407void BBState::MergeSucc(const BBState &Other) {
1408 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1409 // loop backedge. Loop backedges are special.
1410 BottomUpPathCount += Other.BottomUpPathCount;
1411
1412 // For each entry in the other set, if our set has an entry with the
1413 // same key, merge the entries. Otherwise, copy the entry and merge
1414 // it with an empty entry.
1415 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1416 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1417 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1418 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1419 /*TopDown=*/false);
1420 }
1421
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001422 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001423 // with the same key, force it to merge with an empty entry.
1424 for (ptr_iterator MI = bottom_up_ptr_begin(),
1425 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1426 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1427 MI->second.Merge(PtrState(), /*TopDown=*/false);
1428}
1429
1430namespace {
1431 /// ObjCARCOpt - The main ARC optimization pass.
1432 class ObjCARCOpt : public FunctionPass {
1433 bool Changed;
1434 ProvenanceAnalysis PA;
1435
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001436 /// Run - A flag indicating whether this optimization pass should run.
1437 bool Run;
1438
John McCall9fbd3182011-06-15 23:37:01 +00001439 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1440 /// functions, for use in creating calls to them. These are initialized
1441 /// lazily to avoid cluttering up the Module with unused declarations.
1442 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001443 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001444
1445 /// UsedInThisFunciton - Flags which determine whether each of the
1446 /// interesting runtine functions is in fact used in the current function.
1447 unsigned UsedInThisFunction;
1448
1449 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1450 /// metadata.
1451 unsigned ImpreciseReleaseMDKind;
1452
1453 Constant *getRetainRVCallee(Module *M);
1454 Constant *getAutoreleaseRVCallee(Module *M);
1455 Constant *getReleaseCallee(Module *M);
1456 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001457 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001458 Constant *getAutoreleaseCallee(Module *M);
1459
1460 void OptimizeRetainCall(Function &F, Instruction *Retain);
1461 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1462 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1463 void OptimizeIndividualCalls(Function &F);
1464
1465 void CheckForCFGHazards(const BasicBlock *BB,
1466 DenseMap<const BasicBlock *, BBState> &BBStates,
1467 BBState &MyStates) const;
1468 bool VisitBottomUp(BasicBlock *BB,
1469 DenseMap<const BasicBlock *, BBState> &BBStates,
1470 MapVector<Value *, RRInfo> &Retains);
1471 bool VisitTopDown(BasicBlock *BB,
1472 DenseMap<const BasicBlock *, BBState> &BBStates,
1473 DenseMap<Value *, RRInfo> &Releases);
1474 bool Visit(Function &F,
1475 DenseMap<const BasicBlock *, BBState> &BBStates,
1476 MapVector<Value *, RRInfo> &Retains,
1477 DenseMap<Value *, RRInfo> &Releases);
1478
1479 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1480 MapVector<Value *, RRInfo> &Retains,
1481 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001482 SmallVectorImpl<Instruction *> &DeadInsts,
1483 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001484
1485 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1486 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001487 DenseMap<Value *, RRInfo> &Releases,
1488 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001489
1490 void OptimizeWeakCalls(Function &F);
1491
1492 bool OptimizeSequences(Function &F);
1493
1494 void OptimizeReturns(Function &F);
1495
1496 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1497 virtual bool doInitialization(Module &M);
1498 virtual bool runOnFunction(Function &F);
1499 virtual void releaseMemory();
1500
1501 public:
1502 static char ID;
1503 ObjCARCOpt() : FunctionPass(ID) {
1504 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1505 }
1506 };
1507}
1508
1509char ObjCARCOpt::ID = 0;
1510INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1511 "objc-arc", "ObjC ARC optimization", false, false)
1512INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1513INITIALIZE_PASS_END(ObjCARCOpt,
1514 "objc-arc", "ObjC ARC optimization", false, false)
1515
1516Pass *llvm::createObjCARCOptPass() {
1517 return new ObjCARCOpt();
1518}
1519
1520void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1521 AU.addRequired<ObjCARCAliasAnalysis>();
1522 AU.addRequired<AliasAnalysis>();
1523 // ARC optimization doesn't currently split critical edges.
1524 AU.setPreservesCFG();
1525}
1526
1527Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1528 if (!RetainRVCallee) {
1529 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001530 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1531 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001532 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001533 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001534 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1535 AttrListPtr Attributes;
1536 Attributes.addAttr(~0u, Attribute::NoUnwind);
1537 RetainRVCallee =
1538 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1539 Attributes);
1540 }
1541 return RetainRVCallee;
1542}
1543
1544Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1545 if (!AutoreleaseRVCallee) {
1546 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001547 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1548 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001549 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001550 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001551 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1552 AttrListPtr Attributes;
1553 Attributes.addAttr(~0u, Attribute::NoUnwind);
1554 AutoreleaseRVCallee =
1555 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1556 Attributes);
1557 }
1558 return AutoreleaseRVCallee;
1559}
1560
1561Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1562 if (!ReleaseCallee) {
1563 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001564 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001565 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1566 AttrListPtr Attributes;
1567 Attributes.addAttr(~0u, Attribute::NoUnwind);
1568 ReleaseCallee =
1569 M->getOrInsertFunction(
1570 "objc_release",
1571 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1572 Attributes);
1573 }
1574 return ReleaseCallee;
1575}
1576
1577Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1578 if (!RetainCallee) {
1579 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001580 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001581 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1582 AttrListPtr Attributes;
1583 Attributes.addAttr(~0u, Attribute::NoUnwind);
1584 RetainCallee =
1585 M->getOrInsertFunction(
1586 "objc_retain",
1587 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1588 Attributes);
1589 }
1590 return RetainCallee;
1591}
1592
Dan Gohman44280692011-07-22 22:29:21 +00001593Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1594 if (!RetainBlockCallee) {
1595 LLVMContext &C = M->getContext();
1596 std::vector<Type *> Params;
1597 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1598 AttrListPtr Attributes;
1599 Attributes.addAttr(~0u, Attribute::NoUnwind);
1600 RetainBlockCallee =
1601 M->getOrInsertFunction(
1602 "objc_retainBlock",
1603 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1604 Attributes);
1605 }
1606 return RetainBlockCallee;
1607}
1608
John McCall9fbd3182011-06-15 23:37:01 +00001609Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1610 if (!AutoreleaseCallee) {
1611 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001612 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001613 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1614 AttrListPtr Attributes;
1615 Attributes.addAttr(~0u, Attribute::NoUnwind);
1616 AutoreleaseCallee =
1617 M->getOrInsertFunction(
1618 "objc_autorelease",
1619 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1620 Attributes);
1621 }
1622 return AutoreleaseCallee;
1623}
1624
1625/// CanAlterRefCount - Test whether the given instruction can result in a
1626/// reference count modification (positive or negative) for the pointer's
1627/// object.
1628static bool
1629CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1630 ProvenanceAnalysis &PA, InstructionClass Class) {
1631 switch (Class) {
1632 case IC_Autorelease:
1633 case IC_AutoreleaseRV:
1634 case IC_User:
1635 // These operations never directly modify a reference count.
1636 return false;
1637 default: break;
1638 }
1639
1640 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1641 assert(CS && "Only calls can alter reference counts!");
1642
1643 // See if AliasAnalysis can help us with the call.
1644 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1645 if (AliasAnalysis::onlyReadsMemory(MRB))
1646 return false;
1647 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1648 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1649 I != E; ++I) {
1650 const Value *Op = *I;
1651 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1652 return true;
1653 }
1654 return false;
1655 }
1656
1657 // Assume the worst.
1658 return true;
1659}
1660
1661/// CanUse - Test whether the given instruction can "use" the given pointer's
1662/// object in a way that requires the reference count to be positive.
1663static bool
1664CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1665 InstructionClass Class) {
1666 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1667 if (Class == IC_Call)
1668 return false;
1669
1670 // Consider various instructions which may have pointer arguments which are
1671 // not "uses".
1672 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1673 // Comparing a pointer with null, or any other constant, isn't really a use,
1674 // because we don't care what the pointer points to, or about the values
1675 // of any other dynamic reference-counted pointers.
1676 if (!IsPotentialUse(ICI->getOperand(1)))
1677 return false;
1678 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1679 // For calls, just check the arguments (and not the callee operand).
1680 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1681 OE = CS.arg_end(); OI != OE; ++OI) {
1682 const Value *Op = *OI;
1683 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1684 return true;
1685 }
1686 return false;
1687 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1688 // Special-case stores, because we don't care about the stored value, just
1689 // the store address.
1690 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1691 // If we can't tell what the underlying object was, assume there is a
1692 // dependence.
1693 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1694 }
1695
1696 // Check each operand for a match.
1697 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1698 OI != OE; ++OI) {
1699 const Value *Op = *OI;
1700 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1701 return true;
1702 }
1703 return false;
1704}
1705
1706/// CanInterruptRV - Test whether the given instruction can autorelease
1707/// any pointer or cause an autoreleasepool pop.
1708static bool
1709CanInterruptRV(InstructionClass Class) {
1710 switch (Class) {
1711 case IC_AutoreleasepoolPop:
1712 case IC_CallOrUser:
1713 case IC_Call:
1714 case IC_Autorelease:
1715 case IC_AutoreleaseRV:
1716 case IC_FusedRetainAutorelease:
1717 case IC_FusedRetainAutoreleaseRV:
1718 return true;
1719 default:
1720 return false;
1721 }
1722}
1723
1724namespace {
1725 /// DependenceKind - There are several kinds of dependence-like concepts in
1726 /// use here.
1727 enum DependenceKind {
1728 NeedsPositiveRetainCount,
1729 CanChangeRetainCount,
1730 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1731 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1732 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1733 };
1734}
1735
1736/// Depends - Test if there can be dependencies on Inst through Arg. This
1737/// function only tests dependencies relevant for removing pairs of calls.
1738static bool
1739Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1740 ProvenanceAnalysis &PA) {
1741 // If we've reached the definition of Arg, stop.
1742 if (Inst == Arg)
1743 return true;
1744
1745 switch (Flavor) {
1746 case NeedsPositiveRetainCount: {
1747 InstructionClass Class = GetInstructionClass(Inst);
1748 switch (Class) {
1749 case IC_AutoreleasepoolPop:
1750 case IC_AutoreleasepoolPush:
1751 case IC_None:
1752 return false;
1753 default:
1754 return CanUse(Inst, Arg, PA, Class);
1755 }
1756 }
1757
1758 case CanChangeRetainCount: {
1759 InstructionClass Class = GetInstructionClass(Inst);
1760 switch (Class) {
1761 case IC_AutoreleasepoolPop:
1762 // Conservatively assume this can decrement any count.
1763 return true;
1764 case IC_AutoreleasepoolPush:
1765 case IC_None:
1766 return false;
1767 default:
1768 return CanAlterRefCount(Inst, Arg, PA, Class);
1769 }
1770 }
1771
1772 case RetainAutoreleaseDep:
1773 switch (GetBasicInstructionClass(Inst)) {
1774 case IC_AutoreleasepoolPop:
1775 // Don't merge an objc_autorelease with an objc_retain inside a different
1776 // autoreleasepool scope.
1777 return true;
1778 case IC_Retain:
1779 case IC_RetainRV:
1780 // Check for a retain of the same pointer for merging.
1781 return GetObjCArg(Inst) == Arg;
1782 default:
1783 // Nothing else matters for objc_retainAutorelease formation.
1784 return false;
1785 }
1786 break;
1787
1788 case RetainAutoreleaseRVDep: {
1789 InstructionClass Class = GetBasicInstructionClass(Inst);
1790 switch (Class) {
1791 case IC_Retain:
1792 case IC_RetainRV:
1793 // Check for a retain of the same pointer for merging.
1794 return GetObjCArg(Inst) == Arg;
1795 default:
1796 // Anything that can autorelease interrupts
1797 // retainAutoreleaseReturnValue formation.
1798 return CanInterruptRV(Class);
1799 }
1800 break;
1801 }
1802
1803 case RetainRVDep:
1804 return CanInterruptRV(GetBasicInstructionClass(Inst));
1805 }
1806
1807 llvm_unreachable("Invalid dependence flavor");
1808 return true;
1809}
1810
1811/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1812/// find local and non-local dependencies on Arg.
1813/// TODO: Cache results?
1814static void
1815FindDependencies(DependenceKind Flavor,
1816 const Value *Arg,
1817 BasicBlock *StartBB, Instruction *StartInst,
1818 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1819 SmallPtrSet<const BasicBlock *, 4> &Visited,
1820 ProvenanceAnalysis &PA) {
1821 BasicBlock::iterator StartPos = StartInst;
1822
1823 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1824 Worklist.push_back(std::make_pair(StartBB, StartPos));
1825 do {
1826 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1827 Worklist.pop_back_val();
1828 BasicBlock *LocalStartBB = Pair.first;
1829 BasicBlock::iterator LocalStartPos = Pair.second;
1830 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1831 for (;;) {
1832 if (LocalStartPos == StartBBBegin) {
1833 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1834 if (PI == PE)
1835 // If we've reached the function entry, produce a null dependence.
1836 DependingInstructions.insert(0);
1837 else
1838 // Add the predecessors to the worklist.
1839 do {
1840 BasicBlock *PredBB = *PI;
1841 if (Visited.insert(PredBB))
1842 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1843 } while (++PI != PE);
1844 break;
1845 }
1846
1847 Instruction *Inst = --LocalStartPos;
1848 if (Depends(Flavor, Inst, Arg, PA)) {
1849 DependingInstructions.insert(Inst);
1850 break;
1851 }
1852 }
1853 } while (!Worklist.empty());
1854
1855 // Determine whether the original StartBB post-dominates all of the blocks we
1856 // visited. If not, insert a sentinal indicating that most optimizations are
1857 // not safe.
1858 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1859 E = Visited.end(); I != E; ++I) {
1860 const BasicBlock *BB = *I;
1861 if (BB == StartBB)
1862 continue;
1863 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1864 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1865 const BasicBlock *Succ = *SI;
1866 if (Succ != StartBB && !Visited.count(Succ)) {
1867 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1868 return;
1869 }
1870 }
1871 }
1872}
1873
1874static bool isNullOrUndef(const Value *V) {
1875 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1876}
1877
1878static bool isNoopInstruction(const Instruction *I) {
1879 return isa<BitCastInst>(I) ||
1880 (isa<GetElementPtrInst>(I) &&
1881 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1882}
1883
1884/// OptimizeRetainCall - Turn objc_retain into
1885/// objc_retainAutoreleasedReturnValue if the operand is a return value.
1886void
1887ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1888 CallSite CS(GetObjCArg(Retain));
1889 Instruction *Call = CS.getInstruction();
1890 if (!Call) return;
1891 if (Call->getParent() != Retain->getParent()) return;
1892
1893 // Check that the call is next to the retain.
1894 BasicBlock::iterator I = Call;
1895 ++I;
1896 while (isNoopInstruction(I)) ++I;
1897 if (&*I != Retain)
1898 return;
1899
1900 // Turn it to an objc_retainAutoreleasedReturnValue..
1901 Changed = true;
1902 ++NumPeeps;
1903 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1904}
1905
1906/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1907/// objc_retain if the operand is not a return value. Or, if it can be
1908/// paired with an objc_autoreleaseReturnValue, delete the pair and
1909/// return true.
1910bool
1911ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1912 // Check for the argument being from an immediately preceding call.
1913 Value *Arg = GetObjCArg(RetainRV);
1914 CallSite CS(Arg);
1915 if (Instruction *Call = CS.getInstruction())
1916 if (Call->getParent() == RetainRV->getParent()) {
1917 BasicBlock::iterator I = Call;
1918 ++I;
1919 while (isNoopInstruction(I)) ++I;
1920 if (&*I == RetainRV)
1921 return false;
1922 }
1923
1924 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1925 // pointer. In this case, we can delete the pair.
1926 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1927 if (I != Begin) {
1928 do --I; while (I != Begin && isNoopInstruction(I));
1929 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1930 GetObjCArg(I) == Arg) {
1931 Changed = true;
1932 ++NumPeeps;
1933 EraseInstruction(I);
1934 EraseInstruction(RetainRV);
1935 return true;
1936 }
1937 }
1938
1939 // Turn it to a plain objc_retain.
1940 Changed = true;
1941 ++NumPeeps;
1942 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1943 return false;
1944}
1945
1946/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1947/// objc_autorelease if the result is not used as a return value.
1948void
1949ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1950 // Check for a return of the pointer value.
1951 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00001952 SmallVector<const Value *, 2> Users;
1953 Users.push_back(Ptr);
1954 do {
1955 Ptr = Users.pop_back_val();
1956 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1957 UI != UE; ++UI) {
1958 const User *I = *UI;
1959 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1960 return;
1961 if (isa<BitCastInst>(I))
1962 Users.push_back(I);
1963 }
1964 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00001965
1966 Changed = true;
1967 ++NumPeeps;
1968 cast<CallInst>(AutoreleaseRV)->
1969 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1970}
1971
1972/// OptimizeIndividualCalls - Visit each call, one at a time, and make
1973/// simplifications without doing any additional analysis.
1974void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1975 // Reset all the flags in preparation for recomputing them.
1976 UsedInThisFunction = 0;
1977
1978 // Visit all objc_* calls in F.
1979 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1980 Instruction *Inst = &*I++;
1981 InstructionClass Class = GetBasicInstructionClass(Inst);
1982
1983 switch (Class) {
1984 default: break;
1985
1986 // Delete no-op casts. These function calls have special semantics, but
1987 // the semantics are entirely implemented via lowering in the front-end,
1988 // so by the time they reach the optimizer, they are just no-op calls
1989 // which return their argument.
1990 //
1991 // There are gray areas here, as the ability to cast reference-counted
1992 // pointers to raw void* and back allows code to break ARC assumptions,
1993 // however these are currently considered to be unimportant.
1994 case IC_NoopCast:
1995 Changed = true;
1996 ++NumNoops;
1997 EraseInstruction(Inst);
1998 continue;
1999
2000 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2001 case IC_StoreWeak:
2002 case IC_LoadWeak:
2003 case IC_LoadWeakRetained:
2004 case IC_InitWeak:
2005 case IC_DestroyWeak: {
2006 CallInst *CI = cast<CallInst>(Inst);
2007 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002008 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002009 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2010 Constant::getNullValue(Ty),
2011 CI);
2012 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2013 CI->eraseFromParent();
2014 continue;
2015 }
2016 break;
2017 }
2018 case IC_CopyWeak:
2019 case IC_MoveWeak: {
2020 CallInst *CI = cast<CallInst>(Inst);
2021 if (isNullOrUndef(CI->getArgOperand(0)) ||
2022 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002023 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002024 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2025 Constant::getNullValue(Ty),
2026 CI);
2027 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2028 CI->eraseFromParent();
2029 continue;
2030 }
2031 break;
2032 }
2033 case IC_Retain:
2034 OptimizeRetainCall(F, Inst);
2035 break;
2036 case IC_RetainRV:
2037 if (OptimizeRetainRVCall(F, Inst))
2038 continue;
2039 break;
2040 case IC_AutoreleaseRV:
2041 OptimizeAutoreleaseRVCall(F, Inst);
2042 break;
2043 }
2044
2045 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2046 if (IsAutorelease(Class) && Inst->use_empty()) {
2047 CallInst *Call = cast<CallInst>(Inst);
2048 const Value *Arg = Call->getArgOperand(0);
2049 Arg = FindSingleUseIdentifiedObject(Arg);
2050 if (Arg) {
2051 Changed = true;
2052 ++NumAutoreleases;
2053
2054 // Create the declaration lazily.
2055 LLVMContext &C = Inst->getContext();
2056 CallInst *NewCall =
2057 CallInst::Create(getReleaseCallee(F.getParent()),
2058 Call->getArgOperand(0), "", Call);
2059 NewCall->setMetadata(ImpreciseReleaseMDKind,
2060 MDNode::get(C, ArrayRef<Value *>()));
2061 EraseInstruction(Call);
2062 Inst = NewCall;
2063 Class = IC_Release;
2064 }
2065 }
2066
2067 // For functions which can never be passed stack arguments, add
2068 // a tail keyword.
2069 if (IsAlwaysTail(Class)) {
2070 Changed = true;
2071 cast<CallInst>(Inst)->setTailCall();
2072 }
2073
2074 // Set nounwind as needed.
2075 if (IsNoThrow(Class)) {
2076 Changed = true;
2077 cast<CallInst>(Inst)->setDoesNotThrow();
2078 }
2079
2080 if (!IsNoopOnNull(Class)) {
2081 UsedInThisFunction |= 1 << Class;
2082 continue;
2083 }
2084
2085 const Value *Arg = GetObjCArg(Inst);
2086
2087 // ARC calls with null are no-ops. Delete them.
2088 if (isNullOrUndef(Arg)) {
2089 Changed = true;
2090 ++NumNoops;
2091 EraseInstruction(Inst);
2092 continue;
2093 }
2094
2095 // Keep track of which of retain, release, autorelease, and retain_block
2096 // are actually present in this function.
2097 UsedInThisFunction |= 1 << Class;
2098
2099 // If Arg is a PHI, and one or more incoming values to the
2100 // PHI are null, and the call is control-equivalent to the PHI, and there
2101 // are no relevant side effects between the PHI and the call, the call
2102 // could be pushed up to just those paths with non-null incoming values.
2103 // For now, don't bother splitting critical edges for this.
2104 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2105 Worklist.push_back(std::make_pair(Inst, Arg));
2106 do {
2107 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2108 Inst = Pair.first;
2109 Arg = Pair.second;
2110
2111 const PHINode *PN = dyn_cast<PHINode>(Arg);
2112 if (!PN) continue;
2113
2114 // Determine if the PHI has any null operands, or any incoming
2115 // critical edges.
2116 bool HasNull = false;
2117 bool HasCriticalEdges = false;
2118 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2119 Value *Incoming =
2120 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2121 if (isNullOrUndef(Incoming))
2122 HasNull = true;
2123 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2124 .getNumSuccessors() != 1) {
2125 HasCriticalEdges = true;
2126 break;
2127 }
2128 }
2129 // If we have null operands and no critical edges, optimize.
2130 if (!HasCriticalEdges && HasNull) {
2131 SmallPtrSet<Instruction *, 4> DependingInstructions;
2132 SmallPtrSet<const BasicBlock *, 4> Visited;
2133
2134 // Check that there is nothing that cares about the reference
2135 // count between the call and the phi.
2136 FindDependencies(NeedsPositiveRetainCount, Arg,
2137 Inst->getParent(), Inst,
2138 DependingInstructions, Visited, PA);
2139 if (DependingInstructions.size() == 1 &&
2140 *DependingInstructions.begin() == PN) {
2141 Changed = true;
2142 ++NumPartialNoops;
2143 // Clone the call into each predecessor that has a non-null value.
2144 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002145 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002146 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2147 Value *Incoming =
2148 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2149 if (!isNullOrUndef(Incoming)) {
2150 CallInst *Clone = cast<CallInst>(CInst->clone());
2151 Value *Op = PN->getIncomingValue(i);
2152 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2153 if (Op->getType() != ParamTy)
2154 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2155 Clone->setArgOperand(0, Op);
2156 Clone->insertBefore(InsertPos);
2157 Worklist.push_back(std::make_pair(Clone, Incoming));
2158 }
2159 }
2160 // Erase the original call.
2161 EraseInstruction(CInst);
2162 continue;
2163 }
2164 }
2165 } while (!Worklist.empty());
2166 }
2167}
2168
2169/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2170/// control flow, or other CFG structures where moving code across the edge
2171/// would result in it being executed more.
2172void
2173ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2174 DenseMap<const BasicBlock *, BBState> &BBStates,
2175 BBState &MyStates) const {
2176 // If any top-down local-use or possible-dec has a succ which is earlier in
2177 // the sequence, forget it.
2178 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2179 E = MyStates.top_down_ptr_end(); I != E; ++I)
2180 switch (I->second.GetSeq()) {
2181 default: break;
2182 case S_Use: {
2183 const Value *Arg = I->first;
2184 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2185 bool SomeSuccHasSame = false;
2186 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002187 PtrState &S = MyStates.getPtrTopDownState(Arg);
2188 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2189 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2190 switch (SuccS.GetSeq()) {
John McCall9fbd3182011-06-15 23:37:01 +00002191 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002192 case S_CanRelease: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002193 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002194 S.ClearSequenceProgress();
2195 continue;
2196 }
John McCall9fbd3182011-06-15 23:37:01 +00002197 case S_Use:
2198 SomeSuccHasSame = true;
2199 break;
2200 case S_Stop:
2201 case S_Release:
2202 case S_MovableRelease:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002203 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002204 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002205 break;
2206 case S_Retain:
2207 llvm_unreachable("bottom-up pointer in retain state!");
2208 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002209 }
John McCall9fbd3182011-06-15 23:37:01 +00002210 // If the state at the other end of any of the successor edges
2211 // matches the current state, require all edges to match. This
2212 // guards against loops in the middle of a sequence.
2213 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002214 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002215 }
2216 case S_CanRelease: {
2217 const Value *Arg = I->first;
2218 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2219 bool SomeSuccHasSame = false;
2220 bool AllSuccsHaveSame = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002221 PtrState &S = MyStates.getPtrTopDownState(Arg);
2222 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2223 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2224 switch (SuccS.GetSeq()) {
2225 case S_None: {
Dan Gohmane6d5e882011-08-19 00:26:36 +00002226 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002227 S.ClearSequenceProgress();
2228 continue;
2229 }
John McCall9fbd3182011-06-15 23:37:01 +00002230 case S_CanRelease:
2231 SomeSuccHasSame = true;
2232 break;
2233 case S_Stop:
2234 case S_Release:
2235 case S_MovableRelease:
2236 case S_Use:
Dan Gohmane6d5e882011-08-19 00:26:36 +00002237 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002238 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002239 break;
2240 case S_Retain:
2241 llvm_unreachable("bottom-up pointer in retain state!");
2242 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002243 }
John McCall9fbd3182011-06-15 23:37:01 +00002244 // If the state at the other end of any of the successor edges
2245 // matches the current state, require all edges to match. This
2246 // guards against loops in the middle of a sequence.
2247 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002248 S.ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00002249 }
2250 }
2251}
2252
2253bool
2254ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2255 DenseMap<const BasicBlock *, BBState> &BBStates,
2256 MapVector<Value *, RRInfo> &Retains) {
2257 bool NestingDetected = false;
2258 BBState &MyStates = BBStates[BB];
2259
2260 // Merge the states from each successor to compute the initial state
2261 // for the current block.
2262 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2263 succ_const_iterator SI(TI), SE(TI, false);
2264 if (SI == SE)
2265 MyStates.SetAsExit();
2266 else
2267 do {
2268 const BasicBlock *Succ = *SI++;
2269 if (Succ == BB)
2270 continue;
2271 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002272 // If we haven't seen this node yet, then we've found a CFG cycle.
2273 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002274 if (I == BBStates.end())
2275 continue;
2276 MyStates.InitFromSucc(I->second);
2277 while (SI != SE) {
2278 Succ = *SI++;
2279 if (Succ != BB) {
2280 I = BBStates.find(Succ);
2281 if (I != BBStates.end())
2282 MyStates.MergeSucc(I->second);
2283 }
2284 }
2285 break;
2286 } while (SI != SE);
2287
2288 // Visit all the instructions, bottom-up.
2289 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2290 Instruction *Inst = llvm::prior(I);
2291 InstructionClass Class = GetInstructionClass(Inst);
2292 const Value *Arg = 0;
2293
2294 switch (Class) {
2295 case IC_Release: {
2296 Arg = GetObjCArg(Inst);
2297
2298 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2299
2300 // If we see two releases in a row on the same pointer. If so, make
2301 // a note, and we'll cicle back to revisit it after we've
2302 // hopefully eliminated the second release, which may allow us to
2303 // eliminate the first release too.
2304 // Theoretically we could implement removal of nested retain+release
2305 // pairs by making PtrState hold a stack of states, but this is
2306 // simple and avoids adding overhead for the non-nested case.
2307 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2308 NestingDetected = true;
2309
2310 S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
2311 S.RRI.clear();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002312 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002313 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2314 S.RRI.Calls.insert(Inst);
2315
2316 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002317 S.IncrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002318 break;
2319 }
2320 case IC_RetainBlock:
2321 case IC_Retain:
2322 case IC_RetainRV: {
2323 Arg = GetObjCArg(Inst);
2324
2325 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2326 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002327 S.SetAtLeastOneRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002328 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002329
2330 switch (S.GetSeq()) {
2331 case S_Stop:
2332 case S_Release:
2333 case S_MovableRelease:
2334 case S_Use:
2335 S.RRI.ReverseInsertPts.clear();
2336 // FALL THROUGH
2337 case S_CanRelease:
2338 // Don't do retain+release tracking for IC_RetainRV, because it's
2339 // better to let it remain as the first instruction after a call.
2340 if (Class != IC_RetainRV) {
2341 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2342 Retains[Inst] = S.RRI;
2343 }
2344 S.ClearSequenceProgress();
2345 break;
2346 case S_None:
2347 break;
2348 case S_Retain:
2349 llvm_unreachable("bottom-up pointer in retain state!");
2350 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002351 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002352 }
2353 case IC_AutoreleasepoolPop:
2354 // Conservatively, clear MyStates for all known pointers.
2355 MyStates.clearBottomUpPointers();
2356 continue;
2357 case IC_AutoreleasepoolPush:
2358 case IC_None:
2359 // These are irrelevant.
2360 continue;
2361 default:
2362 break;
2363 }
2364
2365 // Consider any other possible effects of this instruction on each
2366 // pointer being tracked.
2367 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2368 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2369 const Value *Ptr = MI->first;
2370 if (Ptr == Arg)
2371 continue; // Handled above.
2372 PtrState &S = MI->second;
2373 Sequence Seq = S.GetSeq();
2374
Dan Gohmane6d5e882011-08-19 00:26:36 +00002375 // Check for possible releases.
2376 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2377 S.DecrementRefCount();
Dan Gohmana7f7db22011-08-12 00:26:31 +00002378 switch (Seq) {
2379 case S_Use:
2380 S.SetSeq(S_CanRelease);
2381 continue;
2382 case S_CanRelease:
2383 case S_Release:
2384 case S_MovableRelease:
2385 case S_Stop:
2386 case S_None:
2387 break;
2388 case S_Retain:
2389 llvm_unreachable("bottom-up pointer in retain state!");
2390 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002391 }
John McCall9fbd3182011-06-15 23:37:01 +00002392
2393 // Check for possible direct uses.
2394 switch (Seq) {
2395 case S_Release:
2396 case S_MovableRelease:
2397 if (CanUse(Inst, Ptr, PA, Class)) {
2398 S.RRI.ReverseInsertPts.clear();
2399 S.RRI.ReverseInsertPts.insert(Inst);
2400 S.SetSeq(S_Use);
2401 } else if (Seq == S_Release &&
2402 (Class == IC_User || Class == IC_CallOrUser)) {
2403 // Non-movable releases depend on any possible objc pointer use.
2404 S.SetSeq(S_Stop);
2405 S.RRI.ReverseInsertPts.clear();
2406 S.RRI.ReverseInsertPts.insert(Inst);
2407 }
2408 break;
2409 case S_Stop:
2410 if (CanUse(Inst, Ptr, PA, Class))
2411 S.SetSeq(S_Use);
2412 break;
2413 case S_CanRelease:
2414 case S_Use:
2415 case S_None:
2416 break;
2417 case S_Retain:
2418 llvm_unreachable("bottom-up pointer in retain state!");
2419 }
2420 }
2421 }
2422
2423 return NestingDetected;
2424}
2425
2426bool
2427ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2428 DenseMap<const BasicBlock *, BBState> &BBStates,
2429 DenseMap<Value *, RRInfo> &Releases) {
2430 bool NestingDetected = false;
2431 BBState &MyStates = BBStates[BB];
2432
2433 // Merge the states from each predecessor to compute the initial state
2434 // for the current block.
2435 const_pred_iterator PI(BB), PE(BB, false);
2436 if (PI == PE)
2437 MyStates.SetAsEntry();
2438 else
2439 do {
2440 const BasicBlock *Pred = *PI++;
2441 if (Pred == BB)
2442 continue;
2443 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002444 assert(I != BBStates.end());
2445 // If we haven't seen this node yet, then we've found a CFG cycle.
2446 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2447 if (!I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002448 continue;
2449 MyStates.InitFromPred(I->second);
2450 while (PI != PE) {
2451 Pred = *PI++;
2452 if (Pred != BB) {
2453 I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002454 assert(I != BBStates.end());
2455 if (I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002456 MyStates.MergePred(I->second);
2457 }
2458 }
2459 break;
2460 } while (PI != PE);
2461
2462 // Visit all the instructions, top-down.
2463 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2464 Instruction *Inst = I;
2465 InstructionClass Class = GetInstructionClass(Inst);
2466 const Value *Arg = 0;
2467
2468 switch (Class) {
2469 case IC_RetainBlock:
2470 case IC_Retain:
2471 case IC_RetainRV: {
2472 Arg = GetObjCArg(Inst);
2473
2474 PtrState &S = MyStates.getPtrTopDownState(Arg);
2475
2476 // Don't do retain+release tracking for IC_RetainRV, because it's
2477 // better to let it remain as the first instruction after a call.
2478 if (Class != IC_RetainRV) {
2479 // If we see two retains in a row on the same pointer. If so, make
2480 // a note, and we'll cicle back to revisit it after we've
2481 // hopefully eliminated the second retain, which may allow us to
2482 // eliminate the first retain too.
2483 // Theoretically we could implement removal of nested retain+release
2484 // pairs by making PtrState hold a stack of states, but this is
2485 // simple and avoids adding overhead for the non-nested case.
2486 if (S.GetSeq() == S_Retain)
2487 NestingDetected = true;
2488
2489 S.SetSeq(S_Retain);
2490 S.RRI.clear();
2491 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002492 // Don't check S.IsKnownIncremented() here because it's not
2493 // sufficient.
2494 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002495 S.RRI.Calls.insert(Inst);
2496 }
2497
Dan Gohmana7f7db22011-08-12 00:26:31 +00002498 S.SetAtLeastOneRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002499 S.IncrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002500 S.IncrementNestCount();
2501 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002502 }
2503 case IC_Release: {
2504 Arg = GetObjCArg(Inst);
2505
2506 PtrState &S = MyStates.getPtrTopDownState(Arg);
2507 S.DecrementRefCount();
Dan Gohmane6d5e882011-08-19 00:26:36 +00002508 S.DecrementNestCount();
John McCall9fbd3182011-06-15 23:37:01 +00002509
2510 switch (S.GetSeq()) {
2511 case S_Retain:
2512 case S_CanRelease:
2513 S.RRI.ReverseInsertPts.clear();
2514 // FALL THROUGH
2515 case S_Use:
2516 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2517 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2518 Releases[Inst] = S.RRI;
2519 S.ClearSequenceProgress();
2520 break;
2521 case S_None:
2522 break;
2523 case S_Stop:
2524 case S_Release:
2525 case S_MovableRelease:
2526 llvm_unreachable("top-down pointer in release state!");
2527 }
2528 break;
2529 }
2530 case IC_AutoreleasepoolPop:
2531 // Conservatively, clear MyStates for all known pointers.
2532 MyStates.clearTopDownPointers();
2533 continue;
2534 case IC_AutoreleasepoolPush:
2535 case IC_None:
2536 // These are irrelevant.
2537 continue;
2538 default:
2539 break;
2540 }
2541
2542 // Consider any other possible effects of this instruction on each
2543 // pointer being tracked.
2544 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2545 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2546 const Value *Ptr = MI->first;
2547 if (Ptr == Arg)
2548 continue; // Handled above.
2549 PtrState &S = MI->second;
2550 Sequence Seq = S.GetSeq();
2551
Dan Gohmane6d5e882011-08-19 00:26:36 +00002552 // Check for possible releases.
2553 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2554 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002555 switch (Seq) {
2556 case S_Retain:
2557 S.SetSeq(S_CanRelease);
2558 S.RRI.ReverseInsertPts.clear();
2559 S.RRI.ReverseInsertPts.insert(Inst);
2560
2561 // One call can't cause a transition from S_Retain to S_CanRelease
2562 // and S_CanRelease to S_Use. If we've made the first transition,
2563 // we're done.
2564 continue;
2565 case S_Use:
2566 case S_CanRelease:
2567 case S_None:
2568 break;
2569 case S_Stop:
2570 case S_Release:
2571 case S_MovableRelease:
2572 llvm_unreachable("top-down pointer in release state!");
2573 }
Dan Gohmane6d5e882011-08-19 00:26:36 +00002574 }
John McCall9fbd3182011-06-15 23:37:01 +00002575
2576 // Check for possible direct uses.
2577 switch (Seq) {
2578 case S_CanRelease:
2579 if (CanUse(Inst, Ptr, PA, Class))
2580 S.SetSeq(S_Use);
2581 break;
2582 case S_Use:
2583 case S_Retain:
2584 case S_None:
2585 break;
2586 case S_Stop:
2587 case S_Release:
2588 case S_MovableRelease:
2589 llvm_unreachable("top-down pointer in release state!");
2590 }
2591 }
2592 }
2593
2594 CheckForCFGHazards(BB, BBStates, MyStates);
2595 return NestingDetected;
2596}
2597
2598// Visit - Visit the function both top-down and bottom-up.
2599bool
2600ObjCARCOpt::Visit(Function &F,
2601 DenseMap<const BasicBlock *, BBState> &BBStates,
2602 MapVector<Value *, RRInfo> &Retains,
2603 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohmand8e48c42011-08-12 00:24:29 +00002604 // Use reverse-postorder on the reverse CFG for bottom-up, because we
John McCall9fbd3182011-06-15 23:37:01 +00002605 // magically know that loops will be well behaved, i.e. they won't repeatedly
Dan Gohmand8e48c42011-08-12 00:24:29 +00002606 // call retain on a single pointer without doing a release. We can't use
2607 // ReversePostOrderTraversal here because we want to walk up from each
2608 // function exit point.
2609 SmallPtrSet<BasicBlock *, 16> Visited;
2610 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> Stack;
2611 SmallVector<BasicBlock *, 16> Order;
2612 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2613 BasicBlock *BB = I;
2614 if (BB->getTerminator()->getNumSuccessors() == 0)
2615 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2616 }
2617 while (!Stack.empty()) {
2618 pred_iterator End = pred_end(Stack.back().first);
2619 while (Stack.back().second != End) {
2620 BasicBlock *BB = *Stack.back().second++;
2621 if (Visited.insert(BB))
2622 Stack.push_back(std::make_pair(BB, pred_begin(BB)));
2623 }
2624 Order.push_back(Stack.pop_back_val().first);
2625 }
John McCall9fbd3182011-06-15 23:37:01 +00002626 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00002627 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2628 Order.rbegin(), E = Order.rend(); I != E; ++I) {
2629 BasicBlock *BB = *I;
John McCall9fbd3182011-06-15 23:37:01 +00002630 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2631 }
2632
Dan Gohmand8e48c42011-08-12 00:24:29 +00002633 // Use regular reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00002634 bool TopDownNestingDetected = false;
Dan Gohmand8e48c42011-08-12 00:24:29 +00002635 typedef ReversePostOrderTraversal<Function *> RPOTType;
2636 RPOTType RPOT(&F);
2637 for (RPOTType::rpo_iterator I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
2638 BasicBlock *BB = *I;
2639 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
2640 }
John McCall9fbd3182011-06-15 23:37:01 +00002641
2642 return TopDownNestingDetected && BottomUpNestingDetected;
2643}
2644
2645/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2646void ObjCARCOpt::MoveCalls(Value *Arg,
2647 RRInfo &RetainsToMove,
2648 RRInfo &ReleasesToMove,
2649 MapVector<Value *, RRInfo> &Retains,
2650 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00002651 SmallVectorImpl<Instruction *> &DeadInsts,
2652 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002653 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00002654 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00002655
2656 // Insert the new retain and release calls.
2657 for (SmallPtrSet<Instruction *, 2>::const_iterator
2658 PI = ReleasesToMove.ReverseInsertPts.begin(),
2659 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2660 Instruction *InsertPt = *PI;
2661 Value *MyArg = ArgTy == ParamTy ? Arg :
2662 new BitCastInst(Arg, ParamTy, "", InsertPt);
2663 CallInst *Call =
2664 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00002665 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00002666 MyArg, "", InsertPt);
2667 Call->setDoesNotThrow();
2668 if (!RetainsToMove.IsRetainBlock)
2669 Call->setTailCall();
2670 }
2671 for (SmallPtrSet<Instruction *, 2>::const_iterator
2672 PI = RetainsToMove.ReverseInsertPts.begin(),
2673 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00002674 Instruction *LastUse = *PI;
2675 Instruction *InsertPts[] = { 0, 0, 0 };
2676 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2677 // We can't insert code immediately after an invoke instruction, so
2678 // insert code at the beginning of both successor blocks instead.
2679 // The invoke's return value isn't available in the unwind block,
2680 // but our releases will never depend on it, because they must be
2681 // paired with retains from before the invoke.
2682 InsertPts[0] = II->getNormalDest()->getFirstNonPHI();
2683 InsertPts[1] = II->getUnwindDest()->getFirstNonPHI();
2684 } else {
2685 // Insert code immediately after the last use.
2686 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2687 }
2688
2689 for (Instruction **I = InsertPts; *I; ++I) {
2690 Instruction *InsertPt = *I;
2691 Value *MyArg = ArgTy == ParamTy ? Arg :
2692 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00002693 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2694 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00002695 // Attach a clang.imprecise_release metadata tag, if appropriate.
2696 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2697 Call->setMetadata(ImpreciseReleaseMDKind, M);
2698 Call->setDoesNotThrow();
2699 if (ReleasesToMove.IsTailCallRelease)
2700 Call->setTailCall();
2701 }
John McCall9fbd3182011-06-15 23:37:01 +00002702 }
2703
2704 // Delete the original retain and release calls.
2705 for (SmallPtrSet<Instruction *, 2>::const_iterator
2706 AI = RetainsToMove.Calls.begin(),
2707 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2708 Instruction *OrigRetain = *AI;
2709 Retains.blot(OrigRetain);
2710 DeadInsts.push_back(OrigRetain);
2711 }
2712 for (SmallPtrSet<Instruction *, 2>::const_iterator
2713 AI = ReleasesToMove.Calls.begin(),
2714 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2715 Instruction *OrigRelease = *AI;
2716 Releases.erase(OrigRelease);
2717 DeadInsts.push_back(OrigRelease);
2718 }
2719}
2720
2721bool
2722ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2723 &BBStates,
2724 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00002725 DenseMap<Value *, RRInfo> &Releases,
2726 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00002727 bool AnyPairsCompletelyEliminated = false;
2728 RRInfo RetainsToMove;
2729 RRInfo ReleasesToMove;
2730 SmallVector<Instruction *, 4> NewRetains;
2731 SmallVector<Instruction *, 4> NewReleases;
2732 SmallVector<Instruction *, 8> DeadInsts;
2733
2734 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2735 E = Retains.end(); I != E; ) {
2736 Value *V = (I++)->first;
2737 if (!V) continue; // blotted
2738
2739 Instruction *Retain = cast<Instruction>(V);
2740 Value *Arg = GetObjCArg(Retain);
2741
2742 // If the object being released is in static or stack storage, we know it's
2743 // not being managed by ObjC reference counting, so we can delete pairs
2744 // regardless of what possible decrements or uses lie between them.
2745 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2746
2747 // If a pair happens in a region where it is known that the reference count
2748 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00002749 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00002750
2751 // Connect the dots between the top-down-collected RetainsToMove and
2752 // bottom-up-collected ReleasesToMove to form sets of related calls.
2753 // This is an iterative process so that we connect multiple releases
2754 // to multiple retains if needed.
2755 unsigned OldDelta = 0;
2756 unsigned NewDelta = 0;
2757 unsigned OldCount = 0;
2758 unsigned NewCount = 0;
2759 bool FirstRelease = true;
2760 bool FirstRetain = true;
2761 NewRetains.push_back(Retain);
2762 for (;;) {
2763 for (SmallVectorImpl<Instruction *>::const_iterator
2764 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2765 Instruction *NewRetain = *NI;
2766 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2767 assert(It != Retains.end());
2768 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002769 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002770 for (SmallPtrSet<Instruction *, 2>::const_iterator
2771 LI = NewRetainRRI.Calls.begin(),
2772 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2773 Instruction *NewRetainRelease = *LI;
2774 DenseMap<Value *, RRInfo>::const_iterator Jt =
2775 Releases.find(NewRetainRelease);
2776 if (Jt == Releases.end())
2777 goto next_retain;
2778 const RRInfo &NewRetainReleaseRRI = Jt->second;
2779 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2780 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2781 OldDelta -=
2782 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2783
2784 // Merge the ReleaseMetadata and IsTailCallRelease values.
2785 if (FirstRelease) {
2786 ReleasesToMove.ReleaseMetadata =
2787 NewRetainReleaseRRI.ReleaseMetadata;
2788 ReleasesToMove.IsTailCallRelease =
2789 NewRetainReleaseRRI.IsTailCallRelease;
2790 FirstRelease = false;
2791 } else {
2792 if (ReleasesToMove.ReleaseMetadata !=
2793 NewRetainReleaseRRI.ReleaseMetadata)
2794 ReleasesToMove.ReleaseMetadata = 0;
2795 if (ReleasesToMove.IsTailCallRelease !=
2796 NewRetainReleaseRRI.IsTailCallRelease)
2797 ReleasesToMove.IsTailCallRelease = false;
2798 }
2799
2800 // Collect the optimal insertion points.
2801 if (!KnownSafe)
2802 for (SmallPtrSet<Instruction *, 2>::const_iterator
2803 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2804 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2805 RI != RE; ++RI) {
2806 Instruction *RIP = *RI;
2807 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2808 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2809 }
2810 NewReleases.push_back(NewRetainRelease);
2811 }
2812 }
2813 }
2814 NewRetains.clear();
2815 if (NewReleases.empty()) break;
2816
2817 // Back the other way.
2818 for (SmallVectorImpl<Instruction *>::const_iterator
2819 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2820 Instruction *NewRelease = *NI;
2821 DenseMap<Value *, RRInfo>::const_iterator It =
2822 Releases.find(NewRelease);
2823 assert(It != Releases.end());
2824 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00002825 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00002826 for (SmallPtrSet<Instruction *, 2>::const_iterator
2827 LI = NewReleaseRRI.Calls.begin(),
2828 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2829 Instruction *NewReleaseRetain = *LI;
2830 MapVector<Value *, RRInfo>::const_iterator Jt =
2831 Retains.find(NewReleaseRetain);
2832 if (Jt == Retains.end())
2833 goto next_retain;
2834 const RRInfo &NewReleaseRetainRRI = Jt->second;
2835 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2836 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2837 unsigned PathCount =
2838 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2839 OldDelta += PathCount;
2840 OldCount += PathCount;
2841
2842 // Merge the IsRetainBlock values.
2843 if (FirstRetain) {
2844 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2845 FirstRetain = false;
2846 } else if (ReleasesToMove.IsRetainBlock !=
2847 NewReleaseRetainRRI.IsRetainBlock)
2848 // It's not possible to merge the sequences if one uses
2849 // objc_retain and the other uses objc_retainBlock.
2850 goto next_retain;
2851
2852 // Collect the optimal insertion points.
2853 if (!KnownSafe)
2854 for (SmallPtrSet<Instruction *, 2>::const_iterator
2855 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2856 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2857 RI != RE; ++RI) {
2858 Instruction *RIP = *RI;
2859 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2860 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2861 NewDelta += PathCount;
2862 NewCount += PathCount;
2863 }
2864 }
2865 NewRetains.push_back(NewReleaseRetain);
2866 }
2867 }
2868 }
2869 NewReleases.clear();
2870 if (NewRetains.empty()) break;
2871 }
2872
Dan Gohmane6d5e882011-08-19 00:26:36 +00002873 // If the pointer is known incremented or nested, we can safely delete the
2874 // pair regardless of what's between them.
2875 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00002876 RetainsToMove.ReverseInsertPts.clear();
2877 ReleasesToMove.ReverseInsertPts.clear();
2878 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00002879 } else {
2880 // Determine whether the new insertion points we computed preserve the
2881 // balance of retain and release calls through the program.
2882 // TODO: If the fully aggressive solution isn't valid, try to find a
2883 // less aggressive solution which is.
2884 if (NewDelta != 0)
2885 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00002886 }
2887
2888 // Determine whether the original call points are balanced in the retain and
2889 // release calls through the program. If not, conservatively don't touch
2890 // them.
2891 // TODO: It's theoretically possible to do code motion in this case, as
2892 // long as the existing imbalances are maintained.
2893 if (OldDelta != 0)
2894 goto next_retain;
2895
John McCall9fbd3182011-06-15 23:37:01 +00002896 // Ok, everything checks out and we're all set. Let's move some code!
2897 Changed = true;
2898 AnyPairsCompletelyEliminated = NewCount == 0;
2899 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00002900 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2901 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00002902
2903 next_retain:
2904 NewReleases.clear();
2905 NewRetains.clear();
2906 RetainsToMove.clear();
2907 ReleasesToMove.clear();
2908 }
2909
2910 // Now that we're done moving everything, we can delete the newly dead
2911 // instructions, as we no longer need them as insert points.
2912 while (!DeadInsts.empty())
2913 EraseInstruction(DeadInsts.pop_back_val());
2914
2915 return AnyPairsCompletelyEliminated;
2916}
2917
2918/// OptimizeWeakCalls - Weak pointer optimizations.
2919void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2920 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2921 // itself because it uses AliasAnalysis and we need to do provenance
2922 // queries instead.
2923 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2924 Instruction *Inst = &*I++;
2925 InstructionClass Class = GetBasicInstructionClass(Inst);
2926 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2927 continue;
2928
2929 // Delete objc_loadWeak calls with no users.
2930 if (Class == IC_LoadWeak && Inst->use_empty()) {
2931 Inst->eraseFromParent();
2932 continue;
2933 }
2934
2935 // TODO: For now, just look for an earlier available version of this value
2936 // within the same block. Theoretically, we could do memdep-style non-local
2937 // analysis too, but that would want caching. A better approach would be to
2938 // use the technique that EarlyCSE uses.
2939 inst_iterator Current = llvm::prior(I);
2940 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2941 for (BasicBlock::iterator B = CurrentBB->begin(),
2942 J = Current.getInstructionIterator();
2943 J != B; --J) {
2944 Instruction *EarlierInst = &*llvm::prior(J);
2945 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2946 switch (EarlierClass) {
2947 case IC_LoadWeak:
2948 case IC_LoadWeakRetained: {
2949 // If this is loading from the same pointer, replace this load's value
2950 // with that one.
2951 CallInst *Call = cast<CallInst>(Inst);
2952 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2953 Value *Arg = Call->getArgOperand(0);
2954 Value *EarlierArg = EarlierCall->getArgOperand(0);
2955 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2956 case AliasAnalysis::MustAlias:
2957 Changed = true;
2958 // If the load has a builtin retain, insert a plain retain for it.
2959 if (Class == IC_LoadWeakRetained) {
2960 CallInst *CI =
2961 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2962 "", Call);
2963 CI->setTailCall();
2964 }
2965 // Zap the fully redundant load.
2966 Call->replaceAllUsesWith(EarlierCall);
2967 Call->eraseFromParent();
2968 goto clobbered;
2969 case AliasAnalysis::MayAlias:
2970 case AliasAnalysis::PartialAlias:
2971 goto clobbered;
2972 case AliasAnalysis::NoAlias:
2973 break;
2974 }
2975 break;
2976 }
2977 case IC_StoreWeak:
2978 case IC_InitWeak: {
2979 // If this is storing to the same pointer and has the same size etc.
2980 // replace this load's value with the stored value.
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->getArgOperand(1));
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_MoveWeak:
3008 case IC_CopyWeak:
3009 // TOOD: Grab the copied value.
3010 goto clobbered;
3011 case IC_AutoreleasepoolPush:
3012 case IC_None:
3013 case IC_User:
3014 // Weak pointers are only modified through the weak entry points
3015 // (and arbitrary calls, which could call the weak entry points).
3016 break;
3017 default:
3018 // Anything else could modify the weak pointer.
3019 goto clobbered;
3020 }
3021 }
3022 clobbered:;
3023 }
3024
3025 // Then, for each destroyWeak with an alloca operand, check to see if
3026 // the alloca and all its users can be zapped.
3027 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3028 Instruction *Inst = &*I++;
3029 InstructionClass Class = GetBasicInstructionClass(Inst);
3030 if (Class != IC_DestroyWeak)
3031 continue;
3032
3033 CallInst *Call = cast<CallInst>(Inst);
3034 Value *Arg = Call->getArgOperand(0);
3035 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3036 for (Value::use_iterator UI = Alloca->use_begin(),
3037 UE = Alloca->use_end(); UI != UE; ++UI) {
3038 Instruction *UserInst = cast<Instruction>(*UI);
3039 switch (GetBasicInstructionClass(UserInst)) {
3040 case IC_InitWeak:
3041 case IC_StoreWeak:
3042 case IC_DestroyWeak:
3043 continue;
3044 default:
3045 goto done;
3046 }
3047 }
3048 Changed = true;
3049 for (Value::use_iterator UI = Alloca->use_begin(),
3050 UE = Alloca->use_end(); UI != UE; ) {
3051 CallInst *UserInst = cast<CallInst>(*UI++);
3052 if (!UserInst->use_empty())
3053 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
3054 UserInst->eraseFromParent();
3055 }
3056 Alloca->eraseFromParent();
3057 done:;
3058 }
3059 }
3060}
3061
3062/// OptimizeSequences - Identify program paths which execute sequences of
3063/// retains and releases which can be eliminated.
3064bool ObjCARCOpt::OptimizeSequences(Function &F) {
3065 /// Releases, Retains - These are used to store the results of the main flow
3066 /// analysis. These use Value* as the key instead of Instruction* so that the
3067 /// map stays valid when we get around to rewriting code and calls get
3068 /// replaced by arguments.
3069 DenseMap<Value *, RRInfo> Releases;
3070 MapVector<Value *, RRInfo> Retains;
3071
3072 /// BBStates, This is used during the traversal of the function to track the
3073 /// states for each identified object at each block.
3074 DenseMap<const BasicBlock *, BBState> BBStates;
3075
3076 // Analyze the CFG of the function, and all instructions.
3077 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3078
3079 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003080 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3081 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003082}
3083
3084/// OptimizeReturns - Look for this pattern:
3085///
3086/// %call = call i8* @something(...)
3087/// %2 = call i8* @objc_retain(i8* %call)
3088/// %3 = call i8* @objc_autorelease(i8* %2)
3089/// ret i8* %3
3090///
3091/// And delete the retain and autorelease.
3092///
3093/// Otherwise if it's just this:
3094///
3095/// %3 = call i8* @objc_autorelease(i8* %2)
3096/// ret i8* %3
3097///
3098/// convert the autorelease to autoreleaseRV.
3099void ObjCARCOpt::OptimizeReturns(Function &F) {
3100 if (!F.getReturnType()->isPointerTy())
3101 return;
3102
3103 SmallPtrSet<Instruction *, 4> DependingInstructions;
3104 SmallPtrSet<const BasicBlock *, 4> Visited;
3105 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3106 BasicBlock *BB = FI;
3107 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3108 if (!Ret) continue;
3109
3110 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3111 FindDependencies(NeedsPositiveRetainCount, Arg,
3112 BB, Ret, DependingInstructions, Visited, PA);
3113 if (DependingInstructions.size() != 1)
3114 goto next_block;
3115
3116 {
3117 CallInst *Autorelease =
3118 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3119 if (!Autorelease)
3120 goto next_block;
3121 InstructionClass AutoreleaseClass =
3122 GetBasicInstructionClass(Autorelease);
3123 if (!IsAutorelease(AutoreleaseClass))
3124 goto next_block;
3125 if (GetObjCArg(Autorelease) != Arg)
3126 goto next_block;
3127
3128 DependingInstructions.clear();
3129 Visited.clear();
3130
3131 // Check that there is nothing that can affect the reference
3132 // count between the autorelease and the retain.
3133 FindDependencies(CanChangeRetainCount, Arg,
3134 BB, Autorelease, DependingInstructions, Visited, PA);
3135 if (DependingInstructions.size() != 1)
3136 goto next_block;
3137
3138 {
3139 CallInst *Retain =
3140 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3141
3142 // Check that we found a retain with the same argument.
3143 if (!Retain ||
3144 !IsRetain(GetBasicInstructionClass(Retain)) ||
3145 GetObjCArg(Retain) != Arg)
3146 goto next_block;
3147
3148 DependingInstructions.clear();
3149 Visited.clear();
3150
3151 // Convert the autorelease to an autoreleaseRV, since it's
3152 // returning the value.
3153 if (AutoreleaseClass == IC_Autorelease) {
3154 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3155 AutoreleaseClass = IC_AutoreleaseRV;
3156 }
3157
3158 // Check that there is nothing that can affect the reference
3159 // count between the retain and the call.
3160 FindDependencies(CanChangeRetainCount, Arg, BB, Retain,
3161 DependingInstructions, Visited, PA);
3162 if (DependingInstructions.size() != 1)
3163 goto next_block;
3164
3165 {
3166 CallInst *Call =
3167 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3168
3169 // Check that the pointer is the return value of the call.
3170 if (!Call || Arg != Call)
3171 goto next_block;
3172
3173 // Check that the call is a regular call.
3174 InstructionClass Class = GetBasicInstructionClass(Call);
3175 if (Class != IC_CallOrUser && Class != IC_Call)
3176 goto next_block;
3177
3178 // If so, we can zap the retain and autorelease.
3179 Changed = true;
3180 ++NumRets;
3181 EraseInstruction(Retain);
3182 EraseInstruction(Autorelease);
3183 }
3184 }
3185 }
3186
3187 next_block:
3188 DependingInstructions.clear();
3189 Visited.clear();
3190 }
3191}
3192
3193bool ObjCARCOpt::doInitialization(Module &M) {
3194 if (!EnableARCOpts)
3195 return false;
3196
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003197 Run = ModuleHasARC(M);
3198 if (!Run)
3199 return false;
3200
John McCall9fbd3182011-06-15 23:37:01 +00003201 // Identify the imprecise release metadata kind.
3202 ImpreciseReleaseMDKind =
3203 M.getContext().getMDKindID("clang.imprecise_release");
3204
John McCall9fbd3182011-06-15 23:37:01 +00003205 // Intuitively, objc_retain and others are nocapture, however in practice
3206 // they are not, because they return their argument value. And objc_release
3207 // calls finalizers.
3208
3209 // These are initialized lazily.
3210 RetainRVCallee = 0;
3211 AutoreleaseRVCallee = 0;
3212 ReleaseCallee = 0;
3213 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003214 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003215 AutoreleaseCallee = 0;
3216
3217 return false;
3218}
3219
3220bool ObjCARCOpt::runOnFunction(Function &F) {
3221 if (!EnableARCOpts)
3222 return false;
3223
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003224 // If nothing in the Module uses ARC, don't do anything.
3225 if (!Run)
3226 return false;
3227
John McCall9fbd3182011-06-15 23:37:01 +00003228 Changed = false;
3229
3230 PA.setAA(&getAnalysis<AliasAnalysis>());
3231
3232 // This pass performs several distinct transformations. As a compile-time aid
3233 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3234 // library functions aren't declared.
3235
3236 // Preliminary optimizations. This also computs UsedInThisFunction.
3237 OptimizeIndividualCalls(F);
3238
3239 // Optimizations for weak pointers.
3240 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3241 (1 << IC_LoadWeakRetained) |
3242 (1 << IC_StoreWeak) |
3243 (1 << IC_InitWeak) |
3244 (1 << IC_CopyWeak) |
3245 (1 << IC_MoveWeak) |
3246 (1 << IC_DestroyWeak)))
3247 OptimizeWeakCalls(F);
3248
3249 // Optimizations for retain+release pairs.
3250 if (UsedInThisFunction & ((1 << IC_Retain) |
3251 (1 << IC_RetainRV) |
3252 (1 << IC_RetainBlock)))
3253 if (UsedInThisFunction & (1 << IC_Release))
3254 // Run OptimizeSequences until it either stops making changes or
3255 // no retain+release pair nesting is detected.
3256 while (OptimizeSequences(F)) {}
3257
3258 // Optimizations if objc_autorelease is used.
3259 if (UsedInThisFunction &
3260 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3261 OptimizeReturns(F);
3262
3263 return Changed;
3264}
3265
3266void ObjCARCOpt::releaseMemory() {
3267 PA.clear();
3268}
3269
3270//===----------------------------------------------------------------------===//
3271// ARC contraction.
3272//===----------------------------------------------------------------------===//
3273
3274// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3275// dominated by single calls.
3276
3277#include "llvm/Operator.h"
3278#include "llvm/InlineAsm.h"
3279#include "llvm/Analysis/Dominators.h"
3280
3281STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3282
3283namespace {
3284 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3285 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3286 class ObjCARCContract : public FunctionPass {
3287 bool Changed;
3288 AliasAnalysis *AA;
3289 DominatorTree *DT;
3290 ProvenanceAnalysis PA;
3291
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003292 /// Run - A flag indicating whether this optimization pass should run.
3293 bool Run;
3294
John McCall9fbd3182011-06-15 23:37:01 +00003295 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3296 /// functions, for use in creating calls to them. These are initialized
3297 /// lazily to avoid cluttering up the Module with unused declarations.
3298 Constant *StoreStrongCallee,
3299 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3300
3301 /// RetainRVMarker - The inline asm string to insert between calls and
3302 /// RetainRV calls to make the optimization work on targets which need it.
3303 const MDString *RetainRVMarker;
3304
3305 Constant *getStoreStrongCallee(Module *M);
3306 Constant *getRetainAutoreleaseCallee(Module *M);
3307 Constant *getRetainAutoreleaseRVCallee(Module *M);
3308
3309 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3310 InstructionClass Class,
3311 SmallPtrSet<Instruction *, 4>
3312 &DependingInstructions,
3313 SmallPtrSet<const BasicBlock *, 4>
3314 &Visited);
3315
3316 void ContractRelease(Instruction *Release,
3317 inst_iterator &Iter);
3318
3319 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3320 virtual bool doInitialization(Module &M);
3321 virtual bool runOnFunction(Function &F);
3322
3323 public:
3324 static char ID;
3325 ObjCARCContract() : FunctionPass(ID) {
3326 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3327 }
3328 };
3329}
3330
3331char ObjCARCContract::ID = 0;
3332INITIALIZE_PASS_BEGIN(ObjCARCContract,
3333 "objc-arc-contract", "ObjC ARC contraction", false, false)
3334INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3335INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3336INITIALIZE_PASS_END(ObjCARCContract,
3337 "objc-arc-contract", "ObjC ARC contraction", false, false)
3338
3339Pass *llvm::createObjCARCContractPass() {
3340 return new ObjCARCContract();
3341}
3342
3343void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3344 AU.addRequired<AliasAnalysis>();
3345 AU.addRequired<DominatorTree>();
3346 AU.setPreservesCFG();
3347}
3348
3349Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3350 if (!StoreStrongCallee) {
3351 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003352 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3353 Type *I8XX = PointerType::getUnqual(I8X);
3354 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003355 Params.push_back(I8XX);
3356 Params.push_back(I8X);
3357
3358 AttrListPtr Attributes;
3359 Attributes.addAttr(~0u, Attribute::NoUnwind);
3360 Attributes.addAttr(1, Attribute::NoCapture);
3361
3362 StoreStrongCallee =
3363 M->getOrInsertFunction(
3364 "objc_storeStrong",
3365 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3366 Attributes);
3367 }
3368 return StoreStrongCallee;
3369}
3370
3371Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3372 if (!RetainAutoreleaseCallee) {
3373 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003374 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3375 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003376 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003377 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003378 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3379 AttrListPtr Attributes;
3380 Attributes.addAttr(~0u, Attribute::NoUnwind);
3381 RetainAutoreleaseCallee =
3382 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3383 }
3384 return RetainAutoreleaseCallee;
3385}
3386
3387Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3388 if (!RetainAutoreleaseRVCallee) {
3389 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003390 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3391 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003392 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003393 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003394 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3395 AttrListPtr Attributes;
3396 Attributes.addAttr(~0u, Attribute::NoUnwind);
3397 RetainAutoreleaseRVCallee =
3398 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3399 Attributes);
3400 }
3401 return RetainAutoreleaseRVCallee;
3402}
3403
3404/// ContractAutorelease - Merge an autorelease with a retain into a fused
3405/// call.
3406bool
3407ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3408 InstructionClass Class,
3409 SmallPtrSet<Instruction *, 4>
3410 &DependingInstructions,
3411 SmallPtrSet<const BasicBlock *, 4>
3412 &Visited) {
3413 const Value *Arg = GetObjCArg(Autorelease);
3414
3415 // Check that there are no instructions between the retain and the autorelease
3416 // (such as an autorelease_pop) which may change the count.
3417 CallInst *Retain = 0;
3418 if (Class == IC_AutoreleaseRV)
3419 FindDependencies(RetainAutoreleaseRVDep, Arg,
3420 Autorelease->getParent(), Autorelease,
3421 DependingInstructions, Visited, PA);
3422 else
3423 FindDependencies(RetainAutoreleaseDep, Arg,
3424 Autorelease->getParent(), Autorelease,
3425 DependingInstructions, Visited, PA);
3426
3427 Visited.clear();
3428 if (DependingInstructions.size() != 1) {
3429 DependingInstructions.clear();
3430 return false;
3431 }
3432
3433 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3434 DependingInstructions.clear();
3435
3436 if (!Retain ||
3437 GetBasicInstructionClass(Retain) != IC_Retain ||
3438 GetObjCArg(Retain) != Arg)
3439 return false;
3440
3441 Changed = true;
3442 ++NumPeeps;
3443
3444 if (Class == IC_AutoreleaseRV)
3445 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3446 else
3447 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3448
3449 EraseInstruction(Autorelease);
3450 return true;
3451}
3452
3453/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3454/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3455/// the instructions don't always appear in order, and there may be unrelated
3456/// intervening instructions.
3457void ObjCARCContract::ContractRelease(Instruction *Release,
3458 inst_iterator &Iter) {
3459 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3460 if (!Load || Load->isVolatile()) return;
3461
3462 // For now, require everything to be in one basic block.
3463 BasicBlock *BB = Release->getParent();
3464 if (Load->getParent() != BB) return;
3465
3466 // Walk down to find the store.
3467 BasicBlock::iterator I = Load, End = BB->end();
3468 ++I;
3469 AliasAnalysis::Location Loc = AA->getLocation(Load);
3470 while (I != End &&
3471 (&*I == Release ||
3472 IsRetain(GetBasicInstructionClass(I)) ||
3473 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3474 ++I;
3475 StoreInst *Store = dyn_cast<StoreInst>(I);
3476 if (!Store || Store->isVolatile()) return;
3477 if (Store->getPointerOperand() != Loc.Ptr) return;
3478
3479 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3480
3481 // Walk up to find the retain.
3482 I = Store;
3483 BasicBlock::iterator Begin = BB->begin();
3484 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3485 --I;
3486 Instruction *Retain = I;
3487 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3488 if (GetObjCArg(Retain) != New) return;
3489
3490 Changed = true;
3491 ++NumStoreStrongs;
3492
3493 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003494 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3495 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003496
3497 Value *Args[] = { Load->getPointerOperand(), New };
3498 if (Args[0]->getType() != I8XX)
3499 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3500 if (Args[1]->getType() != I8X)
3501 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3502 CallInst *StoreStrong =
3503 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003504 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003505 StoreStrong->setDoesNotThrow();
3506 StoreStrong->setDebugLoc(Store->getDebugLoc());
3507
3508 if (&*Iter == Store) ++Iter;
3509 Store->eraseFromParent();
3510 Release->eraseFromParent();
3511 EraseInstruction(Retain);
3512 if (Load->use_empty())
3513 Load->eraseFromParent();
3514}
3515
3516bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003517 Run = ModuleHasARC(M);
3518 if (!Run)
3519 return false;
3520
John McCall9fbd3182011-06-15 23:37:01 +00003521 // These are initialized lazily.
3522 StoreStrongCallee = 0;
3523 RetainAutoreleaseCallee = 0;
3524 RetainAutoreleaseRVCallee = 0;
3525
3526 // Initialize RetainRVMarker.
3527 RetainRVMarker = 0;
3528 if (NamedMDNode *NMD =
3529 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3530 if (NMD->getNumOperands() == 1) {
3531 const MDNode *N = NMD->getOperand(0);
3532 if (N->getNumOperands() == 1)
3533 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3534 RetainRVMarker = S;
3535 }
3536
3537 return false;
3538}
3539
3540bool ObjCARCContract::runOnFunction(Function &F) {
3541 if (!EnableARCOpts)
3542 return false;
3543
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003544 // If nothing in the Module uses ARC, don't do anything.
3545 if (!Run)
3546 return false;
3547
John McCall9fbd3182011-06-15 23:37:01 +00003548 Changed = false;
3549 AA = &getAnalysis<AliasAnalysis>();
3550 DT = &getAnalysis<DominatorTree>();
3551
3552 PA.setAA(&getAnalysis<AliasAnalysis>());
3553
3554 // For ObjC library calls which return their argument, replace uses of the
3555 // argument with uses of the call return value, if it dominates the use. This
3556 // reduces register pressure.
3557 SmallPtrSet<Instruction *, 4> DependingInstructions;
3558 SmallPtrSet<const BasicBlock *, 4> Visited;
3559 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3560 Instruction *Inst = &*I++;
3561
3562 // Only these library routines return their argument. In particular,
3563 // objc_retainBlock does not necessarily return its argument.
3564 InstructionClass Class = GetBasicInstructionClass(Inst);
3565 switch (Class) {
3566 case IC_Retain:
3567 case IC_FusedRetainAutorelease:
3568 case IC_FusedRetainAutoreleaseRV:
3569 break;
3570 case IC_Autorelease:
3571 case IC_AutoreleaseRV:
3572 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3573 continue;
3574 break;
3575 case IC_RetainRV: {
3576 // If we're compiling for a target which needs a special inline-asm
3577 // marker to do the retainAutoreleasedReturnValue optimization,
3578 // insert it now.
3579 if (!RetainRVMarker)
3580 break;
3581 BasicBlock::iterator BBI = Inst;
3582 --BBI;
3583 while (isNoopInstruction(BBI)) --BBI;
3584 if (&*BBI == GetObjCArg(Inst)) {
3585 InlineAsm *IA =
3586 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3587 /*isVarArg=*/false),
3588 RetainRVMarker->getString(),
3589 /*Constraints=*/"", /*hasSideEffects=*/true);
3590 CallInst::Create(IA, "", Inst);
3591 }
3592 break;
3593 }
3594 case IC_InitWeak: {
3595 // objc_initWeak(p, null) => *p = null
3596 CallInst *CI = cast<CallInst>(Inst);
3597 if (isNullOrUndef(CI->getArgOperand(1))) {
3598 Value *Null =
3599 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3600 Changed = true;
3601 new StoreInst(Null, CI->getArgOperand(0), CI);
3602 CI->replaceAllUsesWith(Null);
3603 CI->eraseFromParent();
3604 }
3605 continue;
3606 }
3607 case IC_Release:
3608 ContractRelease(Inst, I);
3609 continue;
3610 default:
3611 continue;
3612 }
3613
3614 // Don't use GetObjCArg because we don't want to look through bitcasts
3615 // and such; to do the replacement, the argument must have type i8*.
3616 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3617 for (;;) {
3618 // If we're compiling bugpointed code, don't get in trouble.
3619 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3620 break;
3621 // Look through the uses of the pointer.
3622 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3623 UI != UE; ) {
3624 Use &U = UI.getUse();
3625 unsigned OperandNo = UI.getOperandNo();
3626 ++UI; // Increment UI now, because we may unlink its element.
3627 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3628 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3629 Changed = true;
3630 Instruction *Replacement = Inst;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003631 Type *UseTy = U.get()->getType();
John McCall9fbd3182011-06-15 23:37:01 +00003632 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3633 // For PHI nodes, insert the bitcast in the predecessor block.
3634 unsigned ValNo =
3635 PHINode::getIncomingValueNumForOperand(OperandNo);
3636 BasicBlock *BB =
3637 PHI->getIncomingBlock(ValNo);
3638 if (Replacement->getType() != UseTy)
3639 Replacement = new BitCastInst(Replacement, UseTy, "",
3640 &BB->back());
3641 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3642 i != e; ++i)
3643 if (PHI->getIncomingBlock(i) == BB) {
3644 // Keep the UI iterator valid.
3645 if (&PHI->getOperandUse(
3646 PHINode::getOperandNumForIncomingValue(i)) ==
3647 &UI.getUse())
3648 ++UI;
3649 PHI->setIncomingValue(i, Replacement);
3650 }
3651 } else {
3652 if (Replacement->getType() != UseTy)
3653 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3654 U.set(Replacement);
3655 }
3656 }
3657 }
3658
3659 // If Arg is a no-op casted pointer, strip one level of casts and
3660 // iterate.
3661 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3662 Arg = BI->getOperand(0);
3663 else if (isa<GEPOperator>(Arg) &&
3664 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3665 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3666 else if (isa<GlobalAlias>(Arg) &&
3667 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3668 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3669 else
3670 break;
3671 }
3672 }
3673
3674 return Changed;
3675}