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