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