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