Simplify the known retain count tracking; use a boolean state instead
[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 = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1037     // If the user used a constructor function with the wrong signature and
1038     // it got bitcasted or whatever, look the other way.
1039     if (!F)
1040       continue;
1041     // Only look at function definitions.
1042     if (F->isDeclaration())
1043       continue;
1044     // Only look at functions with one basic block.
1045     if (llvm::next(F->begin()) != F->end())
1046       continue;
1047     // Ok, a single-block constructor function definition. Try to optimize it.
1048     Changed |= OptimizeBB(F->begin());
1049   }
1050
1051   return Changed;
1052 }
1053
1054 //===----------------------------------------------------------------------===//
1055 // ARC optimization.
1056 //===----------------------------------------------------------------------===//
1057
1058 // TODO: On code like this:
1059 //
1060 // objc_retain(%x)
1061 // stuff_that_cannot_release()
1062 // objc_autorelease(%x)
1063 // stuff_that_cannot_release()
1064 // objc_retain(%x)
1065 // stuff_that_cannot_release()
1066 // objc_autorelease(%x)
1067 //
1068 // The second retain and autorelease can be deleted.
1069
1070 // TODO: It should be possible to delete
1071 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1072 // pairs if nothing is actually autoreleased between them. Also, autorelease
1073 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1074 // after inlining) can be turned into plain release calls.
1075
1076 // TODO: Critical-edge splitting. If the optimial insertion point is
1077 // a critical edge, the current algorithm has to fail, because it doesn't
1078 // know how to split edges. It should be possible to make the optimizer
1079 // think in terms of edges, rather than blocks, and then split critical
1080 // edges on demand.
1081
1082 // TODO: OptimizeSequences could generalized to be Interprocedural.
1083
1084 // TODO: Recognize that a bunch of other objc runtime calls have
1085 // non-escaping arguments and non-releasing arguments, and may be
1086 // non-autoreleasing.
1087
1088 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1089 // usually can't sink them past other calls, which would be the main
1090 // case where it would be useful.
1091
1092 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1093
1094 // TODO: Delete release+retain pairs (rare).
1095
1096 #include "llvm/GlobalAlias.h"
1097 #include "llvm/Constants.h"
1098 #include "llvm/LLVMContext.h"
1099 #include "llvm/Support/ErrorHandling.h"
1100 #include "llvm/Support/CFG.h"
1101 #include "llvm/ADT/Statistic.h"
1102 #include "llvm/ADT/SmallPtrSet.h"
1103 #include "llvm/ADT/DenseSet.h"
1104
1105 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
1106 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1107 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1108 STATISTIC(NumRets,        "Number of return value forwarding "
1109                           "retain+autoreleaes eliminated");
1110 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
1111 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
1112
1113 namespace {
1114   /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1115   /// uses many of the same techniques, except it uses special ObjC-specific
1116   /// reasoning about pointer relationships.
1117   class ProvenanceAnalysis {
1118     AliasAnalysis *AA;
1119
1120     typedef std::pair<const Value *, const Value *> ValuePairTy;
1121     typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1122     CachedResultsTy CachedResults;
1123
1124     bool relatedCheck(const Value *A, const Value *B);
1125     bool relatedSelect(const SelectInst *A, const Value *B);
1126     bool relatedPHI(const PHINode *A, const Value *B);
1127
1128     // Do not implement.
1129     void operator=(const ProvenanceAnalysis &);
1130     ProvenanceAnalysis(const ProvenanceAnalysis &);
1131
1132   public:
1133     ProvenanceAnalysis() {}
1134
1135     void setAA(AliasAnalysis *aa) { AA = aa; }
1136
1137     AliasAnalysis *getAA() const { return AA; }
1138
1139     bool related(const Value *A, const Value *B);
1140
1141     void clear() {
1142       CachedResults.clear();
1143     }
1144   };
1145 }
1146
1147 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1148   // If the values are Selects with the same condition, we can do a more precise
1149   // check: just check for relations between the values on corresponding arms.
1150   if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1151     if (A->getCondition() == SB->getCondition()) {
1152       if (related(A->getTrueValue(), SB->getTrueValue()))
1153         return true;
1154       if (related(A->getFalseValue(), SB->getFalseValue()))
1155         return true;
1156       return false;
1157     }
1158
1159   // Check both arms of the Select node individually.
1160   if (related(A->getTrueValue(), B))
1161     return true;
1162   if (related(A->getFalseValue(), B))
1163     return true;
1164
1165   // The arms both checked out.
1166   return false;
1167 }
1168
1169 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1170   // If the values are PHIs in the same block, we can do a more precise as well
1171   // as efficient check: just check for relations between the values on
1172   // corresponding edges.
1173   if (const PHINode *PNB = dyn_cast<PHINode>(B))
1174     if (PNB->getParent() == A->getParent()) {
1175       for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1176         if (related(A->getIncomingValue(i),
1177                     PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1178           return true;
1179       return false;
1180     }
1181
1182   // Check each unique source of the PHI node against B.
1183   SmallPtrSet<const Value *, 4> UniqueSrc;
1184   for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1185     const Value *PV1 = A->getIncomingValue(i);
1186     if (UniqueSrc.insert(PV1) && related(PV1, B))
1187       return true;
1188   }
1189
1190   // All of the arms checked out.
1191   return false;
1192 }
1193
1194 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1195 /// provenance, is ever stored within the function (not counting callees).
1196 static bool isStoredObjCPointer(const Value *P) {
1197   SmallPtrSet<const Value *, 8> Visited;
1198   SmallVector<const Value *, 8> Worklist;
1199   Worklist.push_back(P);
1200   Visited.insert(P);
1201   do {
1202     P = Worklist.pop_back_val();
1203     for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1204          UI != UE; ++UI) {
1205       const User *Ur = *UI;
1206       if (isa<StoreInst>(Ur)) {
1207         if (UI.getOperandNo() == 0)
1208           // The pointer is stored.
1209           return true;
1210         // The pointed is stored through.
1211         continue;
1212       }
1213       if (isa<CallInst>(Ur))
1214         // The pointer is passed as an argument, ignore this.
1215         continue;
1216       if (isa<PtrToIntInst>(P))
1217         // Assume the worst.
1218         return true;
1219       if (Visited.insert(Ur))
1220         Worklist.push_back(Ur);
1221     }
1222   } while (!Worklist.empty());
1223
1224   // Everything checked out.
1225   return false;
1226 }
1227
1228 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1229   // Skip past provenance pass-throughs.
1230   A = GetUnderlyingObjCPtr(A);
1231   B = GetUnderlyingObjCPtr(B);
1232
1233   // Quick check.
1234   if (A == B)
1235     return true;
1236
1237   // Ask regular AliasAnalysis, for a first approximation.
1238   switch (AA->alias(A, B)) {
1239   case AliasAnalysis::NoAlias:
1240     return false;
1241   case AliasAnalysis::MustAlias:
1242   case AliasAnalysis::PartialAlias:
1243     return true;
1244   case AliasAnalysis::MayAlias:
1245     break;
1246   }
1247
1248   bool AIsIdentified = IsObjCIdentifiedObject(A);
1249   bool BIsIdentified = IsObjCIdentifiedObject(B);
1250
1251   // An ObjC-Identified object can't alias a load if it is never locally stored.
1252   if (AIsIdentified) {
1253     if (BIsIdentified) {
1254       // If both pointers have provenance, they can be directly compared.
1255       if (A != B)
1256         return false;
1257     } else {
1258       if (isa<LoadInst>(B))
1259         return isStoredObjCPointer(A);
1260     }
1261   } else {
1262     if (BIsIdentified && isa<LoadInst>(A))
1263       return isStoredObjCPointer(B);
1264   }
1265
1266    // Special handling for PHI and Select.
1267   if (const PHINode *PN = dyn_cast<PHINode>(A))
1268     return relatedPHI(PN, B);
1269   if (const PHINode *PN = dyn_cast<PHINode>(B))
1270     return relatedPHI(PN, A);
1271   if (const SelectInst *S = dyn_cast<SelectInst>(A))
1272     return relatedSelect(S, B);
1273   if (const SelectInst *S = dyn_cast<SelectInst>(B))
1274     return relatedSelect(S, A);
1275
1276   // Conservative.
1277   return true;
1278 }
1279
1280 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1281   // Begin by inserting a conservative value into the map. If the insertion
1282   // fails, we have the answer already. If it succeeds, leave it there until we
1283   // compute the real answer to guard against recursive queries.
1284   if (A > B) std::swap(A, B);
1285   std::pair<CachedResultsTy::iterator, bool> Pair =
1286     CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1287   if (!Pair.second)
1288     return Pair.first->second;
1289
1290   bool Result = relatedCheck(A, B);
1291   CachedResults[ValuePairTy(A, B)] = Result;
1292   return Result;
1293 }
1294
1295 namespace {
1296   // Sequence - A sequence of states that a pointer may go through in which an
1297   // objc_retain and objc_release are actually needed.
1298   enum Sequence {
1299     S_None,
1300     S_Retain,         ///< objc_retain(x)
1301     S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement
1302     S_Use,            ///< any use of x
1303     S_Stop,           ///< like S_Release, but code motion is stopped
1304     S_Release,        ///< objc_release(x)
1305     S_MovableRelease  ///< objc_release(x), !clang.imprecise_release
1306   };
1307 }
1308
1309 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1310   // The easy cases.
1311   if (A == B)
1312     return A;
1313   if (A == S_None || B == S_None)
1314     return S_None;
1315
1316   if (A > B) std::swap(A, B);
1317   if (TopDown) {
1318     // Choose the side which is further along in the sequence.
1319     if ((A == S_Retain || A == S_CanRelease) &&
1320         (B == S_CanRelease || B == S_Use))
1321       return B;
1322   } else {
1323     // Choose the side which is further along in the sequence.
1324     if ((A == S_Use || A == S_CanRelease) &&
1325         (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1326       return A;
1327     // If both sides are releases, choose the more conservative one.
1328     if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1329       return A;
1330     if (A == S_Release && B == S_MovableRelease)
1331       return A;
1332   }
1333
1334   return S_None;
1335 }
1336
1337 namespace {
1338   /// RRInfo - Unidirectional information about either a
1339   /// retain-decrement-use-release sequence or release-use-decrement-retain
1340   /// reverese sequence.
1341   struct RRInfo {
1342     /// KnownSafe - After an objc_retain, the reference count of the referenced
1343     /// object is known to be positive. Similarly, before an objc_release, the
1344     /// reference count of the referenced object is known to be positive. If
1345     /// there are retain-release pairs in code regions where the retain count
1346     /// is known to be positive, they can be eliminated, regardless of any side
1347     /// effects between them.
1348     ///
1349     /// Also, a retain+release pair nested within another retain+release
1350     /// pair all on the known same pointer value can be eliminated, regardless
1351     /// of any intervening side effects.
1352     ///
1353     /// KnownSafe is true when either of these conditions is satisfied.
1354     bool KnownSafe;
1355
1356     /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1357     /// opposed to objc_retain calls).
1358     bool IsRetainBlock;
1359
1360     /// IsTailCallRelease - True of the objc_release calls are all marked
1361     /// with the "tail" keyword.
1362     bool IsTailCallRelease;
1363
1364     /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1365     /// a clang.imprecise_release tag, this is the metadata tag.
1366     MDNode *ReleaseMetadata;
1367
1368     /// Calls - For a top-down sequence, the set of objc_retains or
1369     /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1370     SmallPtrSet<Instruction *, 2> Calls;
1371
1372     /// ReverseInsertPts - The set of optimal insert positions for
1373     /// moving calls in the opposite sequence.
1374     SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1375
1376     RRInfo() :
1377       KnownSafe(false), IsRetainBlock(false),
1378       IsTailCallRelease(false),
1379       ReleaseMetadata(0) {}
1380
1381     void clear();
1382   };
1383 }
1384
1385 void RRInfo::clear() {
1386   KnownSafe = false;
1387   IsRetainBlock = false;
1388   IsTailCallRelease = false;
1389   ReleaseMetadata = 0;
1390   Calls.clear();
1391   ReverseInsertPts.clear();
1392 }
1393
1394 namespace {
1395   /// PtrState - This class summarizes several per-pointer runtime properties
1396   /// which are propogated through the flow graph.
1397   class PtrState {
1398     /// KnownPositiveRefCount - True if the reference count is known to
1399     /// be incremented.
1400     bool KnownPositiveRefCount;
1401
1402     /// Partial - True of we've seen an opportunity for partial RR elimination,
1403     /// such as pushing calls into a CFG triangle or into one side of a
1404     /// CFG diamond.
1405     bool Partial;
1406
1407     /// NestCount - The known minimum level of retain+release nesting.
1408     unsigned NestCount;
1409
1410     /// Seq - The current position in the sequence.
1411     Sequence Seq;
1412
1413   public:
1414     /// RRI - Unidirectional information about the current sequence.
1415     /// TODO: Encapsulate this better.
1416     RRInfo RRI;
1417
1418     PtrState() : KnownPositiveRefCount(false), Partial(false),
1419                  NestCount(0), Seq(S_None) {}
1420
1421     void SetKnownPositiveRefCount() {
1422       KnownPositiveRefCount = true;
1423     }
1424
1425     void ClearRefCount() {
1426       KnownPositiveRefCount = false;
1427     }
1428
1429     bool IsKnownIncremented() const {
1430       return KnownPositiveRefCount;
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       ResetSequenceProgress(S_None);
1455     }
1456
1457     void ResetSequenceProgress(Sequence NewSeq) {
1458       Seq = NewSeq;
1459       Partial = false;
1460       RRI.clear();
1461     }
1462
1463     void Merge(const PtrState &Other, bool TopDown);
1464   };
1465 }
1466
1467 void
1468 PtrState::Merge(const PtrState &Other, bool TopDown) {
1469   Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1470   KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1471   NestCount = std::min(NestCount, Other.NestCount);
1472
1473   // We can't merge a plain objc_retain with an objc_retainBlock.
1474   if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1475     Seq = S_None;
1476
1477   // If we're not in a sequence (anymore), drop all associated state.
1478   if (Seq == S_None) {
1479     Partial = false;
1480     RRI.clear();
1481   } else if (Partial || Other.Partial) {
1482     // If we're doing a merge on a path that's previously seen a partial
1483     // merge, conservatively drop the sequence, to avoid doing partial
1484     // RR elimination. If the branch predicates for the two merge differ,
1485     // mixing them is unsafe.
1486     ClearSequenceProgress();
1487   } else {
1488     // Conservatively merge the ReleaseMetadata information.
1489     if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1490       RRI.ReleaseMetadata = 0;
1491
1492     RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1493     RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1494     RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1495
1496     // Merge the insert point sets. If there are any differences,
1497     // that makes this a partial merge.
1498     Partial = RRI.ReverseInsertPts.size() !=
1499               Other.RRI.ReverseInsertPts.size();
1500     for (SmallPtrSet<Instruction *, 2>::const_iterator
1501          I = Other.RRI.ReverseInsertPts.begin(),
1502          E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1503       Partial |= RRI.ReverseInsertPts.insert(*I);
1504   }
1505 }
1506
1507 namespace {
1508   /// BBState - Per-BasicBlock state.
1509   class BBState {
1510     /// TopDownPathCount - The number of unique control paths from the entry
1511     /// which can reach this block.
1512     unsigned TopDownPathCount;
1513
1514     /// BottomUpPathCount - The number of unique control paths to exits
1515     /// from this block.
1516     unsigned BottomUpPathCount;
1517
1518     /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1519     typedef MapVector<const Value *, PtrState> MapTy;
1520
1521     /// PerPtrTopDown - The top-down traversal uses this to record information
1522     /// known about a pointer at the bottom of each block.
1523     MapTy PerPtrTopDown;
1524
1525     /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1526     /// known about a pointer at the top of each block.
1527     MapTy PerPtrBottomUp;
1528
1529     /// Preds, Succs - Effective successors and predecessors of the current
1530     /// block (this ignores ignorable edges and ignored backedges).
1531     SmallVector<BasicBlock *, 2> Preds;
1532     SmallVector<BasicBlock *, 2> Succs;
1533
1534   public:
1535     BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1536
1537     typedef MapTy::iterator ptr_iterator;
1538     typedef MapTy::const_iterator ptr_const_iterator;
1539
1540     ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1541     ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1542     ptr_const_iterator top_down_ptr_begin() const {
1543       return PerPtrTopDown.begin();
1544     }
1545     ptr_const_iterator top_down_ptr_end() const {
1546       return PerPtrTopDown.end();
1547     }
1548
1549     ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1550     ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1551     ptr_const_iterator bottom_up_ptr_begin() const {
1552       return PerPtrBottomUp.begin();
1553     }
1554     ptr_const_iterator bottom_up_ptr_end() const {
1555       return PerPtrBottomUp.end();
1556     }
1557
1558     /// SetAsEntry - Mark this block as being an entry block, which has one
1559     /// path from the entry by definition.
1560     void SetAsEntry() { TopDownPathCount = 1; }
1561
1562     /// SetAsExit - Mark this block as being an exit block, which has one
1563     /// path to an exit by definition.
1564     void SetAsExit()  { BottomUpPathCount = 1; }
1565
1566     PtrState &getPtrTopDownState(const Value *Arg) {
1567       return PerPtrTopDown[Arg];
1568     }
1569
1570     PtrState &getPtrBottomUpState(const Value *Arg) {
1571       return PerPtrBottomUp[Arg];
1572     }
1573
1574     void clearBottomUpPointers() {
1575       PerPtrBottomUp.clear();
1576     }
1577
1578     void clearTopDownPointers() {
1579       PerPtrTopDown.clear();
1580     }
1581
1582     void InitFromPred(const BBState &Other);
1583     void InitFromSucc(const BBState &Other);
1584     void MergePred(const BBState &Other);
1585     void MergeSucc(const BBState &Other);
1586
1587     /// GetAllPathCount - Return the number of possible unique paths from an
1588     /// entry to an exit which pass through this block. This is only valid
1589     /// after both the top-down and bottom-up traversals are complete.
1590     unsigned GetAllPathCount() const {
1591       assert(TopDownPathCount != 0);
1592       assert(BottomUpPathCount != 0);
1593       return TopDownPathCount * BottomUpPathCount;
1594     }
1595
1596     // Specialized CFG utilities.
1597     typedef SmallVectorImpl<BasicBlock *>::iterator edge_iterator;
1598     edge_iterator pred_begin() { return Preds.begin(); }
1599     edge_iterator pred_end() { return Preds.end(); }
1600     edge_iterator succ_begin() { return Succs.begin(); }
1601     edge_iterator succ_end() { return Succs.end(); }
1602
1603     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1604     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1605
1606     bool isExit() const { return Succs.empty(); }
1607   };
1608 }
1609
1610 void BBState::InitFromPred(const BBState &Other) {
1611   PerPtrTopDown = Other.PerPtrTopDown;
1612   TopDownPathCount = Other.TopDownPathCount;
1613 }
1614
1615 void BBState::InitFromSucc(const BBState &Other) {
1616   PerPtrBottomUp = Other.PerPtrBottomUp;
1617   BottomUpPathCount = Other.BottomUpPathCount;
1618 }
1619
1620 /// MergePred - The top-down traversal uses this to merge information about
1621 /// predecessors to form the initial state for a new block.
1622 void BBState::MergePred(const BBState &Other) {
1623   // Other.TopDownPathCount can be 0, in which case it is either dead or a
1624   // loop backedge. Loop backedges are special.
1625   TopDownPathCount += Other.TopDownPathCount;
1626
1627   // For each entry in the other set, if our set has an entry with the same key,
1628   // merge the entries. Otherwise, copy the entry and merge it with an empty
1629   // entry.
1630   for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1631        ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1632     std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1633     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1634                              /*TopDown=*/true);
1635   }
1636
1637   // For each entry in our set, if the other set doesn't have an entry with the
1638   // same key, force it to merge with an empty entry.
1639   for (ptr_iterator MI = top_down_ptr_begin(),
1640        ME = top_down_ptr_end(); MI != ME; ++MI)
1641     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1642       MI->second.Merge(PtrState(), /*TopDown=*/true);
1643 }
1644
1645 /// MergeSucc - The bottom-up traversal uses this to merge information about
1646 /// successors to form the initial state for a new block.
1647 void BBState::MergeSucc(const BBState &Other) {
1648   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1649   // loop backedge. Loop backedges are special.
1650   BottomUpPathCount += Other.BottomUpPathCount;
1651
1652   // For each entry in the other set, if our set has an entry with the
1653   // same key, merge the entries. Otherwise, copy the entry and merge
1654   // it with an empty entry.
1655   for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1656        ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1657     std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1658     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1659                              /*TopDown=*/false);
1660   }
1661
1662   // For each entry in our set, if the other set doesn't have an entry
1663   // with the same key, force it to merge with an empty entry.
1664   for (ptr_iterator MI = bottom_up_ptr_begin(),
1665        ME = bottom_up_ptr_end(); MI != ME; ++MI)
1666     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1667       MI->second.Merge(PtrState(), /*TopDown=*/false);
1668 }
1669
1670 namespace {
1671   /// ObjCARCOpt - The main ARC optimization pass.
1672   class ObjCARCOpt : public FunctionPass {
1673     bool Changed;
1674     ProvenanceAnalysis PA;
1675
1676     /// Run - A flag indicating whether this optimization pass should run.
1677     bool Run;
1678
1679     /// RetainRVCallee, etc. - Declarations for ObjC runtime
1680     /// functions, for use in creating calls to them. These are initialized
1681     /// lazily to avoid cluttering up the Module with unused declarations.
1682     Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1683              *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1684
1685     /// UsedInThisFunciton - Flags which determine whether each of the
1686     /// interesting runtine functions is in fact used in the current function.
1687     unsigned UsedInThisFunction;
1688
1689     /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1690     /// metadata.
1691     unsigned ImpreciseReleaseMDKind;
1692
1693     /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1694     /// metadata.
1695     unsigned CopyOnEscapeMDKind;
1696
1697     /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1698     /// clang.arc.no_objc_arc_exceptions metadata.
1699     unsigned NoObjCARCExceptionsMDKind;
1700
1701     Constant *getRetainRVCallee(Module *M);
1702     Constant *getAutoreleaseRVCallee(Module *M);
1703     Constant *getReleaseCallee(Module *M);
1704     Constant *getRetainCallee(Module *M);
1705     Constant *getRetainBlockCallee(Module *M);
1706     Constant *getAutoreleaseCallee(Module *M);
1707
1708     bool IsRetainBlockOptimizable(const Instruction *Inst);
1709
1710     void OptimizeRetainCall(Function &F, Instruction *Retain);
1711     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1712     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1713     void OptimizeIndividualCalls(Function &F);
1714
1715     void CheckForCFGHazards(const BasicBlock *BB,
1716                             DenseMap<const BasicBlock *, BBState> &BBStates,
1717                             BBState &MyStates) const;
1718     bool VisitInstructionBottomUp(Instruction *Inst,
1719                                   BasicBlock *BB,
1720                                   MapVector<Value *, RRInfo> &Retains,
1721                                   BBState &MyStates);
1722     bool VisitBottomUp(BasicBlock *BB,
1723                        DenseMap<const BasicBlock *, BBState> &BBStates,
1724                        MapVector<Value *, RRInfo> &Retains);
1725     bool VisitInstructionTopDown(Instruction *Inst,
1726                                  DenseMap<Value *, RRInfo> &Releases,
1727                                  BBState &MyStates);
1728     bool VisitTopDown(BasicBlock *BB,
1729                       DenseMap<const BasicBlock *, BBState> &BBStates,
1730                       DenseMap<Value *, RRInfo> &Releases);
1731     bool Visit(Function &F,
1732                DenseMap<const BasicBlock *, BBState> &BBStates,
1733                MapVector<Value *, RRInfo> &Retains,
1734                DenseMap<Value *, RRInfo> &Releases);
1735
1736     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1737                    MapVector<Value *, RRInfo> &Retains,
1738                    DenseMap<Value *, RRInfo> &Releases,
1739                    SmallVectorImpl<Instruction *> &DeadInsts,
1740                    Module *M);
1741
1742     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1743                               MapVector<Value *, RRInfo> &Retains,
1744                               DenseMap<Value *, RRInfo> &Releases,
1745                               Module *M);
1746
1747     void OptimizeWeakCalls(Function &F);
1748
1749     bool OptimizeSequences(Function &F);
1750
1751     void OptimizeReturns(Function &F);
1752
1753     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1754     virtual bool doInitialization(Module &M);
1755     virtual bool runOnFunction(Function &F);
1756     virtual void releaseMemory();
1757
1758   public:
1759     static char ID;
1760     ObjCARCOpt() : FunctionPass(ID) {
1761       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1762     }
1763   };
1764 }
1765
1766 char ObjCARCOpt::ID = 0;
1767 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1768                       "objc-arc", "ObjC ARC optimization", false, false)
1769 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1770 INITIALIZE_PASS_END(ObjCARCOpt,
1771                     "objc-arc", "ObjC ARC optimization", false, false)
1772
1773 Pass *llvm::createObjCARCOptPass() {
1774   return new ObjCARCOpt();
1775 }
1776
1777 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1778   AU.addRequired<ObjCARCAliasAnalysis>();
1779   AU.addRequired<AliasAnalysis>();
1780   // ARC optimization doesn't currently split critical edges.
1781   AU.setPreservesCFG();
1782 }
1783
1784 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1785   // Without the magic metadata tag, we have to assume this might be an
1786   // objc_retainBlock call inserted to convert a block pointer to an id,
1787   // in which case it really is needed.
1788   if (!Inst->getMetadata(CopyOnEscapeMDKind))
1789     return false;
1790
1791   // If the pointer "escapes" (not including being used in a call),
1792   // the copy may be needed.
1793   if (DoesObjCBlockEscape(Inst))
1794     return false;
1795
1796   // Otherwise, it's not needed.
1797   return true;
1798 }
1799
1800 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1801   if (!RetainRVCallee) {
1802     LLVMContext &C = M->getContext();
1803     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1804     std::vector<Type *> Params;
1805     Params.push_back(I8X);
1806     FunctionType *FTy =
1807       FunctionType::get(I8X, Params, /*isVarArg=*/false);
1808     AttrListPtr Attributes;
1809     Attributes.addAttr(~0u, Attribute::NoUnwind);
1810     RetainRVCallee =
1811       M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1812                              Attributes);
1813   }
1814   return RetainRVCallee;
1815 }
1816
1817 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1818   if (!AutoreleaseRVCallee) {
1819     LLVMContext &C = M->getContext();
1820     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1821     std::vector<Type *> Params;
1822     Params.push_back(I8X);
1823     FunctionType *FTy =
1824       FunctionType::get(I8X, Params, /*isVarArg=*/false);
1825     AttrListPtr Attributes;
1826     Attributes.addAttr(~0u, Attribute::NoUnwind);
1827     AutoreleaseRVCallee =
1828       M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1829                              Attributes);
1830   }
1831   return AutoreleaseRVCallee;
1832 }
1833
1834 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1835   if (!ReleaseCallee) {
1836     LLVMContext &C = M->getContext();
1837     std::vector<Type *> Params;
1838     Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1839     AttrListPtr Attributes;
1840     Attributes.addAttr(~0u, Attribute::NoUnwind);
1841     ReleaseCallee =
1842       M->getOrInsertFunction(
1843         "objc_release",
1844         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1845         Attributes);
1846   }
1847   return ReleaseCallee;
1848 }
1849
1850 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1851   if (!RetainCallee) {
1852     LLVMContext &C = M->getContext();
1853     std::vector<Type *> Params;
1854     Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1855     AttrListPtr Attributes;
1856     Attributes.addAttr(~0u, Attribute::NoUnwind);
1857     RetainCallee =
1858       M->getOrInsertFunction(
1859         "objc_retain",
1860         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1861         Attributes);
1862   }
1863   return RetainCallee;
1864 }
1865
1866 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1867   if (!RetainBlockCallee) {
1868     LLVMContext &C = M->getContext();
1869     std::vector<Type *> Params;
1870     Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1871     AttrListPtr Attributes;
1872     // objc_retainBlock is not nounwind because it calls user copy constructors
1873     // which could theoretically throw.
1874     RetainBlockCallee =
1875       M->getOrInsertFunction(
1876         "objc_retainBlock",
1877         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1878         Attributes);
1879   }
1880   return RetainBlockCallee;
1881 }
1882
1883 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1884   if (!AutoreleaseCallee) {
1885     LLVMContext &C = M->getContext();
1886     std::vector<Type *> Params;
1887     Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1888     AttrListPtr Attributes;
1889     Attributes.addAttr(~0u, Attribute::NoUnwind);
1890     AutoreleaseCallee =
1891       M->getOrInsertFunction(
1892         "objc_autorelease",
1893         FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1894         Attributes);
1895   }
1896   return AutoreleaseCallee;
1897 }
1898
1899 /// CanAlterRefCount - Test whether the given instruction can result in a
1900 /// reference count modification (positive or negative) for the pointer's
1901 /// object.
1902 static bool
1903 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1904                  ProvenanceAnalysis &PA, InstructionClass Class) {
1905   switch (Class) {
1906   case IC_Autorelease:
1907   case IC_AutoreleaseRV:
1908   case IC_User:
1909     // These operations never directly modify a reference count.
1910     return false;
1911   default: break;
1912   }
1913
1914   ImmutableCallSite CS = static_cast<const Value *>(Inst);
1915   assert(CS && "Only calls can alter reference counts!");
1916
1917   // See if AliasAnalysis can help us with the call.
1918   AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1919   if (AliasAnalysis::onlyReadsMemory(MRB))
1920     return false;
1921   if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1922     for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1923          I != E; ++I) {
1924       const Value *Op = *I;
1925       if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1926         return true;
1927     }
1928     return false;
1929   }
1930
1931   // Assume the worst.
1932   return true;
1933 }
1934
1935 /// CanUse - Test whether the given instruction can "use" the given pointer's
1936 /// object in a way that requires the reference count to be positive.
1937 static bool
1938 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1939        InstructionClass Class) {
1940   // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1941   if (Class == IC_Call)
1942     return false;
1943
1944   // Consider various instructions which may have pointer arguments which are
1945   // not "uses".
1946   if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1947     // Comparing a pointer with null, or any other constant, isn't really a use,
1948     // because we don't care what the pointer points to, or about the values
1949     // of any other dynamic reference-counted pointers.
1950     if (!IsPotentialUse(ICI->getOperand(1)))
1951       return false;
1952   } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1953     // For calls, just check the arguments (and not the callee operand).
1954     for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1955          OE = CS.arg_end(); OI != OE; ++OI) {
1956       const Value *Op = *OI;
1957       if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1958         return true;
1959     }
1960     return false;
1961   } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1962     // Special-case stores, because we don't care about the stored value, just
1963     // the store address.
1964     const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1965     // If we can't tell what the underlying object was, assume there is a
1966     // dependence.
1967     return IsPotentialUse(Op) && PA.related(Op, Ptr);
1968   }
1969
1970   // Check each operand for a match.
1971   for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1972        OI != OE; ++OI) {
1973     const Value *Op = *OI;
1974     if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1975       return true;
1976   }
1977   return false;
1978 }
1979
1980 /// CanInterruptRV - Test whether the given instruction can autorelease
1981 /// any pointer or cause an autoreleasepool pop.
1982 static bool
1983 CanInterruptRV(InstructionClass Class) {
1984   switch (Class) {
1985   case IC_AutoreleasepoolPop:
1986   case IC_CallOrUser:
1987   case IC_Call:
1988   case IC_Autorelease:
1989   case IC_AutoreleaseRV:
1990   case IC_FusedRetainAutorelease:
1991   case IC_FusedRetainAutoreleaseRV:
1992     return true;
1993   default:
1994     return false;
1995   }
1996 }
1997
1998 namespace {
1999   /// DependenceKind - There are several kinds of dependence-like concepts in
2000   /// use here.
2001   enum DependenceKind {
2002     NeedsPositiveRetainCount,
2003     AutoreleasePoolBoundary,
2004     CanChangeRetainCount,
2005     RetainAutoreleaseDep,       ///< Blocks objc_retainAutorelease.
2006     RetainAutoreleaseRVDep,     ///< Blocks objc_retainAutoreleaseReturnValue.
2007     RetainRVDep                 ///< Blocks objc_retainAutoreleasedReturnValue.
2008   };
2009 }
2010
2011 /// Depends - Test if there can be dependencies on Inst through Arg. This
2012 /// function only tests dependencies relevant for removing pairs of calls.
2013 static bool
2014 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2015         ProvenanceAnalysis &PA) {
2016   // If we've reached the definition of Arg, stop.
2017   if (Inst == Arg)
2018     return true;
2019
2020   switch (Flavor) {
2021   case NeedsPositiveRetainCount: {
2022     InstructionClass Class = GetInstructionClass(Inst);
2023     switch (Class) {
2024     case IC_AutoreleasepoolPop:
2025     case IC_AutoreleasepoolPush:
2026     case IC_None:
2027       return false;
2028     default:
2029       return CanUse(Inst, Arg, PA, Class);
2030     }
2031   }
2032
2033   case AutoreleasePoolBoundary: {
2034     InstructionClass Class = GetInstructionClass(Inst);
2035     switch (Class) {
2036     case IC_AutoreleasepoolPop:
2037     case IC_AutoreleasepoolPush:
2038       // These mark the end and begin of an autorelease pool scope.
2039       return true;
2040     default:
2041       // Nothing else does this.
2042       return false;
2043     }
2044   }
2045
2046   case CanChangeRetainCount: {
2047     InstructionClass Class = GetInstructionClass(Inst);
2048     switch (Class) {
2049     case IC_AutoreleasepoolPop:
2050       // Conservatively assume this can decrement any count.
2051       return true;
2052     case IC_AutoreleasepoolPush:
2053     case IC_None:
2054       return false;
2055     default:
2056       return CanAlterRefCount(Inst, Arg, PA, Class);
2057     }
2058   }
2059
2060   case RetainAutoreleaseDep:
2061     switch (GetBasicInstructionClass(Inst)) {
2062     case IC_AutoreleasepoolPop:
2063     case IC_AutoreleasepoolPush:
2064       // Don't merge an objc_autorelease with an objc_retain inside a different
2065       // autoreleasepool scope.
2066       return true;
2067     case IC_Retain:
2068     case IC_RetainRV:
2069       // Check for a retain of the same pointer for merging.
2070       return GetObjCArg(Inst) == Arg;
2071     default:
2072       // Nothing else matters for objc_retainAutorelease formation.
2073       return false;
2074     }
2075
2076   case RetainAutoreleaseRVDep: {
2077     InstructionClass Class = GetBasicInstructionClass(Inst);
2078     switch (Class) {
2079     case IC_Retain:
2080     case IC_RetainRV:
2081       // Check for a retain of the same pointer for merging.
2082       return GetObjCArg(Inst) == Arg;
2083     default:
2084       // Anything that can autorelease interrupts
2085       // retainAutoreleaseReturnValue formation.
2086       return CanInterruptRV(Class);
2087     }
2088   }
2089
2090   case RetainRVDep:
2091     return CanInterruptRV(GetBasicInstructionClass(Inst));
2092   }
2093
2094   llvm_unreachable("Invalid dependence flavor");
2095 }
2096
2097 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2098 /// find local and non-local dependencies on Arg.
2099 /// TODO: Cache results?
2100 static void
2101 FindDependencies(DependenceKind Flavor,
2102                  const Value *Arg,
2103                  BasicBlock *StartBB, Instruction *StartInst,
2104                  SmallPtrSet<Instruction *, 4> &DependingInstructions,
2105                  SmallPtrSet<const BasicBlock *, 4> &Visited,
2106                  ProvenanceAnalysis &PA) {
2107   BasicBlock::iterator StartPos = StartInst;
2108
2109   SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2110   Worklist.push_back(std::make_pair(StartBB, StartPos));
2111   do {
2112     std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2113       Worklist.pop_back_val();
2114     BasicBlock *LocalStartBB = Pair.first;
2115     BasicBlock::iterator LocalStartPos = Pair.second;
2116     BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2117     for (;;) {
2118       if (LocalStartPos == StartBBBegin) {
2119         pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2120         if (PI == PE)
2121           // If we've reached the function entry, produce a null dependence.
2122           DependingInstructions.insert(0);
2123         else
2124           // Add the predecessors to the worklist.
2125           do {
2126             BasicBlock *PredBB = *PI;
2127             if (Visited.insert(PredBB))
2128               Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2129           } while (++PI != PE);
2130         break;
2131       }
2132
2133       Instruction *Inst = --LocalStartPos;
2134       if (Depends(Flavor, Inst, Arg, PA)) {
2135         DependingInstructions.insert(Inst);
2136         break;
2137       }
2138     }
2139   } while (!Worklist.empty());
2140
2141   // Determine whether the original StartBB post-dominates all of the blocks we
2142   // visited. If not, insert a sentinal indicating that most optimizations are
2143   // not safe.
2144   for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2145        E = Visited.end(); I != E; ++I) {
2146     const BasicBlock *BB = *I;
2147     if (BB == StartBB)
2148       continue;
2149     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2150     for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2151       const BasicBlock *Succ = *SI;
2152       if (Succ != StartBB && !Visited.count(Succ)) {
2153         DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2154         return;
2155       }
2156     }
2157   }
2158 }
2159
2160 static bool isNullOrUndef(const Value *V) {
2161   return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2162 }
2163
2164 static bool isNoopInstruction(const Instruction *I) {
2165   return isa<BitCastInst>(I) ||
2166          (isa<GetElementPtrInst>(I) &&
2167           cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2168 }
2169
2170 /// OptimizeRetainCall - Turn objc_retain into
2171 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2172 void
2173 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2174   CallSite CS(GetObjCArg(Retain));
2175   Instruction *Call = CS.getInstruction();
2176   if (!Call) return;
2177   if (Call->getParent() != Retain->getParent()) return;
2178
2179   // Check that the call is next to the retain.
2180   BasicBlock::iterator I = Call;
2181   ++I;
2182   while (isNoopInstruction(I)) ++I;
2183   if (&*I != Retain)
2184     return;
2185
2186   // Turn it to an objc_retainAutoreleasedReturnValue..
2187   Changed = true;
2188   ++NumPeeps;
2189   cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2190 }
2191
2192 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2193 /// objc_retain if the operand is not a return value.  Or, if it can be
2194 /// paired with an objc_autoreleaseReturnValue, delete the pair and
2195 /// return true.
2196 bool
2197 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2198   // Check for the argument being from an immediately preceding call or invoke.
2199   Value *Arg = GetObjCArg(RetainRV);
2200   CallSite CS(Arg);
2201   if (Instruction *Call = CS.getInstruction()) {
2202     if (Call->getParent() == RetainRV->getParent()) {
2203       BasicBlock::iterator I = Call;
2204       ++I;
2205       while (isNoopInstruction(I)) ++I;
2206       if (&*I == RetainRV)
2207         return false;
2208     } else if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2209       BasicBlock *RetainRVParent = RetainRV->getParent();
2210       if (II->getNormalDest() == RetainRVParent) {
2211         BasicBlock::iterator I = RetainRVParent->begin();
2212         while (isNoopInstruction(I)) ++I;
2213         if (&*I == RetainRV)
2214           return false;
2215       }
2216     }
2217   }
2218
2219   // Check for being preceded by an objc_autoreleaseReturnValue on the same
2220   // pointer. In this case, we can delete the pair.
2221   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2222   if (I != Begin) {
2223     do --I; while (I != Begin && isNoopInstruction(I));
2224     if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2225         GetObjCArg(I) == Arg) {
2226       Changed = true;
2227       ++NumPeeps;
2228       EraseInstruction(I);
2229       EraseInstruction(RetainRV);
2230       return true;
2231     }
2232   }
2233
2234   // Turn it to a plain objc_retain.
2235   Changed = true;
2236   ++NumPeeps;
2237   cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2238   return false;
2239 }
2240
2241 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2242 /// objc_autorelease if the result is not used as a return value.
2243 void
2244 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2245   // Check for a return of the pointer value.
2246   const Value *Ptr = GetObjCArg(AutoreleaseRV);
2247   SmallVector<const Value *, 2> Users;
2248   Users.push_back(Ptr);
2249   do {
2250     Ptr = Users.pop_back_val();
2251     for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2252          UI != UE; ++UI) {
2253       const User *I = *UI;
2254       if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2255         return;
2256       if (isa<BitCastInst>(I))
2257         Users.push_back(I);
2258     }
2259   } while (!Users.empty());
2260
2261   Changed = true;
2262   ++NumPeeps;
2263   cast<CallInst>(AutoreleaseRV)->
2264     setCalledFunction(getAutoreleaseCallee(F.getParent()));
2265 }
2266
2267 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2268 /// simplifications without doing any additional analysis.
2269 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2270   // Reset all the flags in preparation for recomputing them.
2271   UsedInThisFunction = 0;
2272
2273   // Visit all objc_* calls in F.
2274   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2275     Instruction *Inst = &*I++;
2276     InstructionClass Class = GetBasicInstructionClass(Inst);
2277
2278     switch (Class) {
2279     default: break;
2280
2281     // Delete no-op casts. These function calls have special semantics, but
2282     // the semantics are entirely implemented via lowering in the front-end,
2283     // so by the time they reach the optimizer, they are just no-op calls
2284     // which return their argument.
2285     //
2286     // There are gray areas here, as the ability to cast reference-counted
2287     // pointers to raw void* and back allows code to break ARC assumptions,
2288     // however these are currently considered to be unimportant.
2289     case IC_NoopCast:
2290       Changed = true;
2291       ++NumNoops;
2292       EraseInstruction(Inst);
2293       continue;
2294
2295     // If the pointer-to-weak-pointer is null, it's undefined behavior.
2296     case IC_StoreWeak:
2297     case IC_LoadWeak:
2298     case IC_LoadWeakRetained:
2299     case IC_InitWeak:
2300     case IC_DestroyWeak: {
2301       CallInst *CI = cast<CallInst>(Inst);
2302       if (isNullOrUndef(CI->getArgOperand(0))) {
2303         Changed = true;
2304         Type *Ty = CI->getArgOperand(0)->getType();
2305         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2306                       Constant::getNullValue(Ty),
2307                       CI);
2308         CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2309         CI->eraseFromParent();
2310         continue;
2311       }
2312       break;
2313     }
2314     case IC_CopyWeak:
2315     case IC_MoveWeak: {
2316       CallInst *CI = cast<CallInst>(Inst);
2317       if (isNullOrUndef(CI->getArgOperand(0)) ||
2318           isNullOrUndef(CI->getArgOperand(1))) {
2319         Changed = true;
2320         Type *Ty = CI->getArgOperand(0)->getType();
2321         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2322                       Constant::getNullValue(Ty),
2323                       CI);
2324         CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2325         CI->eraseFromParent();
2326         continue;
2327       }
2328       break;
2329     }
2330     case IC_Retain:
2331       OptimizeRetainCall(F, Inst);
2332       break;
2333     case IC_RetainRV:
2334       if (OptimizeRetainRVCall(F, Inst))
2335         continue;
2336       break;
2337     case IC_AutoreleaseRV:
2338       OptimizeAutoreleaseRVCall(F, Inst);
2339       break;
2340     }
2341
2342     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2343     if (IsAutorelease(Class) && Inst->use_empty()) {
2344       CallInst *Call = cast<CallInst>(Inst);
2345       const Value *Arg = Call->getArgOperand(0);
2346       Arg = FindSingleUseIdentifiedObject(Arg);
2347       if (Arg) {
2348         Changed = true;
2349         ++NumAutoreleases;
2350
2351         // Create the declaration lazily.
2352         LLVMContext &C = Inst->getContext();
2353         CallInst *NewCall =
2354           CallInst::Create(getReleaseCallee(F.getParent()),
2355                            Call->getArgOperand(0), "", Call);
2356         NewCall->setMetadata(ImpreciseReleaseMDKind,
2357                              MDNode::get(C, ArrayRef<Value *>()));
2358         EraseInstruction(Call);
2359         Inst = NewCall;
2360         Class = IC_Release;
2361       }
2362     }
2363
2364     // For functions which can never be passed stack arguments, add
2365     // a tail keyword.
2366     if (IsAlwaysTail(Class)) {
2367       Changed = true;
2368       cast<CallInst>(Inst)->setTailCall();
2369     }
2370
2371     // Set nounwind as needed.
2372     if (IsNoThrow(Class)) {
2373       Changed = true;
2374       cast<CallInst>(Inst)->setDoesNotThrow();
2375     }
2376
2377     if (!IsNoopOnNull(Class)) {
2378       UsedInThisFunction |= 1 << Class;
2379       continue;
2380     }
2381
2382     const Value *Arg = GetObjCArg(Inst);
2383
2384     // ARC calls with null are no-ops. Delete them.
2385     if (isNullOrUndef(Arg)) {
2386       Changed = true;
2387       ++NumNoops;
2388       EraseInstruction(Inst);
2389       continue;
2390     }
2391
2392     // Keep track of which of retain, release, autorelease, and retain_block
2393     // are actually present in this function.
2394     UsedInThisFunction |= 1 << Class;
2395
2396     // If Arg is a PHI, and one or more incoming values to the
2397     // PHI are null, and the call is control-equivalent to the PHI, and there
2398     // are no relevant side effects between the PHI and the call, the call
2399     // could be pushed up to just those paths with non-null incoming values.
2400     // For now, don't bother splitting critical edges for this.
2401     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2402     Worklist.push_back(std::make_pair(Inst, Arg));
2403     do {
2404       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2405       Inst = Pair.first;
2406       Arg = Pair.second;
2407
2408       const PHINode *PN = dyn_cast<PHINode>(Arg);
2409       if (!PN) continue;
2410
2411       // Determine if the PHI has any null operands, or any incoming
2412       // critical edges.
2413       bool HasNull = false;
2414       bool HasCriticalEdges = false;
2415       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2416         Value *Incoming =
2417           StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2418         if (isNullOrUndef(Incoming))
2419           HasNull = true;
2420         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2421                    .getNumSuccessors() != 1) {
2422           HasCriticalEdges = true;
2423           break;
2424         }
2425       }
2426       // If we have null operands and no critical edges, optimize.
2427       if (!HasCriticalEdges && HasNull) {
2428         SmallPtrSet<Instruction *, 4> DependingInstructions;
2429         SmallPtrSet<const BasicBlock *, 4> Visited;
2430
2431         // Check that there is nothing that cares about the reference
2432         // count between the call and the phi.
2433         switch (Class) {
2434         case IC_Retain:
2435         case IC_RetainBlock:
2436           // These can always be moved up.
2437           break;
2438         case IC_Release:
2439           // These can't be moved across things that care about the retain count.
2440           FindDependencies(NeedsPositiveRetainCount, Arg,
2441                            Inst->getParent(), Inst,
2442                            DependingInstructions, Visited, PA);
2443           break;
2444         case IC_Autorelease:
2445           // These can't be moved across autorelease pool scope boundaries.
2446           FindDependencies(AutoreleasePoolBoundary, Arg,
2447                            Inst->getParent(), Inst,
2448                            DependingInstructions, Visited, PA);
2449           break;
2450         case IC_RetainRV:
2451         case IC_AutoreleaseRV:
2452           // Don't move these; the RV optimization depends on the autoreleaseRV
2453           // being tail called, and the retainRV being immediately after a call
2454           // (which might still happen if we get lucky with codegen layout, but
2455           // it's not worth taking the chance).
2456           continue;
2457         default:
2458           llvm_unreachable("Invalid dependence flavor");
2459         }
2460
2461         if (DependingInstructions.size() == 1 &&
2462             *DependingInstructions.begin() == PN) {
2463           Changed = true;
2464           ++NumPartialNoops;
2465           // Clone the call into each predecessor that has a non-null value.
2466           CallInst *CInst = cast<CallInst>(Inst);
2467           Type *ParamTy = CInst->getArgOperand(0)->getType();
2468           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2469             Value *Incoming =
2470               StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2471             if (!isNullOrUndef(Incoming)) {
2472               CallInst *Clone = cast<CallInst>(CInst->clone());
2473               Value *Op = PN->getIncomingValue(i);
2474               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2475               if (Op->getType() != ParamTy)
2476                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2477               Clone->setArgOperand(0, Op);
2478               Clone->insertBefore(InsertPos);
2479               Worklist.push_back(std::make_pair(Clone, Incoming));
2480             }
2481           }
2482           // Erase the original call.
2483           EraseInstruction(CInst);
2484           continue;
2485         }
2486       }
2487     } while (!Worklist.empty());
2488   }
2489 }
2490
2491 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2492 /// control flow, or other CFG structures where moving code across the edge
2493 /// would result in it being executed more.
2494 void
2495 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2496                                DenseMap<const BasicBlock *, BBState> &BBStates,
2497                                BBState &MyStates) const {
2498   // If any top-down local-use or possible-dec has a succ which is earlier in
2499   // the sequence, forget it.
2500   for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2501        E = MyStates.top_down_ptr_end(); I != E; ++I)
2502     switch (I->second.GetSeq()) {
2503     default: break;
2504     case S_Use: {
2505       const Value *Arg = I->first;
2506       const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2507       bool SomeSuccHasSame = false;
2508       bool AllSuccsHaveSame = true;
2509       PtrState &S = I->second;
2510       succ_const_iterator SI(TI), SE(TI, false);
2511
2512       // If the terminator is an invoke marked with the
2513       // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2514       // ignored, for ARC purposes.
2515       if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2516         --SE;
2517
2518       for (; SI != SE; ++SI) {
2519         Sequence SuccSSeq = S_None;
2520         bool SuccSRRIKnownSafe = false;
2521         // If VisitBottomUp has visited this successor, take what we know about it.
2522         DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2523         if (BBI != BBStates.end()) {
2524           const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2525           SuccSSeq = SuccS.GetSeq();
2526           SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2527         }
2528         switch (SuccSSeq) {
2529         case S_None:
2530         case S_CanRelease: {
2531           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2532             S.ClearSequenceProgress();
2533             break;
2534           }
2535           continue;
2536         }
2537         case S_Use:
2538           SomeSuccHasSame = true;
2539           break;
2540         case S_Stop:
2541         case S_Release:
2542         case S_MovableRelease:
2543           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2544             AllSuccsHaveSame = false;
2545           break;
2546         case S_Retain:
2547           llvm_unreachable("bottom-up pointer in retain state!");
2548         }
2549       }
2550       // If the state at the other end of any of the successor edges
2551       // matches the current state, require all edges to match. This
2552       // guards against loops in the middle of a sequence.
2553       if (SomeSuccHasSame && !AllSuccsHaveSame)
2554         S.ClearSequenceProgress();
2555       break;
2556     }
2557     case S_CanRelease: {
2558       const Value *Arg = I->first;
2559       const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2560       bool SomeSuccHasSame = false;
2561       bool AllSuccsHaveSame = true;
2562       PtrState &S = I->second;
2563       succ_const_iterator SI(TI), SE(TI, false);
2564
2565       // If the terminator is an invoke marked with the
2566       // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2567       // ignored, for ARC purposes.
2568       if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2569         --SE;
2570
2571       for (; SI != SE; ++SI) {
2572         Sequence SuccSSeq = S_None;
2573         bool SuccSRRIKnownSafe = false;
2574         // If VisitBottomUp has visited this successor, take what we know about it.
2575         DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2576         if (BBI != BBStates.end()) {
2577           const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2578           SuccSSeq = SuccS.GetSeq();
2579           SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2580         }
2581         switch (SuccSSeq) {
2582         case S_None: {
2583           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2584             S.ClearSequenceProgress();
2585             break;
2586           }
2587           continue;
2588         }
2589         case S_CanRelease:
2590           SomeSuccHasSame = true;
2591           break;
2592         case S_Stop:
2593         case S_Release:
2594         case S_MovableRelease:
2595         case S_Use:
2596           if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2597             AllSuccsHaveSame = false;
2598           break;
2599         case S_Retain:
2600           llvm_unreachable("bottom-up pointer in retain state!");
2601         }
2602       }
2603       // If the state at the other end of any of the successor edges
2604       // matches the current state, require all edges to match. This
2605       // guards against loops in the middle of a sequence.
2606       if (SomeSuccHasSame && !AllSuccsHaveSame)
2607         S.ClearSequenceProgress();
2608       break;
2609     }
2610     }
2611 }
2612
2613 bool
2614 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2615                                      BasicBlock *BB,
2616                                      MapVector<Value *, RRInfo> &Retains,
2617                                      BBState &MyStates) {
2618   bool NestingDetected = false;
2619   InstructionClass Class = GetInstructionClass(Inst);
2620   const Value *Arg = 0;
2621
2622   switch (Class) {
2623   case IC_Release: {
2624     Arg = GetObjCArg(Inst);
2625
2626     PtrState &S = MyStates.getPtrBottomUpState(Arg);
2627
2628     // If we see two releases in a row on the same pointer. If so, make
2629     // a note, and we'll cicle back to revisit it after we've
2630     // hopefully eliminated the second release, which may allow us to
2631     // eliminate the first release too.
2632     // Theoretically we could implement removal of nested retain+release
2633     // pairs by making PtrState hold a stack of states, but this is
2634     // simple and avoids adding overhead for the non-nested case.
2635     if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2636       NestingDetected = true;
2637
2638     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2639     S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2640     S.RRI.ReleaseMetadata = ReleaseMetadata;
2641     S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2642     S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2643     S.RRI.Calls.insert(Inst);
2644
2645     S.IncrementNestCount();
2646     break;
2647   }
2648   case IC_RetainBlock:
2649     // An objc_retainBlock call with just a use may need to be kept,
2650     // because it may be copying a block from the stack to the heap.
2651     if (!IsRetainBlockOptimizable(Inst))
2652       break;
2653     // FALLTHROUGH
2654   case IC_Retain:
2655   case IC_RetainRV: {
2656     Arg = GetObjCArg(Inst);
2657
2658     PtrState &S = MyStates.getPtrBottomUpState(Arg);
2659     S.SetKnownPositiveRefCount();
2660     S.DecrementNestCount();
2661
2662     switch (S.GetSeq()) {
2663     case S_Stop:
2664     case S_Release:
2665     case S_MovableRelease:
2666     case S_Use:
2667       S.RRI.ReverseInsertPts.clear();
2668       // FALL THROUGH
2669     case S_CanRelease:
2670       // Don't do retain+release tracking for IC_RetainRV, because it's
2671       // better to let it remain as the first instruction after a call.
2672       if (Class != IC_RetainRV) {
2673         S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2674         Retains[Inst] = S.RRI;
2675       }
2676       S.ClearSequenceProgress();
2677       break;
2678     case S_None:
2679       break;
2680     case S_Retain:
2681       llvm_unreachable("bottom-up pointer in retain state!");
2682     }
2683     return NestingDetected;
2684   }
2685   case IC_AutoreleasepoolPop:
2686     // Conservatively, clear MyStates for all known pointers.
2687     MyStates.clearBottomUpPointers();
2688     return NestingDetected;
2689   case IC_AutoreleasepoolPush:
2690   case IC_None:
2691     // These are irrelevant.
2692     return NestingDetected;
2693   default:
2694     break;
2695   }
2696
2697   // Consider any other possible effects of this instruction on each
2698   // pointer being tracked.
2699   for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2700        ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2701     const Value *Ptr = MI->first;
2702     if (Ptr == Arg)
2703       continue; // Handled above.
2704     PtrState &S = MI->second;
2705     Sequence Seq = S.GetSeq();
2706
2707     // Check for possible releases.
2708     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2709       S.ClearRefCount();
2710       switch (Seq) {
2711       case S_Use:
2712         S.SetSeq(S_CanRelease);
2713         continue;
2714       case S_CanRelease:
2715       case S_Release:
2716       case S_MovableRelease:
2717       case S_Stop:
2718       case S_None:
2719         break;
2720       case S_Retain:
2721         llvm_unreachable("bottom-up pointer in retain state!");
2722       }
2723     }
2724
2725     // Check for possible direct uses.
2726     switch (Seq) {
2727     case S_Release:
2728     case S_MovableRelease:
2729       if (CanUse(Inst, Ptr, PA, Class)) {
2730         assert(S.RRI.ReverseInsertPts.empty());
2731         // If this is an invoke instruction, we're scanning it as part of
2732         // one of its successor blocks, since we can't insert code after it
2733         // in its own block, and we don't want to split critical edges.
2734         if (isa<InvokeInst>(Inst))
2735           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2736         else
2737           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2738         S.SetSeq(S_Use);
2739       } else if (Seq == S_Release &&
2740                  (Class == IC_User || Class == IC_CallOrUser)) {
2741         // Non-movable releases depend on any possible objc pointer use.
2742         S.SetSeq(S_Stop);
2743         assert(S.RRI.ReverseInsertPts.empty());
2744         // As above; handle invoke specially.
2745         if (isa<InvokeInst>(Inst))
2746           S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2747         else
2748           S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2749       }
2750       break;
2751     case S_Stop:
2752       if (CanUse(Inst, Ptr, PA, Class))
2753         S.SetSeq(S_Use);
2754       break;
2755     case S_CanRelease:
2756     case S_Use:
2757     case S_None:
2758       break;
2759     case S_Retain:
2760       llvm_unreachable("bottom-up pointer in retain state!");
2761     }
2762   }
2763
2764   return NestingDetected;
2765 }
2766
2767 bool
2768 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2769                           DenseMap<const BasicBlock *, BBState> &BBStates,
2770                           MapVector<Value *, RRInfo> &Retains) {
2771   bool NestingDetected = false;
2772   BBState &MyStates = BBStates[BB];
2773
2774   // Merge the states from each successor to compute the initial state
2775   // for the current block.
2776   for (BBState::edge_iterator SI(MyStates.succ_begin()),
2777        SE(MyStates.succ_end()); SI != SE; ++SI) {
2778     const BasicBlock *Succ = *SI;
2779     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2780     assert(I != BBStates.end());
2781     MyStates.InitFromSucc(I->second);
2782     ++SI;
2783     for (; SI != SE; ++SI) {
2784       Succ = *SI;
2785       I = BBStates.find(Succ);
2786       assert(I != BBStates.end());
2787       MyStates.MergeSucc(I->second);
2788     }
2789     break;
2790   }
2791
2792   // Visit all the instructions, bottom-up.
2793   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2794     Instruction *Inst = llvm::prior(I);
2795
2796     // Invoke instructions are visited as part of their successors (below).
2797     if (isa<InvokeInst>(Inst))
2798       continue;
2799
2800     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2801   }
2802
2803   // If there's a predecessor with an invoke, visit the invoke as
2804   // if it were part of this block, since we can't insert code after
2805   // an invoke in its own block, and we don't want to split critical
2806   // edges.
2807   for (BBState::edge_iterator PI(MyStates.pred_begin()),
2808        PE(MyStates.pred_end()); PI != PE; ++PI) {
2809     BasicBlock *Pred = *PI;
2810     TerminatorInst *PredTI = cast<TerminatorInst>(&Pred->back());
2811     if (isa<InvokeInst>(PredTI))
2812       NestingDetected |= VisitInstructionBottomUp(PredTI, BB, Retains, MyStates);
2813   }
2814
2815   return NestingDetected;
2816 }
2817
2818 bool
2819 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2820                                     DenseMap<Value *, RRInfo> &Releases,
2821                                     BBState &MyStates) {
2822   bool NestingDetected = false;
2823   InstructionClass Class = GetInstructionClass(Inst);
2824   const Value *Arg = 0;
2825
2826   switch (Class) {
2827   case IC_RetainBlock:
2828     // An objc_retainBlock call with just a use may need to be kept,
2829     // because it may be copying a block from the stack to the heap.
2830     if (!IsRetainBlockOptimizable(Inst))
2831       break;
2832     // FALLTHROUGH
2833   case IC_Retain:
2834   case IC_RetainRV: {
2835     Arg = GetObjCArg(Inst);
2836
2837     PtrState &S = MyStates.getPtrTopDownState(Arg);
2838
2839     // Don't do retain+release tracking for IC_RetainRV, because it's
2840     // better to let it remain as the first instruction after a call.
2841     if (Class != IC_RetainRV) {
2842       // If we see two retains in a row on the same pointer. If so, make
2843       // a note, and we'll cicle back to revisit it after we've
2844       // hopefully eliminated the second retain, which may allow us to
2845       // eliminate the first retain too.
2846       // Theoretically we could implement removal of nested retain+release
2847       // pairs by making PtrState hold a stack of states, but this is
2848       // simple and avoids adding overhead for the non-nested case.
2849       if (S.GetSeq() == S_Retain)
2850         NestingDetected = true;
2851
2852       S.ResetSequenceProgress(S_Retain);
2853       S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2854       // Don't check S.IsKnownIncremented() here because it's not
2855       // sufficient.
2856       S.RRI.KnownSafe = S.IsKnownNested();
2857       S.RRI.Calls.insert(Inst);
2858     }
2859
2860     S.IncrementNestCount();
2861     return NestingDetected;
2862   }
2863   case IC_Release: {
2864     Arg = GetObjCArg(Inst);
2865
2866     PtrState &S = MyStates.getPtrTopDownState(Arg);
2867     S.DecrementNestCount();
2868
2869     switch (S.GetSeq()) {
2870     case S_Retain:
2871     case S_CanRelease:
2872       S.RRI.ReverseInsertPts.clear();
2873       // FALL THROUGH
2874     case S_Use:
2875       S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2876       S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2877       Releases[Inst] = S.RRI;
2878       S.ClearSequenceProgress();
2879       break;
2880     case S_None:
2881       break;
2882     case S_Stop:
2883     case S_Release:
2884     case S_MovableRelease:
2885       llvm_unreachable("top-down pointer in release state!");
2886     }
2887     break;
2888   }
2889   case IC_AutoreleasepoolPop:
2890     // Conservatively, clear MyStates for all known pointers.
2891     MyStates.clearTopDownPointers();
2892     return NestingDetected;
2893   case IC_AutoreleasepoolPush:
2894   case IC_None:
2895     // These are irrelevant.
2896     return NestingDetected;
2897   default:
2898     break;
2899   }
2900
2901   // Consider any other possible effects of this instruction on each
2902   // pointer being tracked.
2903   for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2904        ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2905     const Value *Ptr = MI->first;
2906     if (Ptr == Arg)
2907       continue; // Handled above.
2908     PtrState &S = MI->second;
2909     Sequence Seq = S.GetSeq();
2910
2911     // Check for possible releases.
2912     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2913       S.ClearRefCount();
2914       switch (Seq) {
2915       case S_Retain:
2916         S.SetSeq(S_CanRelease);
2917         assert(S.RRI.ReverseInsertPts.empty());
2918         S.RRI.ReverseInsertPts.insert(Inst);
2919
2920         // One call can't cause a transition from S_Retain to S_CanRelease
2921         // and S_CanRelease to S_Use. If we've made the first transition,
2922         // we're done.
2923         continue;
2924       case S_Use:
2925       case S_CanRelease:
2926       case S_None:
2927         break;
2928       case S_Stop:
2929       case S_Release:
2930       case S_MovableRelease:
2931         llvm_unreachable("top-down pointer in release state!");
2932       }
2933     }
2934
2935     // Check for possible direct uses.
2936     switch (Seq) {
2937     case S_CanRelease:
2938       if (CanUse(Inst, Ptr, PA, Class))
2939         S.SetSeq(S_Use);
2940       break;
2941     case S_Retain:
2942     case S_Use:
2943     case S_None:
2944       break;
2945     case S_Stop:
2946     case S_Release:
2947     case S_MovableRelease:
2948       llvm_unreachable("top-down pointer in release state!");
2949     }
2950   }
2951
2952   return NestingDetected;
2953 }
2954
2955 bool
2956 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2957                          DenseMap<const BasicBlock *, BBState> &BBStates,
2958                          DenseMap<Value *, RRInfo> &Releases) {
2959   bool NestingDetected = false;
2960   BBState &MyStates = BBStates[BB];
2961
2962   // Merge the states from each predecessor to compute the initial state
2963   // for the current block.
2964   for (BBState::edge_iterator PI(MyStates.pred_begin()),
2965        PE(MyStates.pred_end()); PI != PE; ++PI) {
2966     const BasicBlock *Pred = *PI;
2967     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2968     assert(I != BBStates.end());
2969     MyStates.InitFromPred(I->second);
2970     ++PI;
2971     for (; PI != PE; ++PI) {
2972       Pred = *PI;
2973       I = BBStates.find(Pred);
2974       assert(I != BBStates.end());
2975       MyStates.MergePred(I->second);
2976     }
2977     break;
2978   }
2979
2980   // Visit all the instructions, top-down.
2981   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2982     Instruction *Inst = I;
2983     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2984   }
2985
2986   CheckForCFGHazards(BB, BBStates, MyStates);
2987   return NestingDetected;
2988 }
2989
2990 static void
2991 ComputePostOrders(Function &F,
2992                   SmallVectorImpl<BasicBlock *> &PostOrder,
2993                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2994                   unsigned NoObjCARCExceptionsMDKind,
2995                   DenseMap<const BasicBlock *, BBState> &BBStates) {
2996   /// Visited - The visited set, for doing DFS walks.
2997   SmallPtrSet<BasicBlock *, 16> Visited;
2998
2999   // Do DFS, computing the PostOrder.
3000   SmallPtrSet<BasicBlock *, 16> OnStack;
3001   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3002
3003   // Functions always have exactly one entry block, and we don't have
3004   // any other block that we treat like an entry block.
3005   BasicBlock *EntryBB = &F.getEntryBlock();
3006   BBStates[EntryBB].SetAsEntry();
3007
3008   SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
3009   Visited.insert(EntryBB);
3010   OnStack.insert(EntryBB);
3011   do {
3012   dfs_next_succ:
3013     BasicBlock *CurrBB = SuccStack.back().first;
3014     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3015     succ_iterator SE(TI, false);
3016     
3017     // If the terminator is an invoke marked with the
3018     // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3019     // ignored, for ARC purposes.
3020     if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3021       --SE;
3022
3023     while (SuccStack.back().second != SE) {
3024       BasicBlock *SuccBB = *SuccStack.back().second++;
3025       if (Visited.insert(SuccBB)) {
3026         SuccStack.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
3027         BBStates[CurrBB].addSucc(SuccBB);
3028         BBStates[SuccBB].addPred(CurrBB);
3029         OnStack.insert(SuccBB);
3030         goto dfs_next_succ;
3031       }
3032
3033       if (!OnStack.count(SuccBB)) {
3034         BBStates[CurrBB].addSucc(SuccBB);
3035         BBStates[SuccBB].addPred(CurrBB);
3036       }
3037     }
3038     OnStack.erase(CurrBB);
3039     PostOrder.push_back(CurrBB);
3040     SuccStack.pop_back();
3041   } while (!SuccStack.empty());
3042
3043   Visited.clear();
3044
3045   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3046   // Functions may have many exits, and there also blocks which we treat
3047   // as exits due to ignored edges.
3048   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3049   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3050     BasicBlock *ExitBB = I;
3051     BBState &MyStates = BBStates[ExitBB];
3052     if (!MyStates.isExit())
3053       continue;
3054
3055     BBStates[ExitBB].SetAsExit();
3056
3057     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3058     Visited.insert(ExitBB);
3059     while (!PredStack.empty()) {
3060     reverse_dfs_next_succ:
3061       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3062       while (PredStack.back().second != PE) {
3063         BasicBlock *BB = *PredStack.back().second++;
3064         if (Visited.insert(BB)) {
3065           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3066           goto reverse_dfs_next_succ;
3067         }
3068       }
3069       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3070     }
3071   }
3072 }
3073
3074 // Visit - Visit the function both top-down and bottom-up.
3075 bool
3076 ObjCARCOpt::Visit(Function &F,
3077                   DenseMap<const BasicBlock *, BBState> &BBStates,
3078                   MapVector<Value *, RRInfo> &Retains,
3079                   DenseMap<Value *, RRInfo> &Releases) {
3080
3081   // Use reverse-postorder traversals, because we magically know that loops
3082   // will be well behaved, i.e. they won't repeatedly call retain on a single
3083   // pointer without doing a release. We can't use the ReversePostOrderTraversal
3084   // class here because we want the reverse-CFG postorder to consider each
3085   // function exit point, and we want to ignore selected cycle edges.
3086   SmallVector<BasicBlock *, 16> PostOrder;
3087   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3088   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3089                     NoObjCARCExceptionsMDKind,
3090                     BBStates);
3091
3092   // Use reverse-postorder on the reverse CFG for bottom-up.
3093   bool BottomUpNestingDetected = false;
3094   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3095        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3096        I != E; ++I)
3097     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3098
3099   // Use reverse-postorder for top-down.
3100   bool TopDownNestingDetected = false;
3101   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3102        PostOrder.rbegin(), E = PostOrder.rend();
3103        I != E; ++I)
3104     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3105
3106   return TopDownNestingDetected && BottomUpNestingDetected;
3107 }
3108
3109 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3110 void ObjCARCOpt::MoveCalls(Value *Arg,
3111                            RRInfo &RetainsToMove,
3112                            RRInfo &ReleasesToMove,
3113                            MapVector<Value *, RRInfo> &Retains,
3114                            DenseMap<Value *, RRInfo> &Releases,
3115                            SmallVectorImpl<Instruction *> &DeadInsts,
3116                            Module *M) {
3117   Type *ArgTy = Arg->getType();
3118   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3119
3120   // Insert the new retain and release calls.
3121   for (SmallPtrSet<Instruction *, 2>::const_iterator
3122        PI = ReleasesToMove.ReverseInsertPts.begin(),
3123        PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3124     Instruction *InsertPt = *PI;
3125     Value *MyArg = ArgTy == ParamTy ? Arg :
3126                    new BitCastInst(Arg, ParamTy, "", InsertPt);
3127     CallInst *Call =
3128       CallInst::Create(RetainsToMove.IsRetainBlock ?
3129                          getRetainBlockCallee(M) : getRetainCallee(M),
3130                        MyArg, "", InsertPt);
3131     Call->setDoesNotThrow();
3132     if (RetainsToMove.IsRetainBlock)
3133       Call->setMetadata(CopyOnEscapeMDKind,
3134                         MDNode::get(M->getContext(), ArrayRef<Value *>()));
3135     else
3136       Call->setTailCall();
3137   }
3138   for (SmallPtrSet<Instruction *, 2>::const_iterator
3139        PI = RetainsToMove.ReverseInsertPts.begin(),
3140        PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3141     Instruction *InsertPt = *PI;
3142     Value *MyArg = ArgTy == ParamTy ? Arg :
3143                    new BitCastInst(Arg, ParamTy, "", InsertPt);
3144     CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3145                                       "", InsertPt);
3146     // Attach a clang.imprecise_release metadata tag, if appropriate.
3147     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3148       Call->setMetadata(ImpreciseReleaseMDKind, M);
3149     Call->setDoesNotThrow();
3150     if (ReleasesToMove.IsTailCallRelease)
3151       Call->setTailCall();
3152   }
3153
3154   // Delete the original retain and release calls.
3155   for (SmallPtrSet<Instruction *, 2>::const_iterator
3156        AI = RetainsToMove.Calls.begin(),
3157        AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3158     Instruction *OrigRetain = *AI;
3159     Retains.blot(OrigRetain);
3160     DeadInsts.push_back(OrigRetain);
3161   }
3162   for (SmallPtrSet<Instruction *, 2>::const_iterator
3163        AI = ReleasesToMove.Calls.begin(),
3164        AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3165     Instruction *OrigRelease = *AI;
3166     Releases.erase(OrigRelease);
3167     DeadInsts.push_back(OrigRelease);
3168   }
3169 }
3170
3171 /// PerformCodePlacement - Identify pairings between the retains and releases,
3172 /// and delete and/or move them.
3173 bool
3174 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3175                                    &BBStates,
3176                                  MapVector<Value *, RRInfo> &Retains,
3177                                  DenseMap<Value *, RRInfo> &Releases,
3178                                  Module *M) {
3179   bool AnyPairsCompletelyEliminated = false;
3180   RRInfo RetainsToMove;
3181   RRInfo ReleasesToMove;
3182   SmallVector<Instruction *, 4> NewRetains;
3183   SmallVector<Instruction *, 4> NewReleases;
3184   SmallVector<Instruction *, 8> DeadInsts;
3185
3186   // Visit each retain.
3187   for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3188        E = Retains.end(); I != E; ++I) {
3189     Value *V = I->first;
3190     if (!V) continue; // blotted
3191
3192     Instruction *Retain = cast<Instruction>(V);
3193     Value *Arg = GetObjCArg(Retain);
3194
3195     // If the object being released is in static or stack storage, we know it's
3196     // not being managed by ObjC reference counting, so we can delete pairs
3197     // regardless of what possible decrements or uses lie between them.
3198     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3199    
3200     // A constant pointer can't be pointing to an object on the heap. It may
3201     // be reference-counted, but it won't be deleted.
3202     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3203       if (const GlobalVariable *GV =
3204             dyn_cast<GlobalVariable>(
3205               StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3206         if (GV->isConstant())
3207           KnownSafe = true;
3208
3209     // If a pair happens in a region where it is known that the reference count
3210     // is already incremented, we can similarly ignore possible decrements.
3211     bool KnownSafeTD = true, KnownSafeBU = true;
3212
3213     // Connect the dots between the top-down-collected RetainsToMove and
3214     // bottom-up-collected ReleasesToMove to form sets of related calls.
3215     // This is an iterative process so that we connect multiple releases
3216     // to multiple retains if needed.
3217     unsigned OldDelta = 0;
3218     unsigned NewDelta = 0;
3219     unsigned OldCount = 0;
3220     unsigned NewCount = 0;
3221     bool FirstRelease = true;
3222     bool FirstRetain = true;
3223     NewRetains.push_back(Retain);
3224     for (;;) {
3225       for (SmallVectorImpl<Instruction *>::const_iterator
3226            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3227         Instruction *NewRetain = *NI;
3228         MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3229         assert(It != Retains.end());
3230         const RRInfo &NewRetainRRI = It->second;
3231         KnownSafeTD &= NewRetainRRI.KnownSafe;
3232         for (SmallPtrSet<Instruction *, 2>::const_iterator
3233              LI = NewRetainRRI.Calls.begin(),
3234              LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3235           Instruction *NewRetainRelease = *LI;
3236           DenseMap<Value *, RRInfo>::const_iterator Jt =
3237             Releases.find(NewRetainRelease);
3238           if (Jt == Releases.end())
3239             goto next_retain;
3240           const RRInfo &NewRetainReleaseRRI = Jt->second;
3241           assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3242           if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3243             OldDelta -=
3244               BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3245
3246             // Merge the ReleaseMetadata and IsTailCallRelease values.
3247             if (FirstRelease) {
3248               ReleasesToMove.ReleaseMetadata =
3249                 NewRetainReleaseRRI.ReleaseMetadata;
3250               ReleasesToMove.IsTailCallRelease =
3251                 NewRetainReleaseRRI.IsTailCallRelease;
3252               FirstRelease = false;
3253             } else {
3254               if (ReleasesToMove.ReleaseMetadata !=
3255                     NewRetainReleaseRRI.ReleaseMetadata)
3256                 ReleasesToMove.ReleaseMetadata = 0;
3257               if (ReleasesToMove.IsTailCallRelease !=
3258                     NewRetainReleaseRRI.IsTailCallRelease)
3259                 ReleasesToMove.IsTailCallRelease = false;
3260             }
3261
3262             // Collect the optimal insertion points.
3263             if (!KnownSafe)
3264               for (SmallPtrSet<Instruction *, 2>::const_iterator
3265                    RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3266                    RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3267                    RI != RE; ++RI) {
3268                 Instruction *RIP = *RI;
3269                 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3270                   NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3271               }
3272             NewReleases.push_back(NewRetainRelease);
3273           }
3274         }
3275       }
3276       NewRetains.clear();
3277       if (NewReleases.empty()) break;
3278
3279       // Back the other way.
3280       for (SmallVectorImpl<Instruction *>::const_iterator
3281            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3282         Instruction *NewRelease = *NI;
3283         DenseMap<Value *, RRInfo>::const_iterator It =
3284           Releases.find(NewRelease);
3285         assert(It != Releases.end());
3286         const RRInfo &NewReleaseRRI = It->second;
3287         KnownSafeBU &= NewReleaseRRI.KnownSafe;
3288         for (SmallPtrSet<Instruction *, 2>::const_iterator
3289              LI = NewReleaseRRI.Calls.begin(),
3290              LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3291           Instruction *NewReleaseRetain = *LI;
3292           MapVector<Value *, RRInfo>::const_iterator Jt =
3293             Retains.find(NewReleaseRetain);
3294           if (Jt == Retains.end())
3295             goto next_retain;
3296           const RRInfo &NewReleaseRetainRRI = Jt->second;
3297           assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3298           if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3299             unsigned PathCount =
3300               BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3301             OldDelta += PathCount;
3302             OldCount += PathCount;
3303
3304             // Merge the IsRetainBlock values.
3305             if (FirstRetain) {
3306               RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3307               FirstRetain = false;
3308             } else if (ReleasesToMove.IsRetainBlock !=
3309                        NewReleaseRetainRRI.IsRetainBlock)
3310               // It's not possible to merge the sequences if one uses
3311               // objc_retain and the other uses objc_retainBlock.
3312               goto next_retain;
3313
3314             // Collect the optimal insertion points.
3315             if (!KnownSafe)
3316               for (SmallPtrSet<Instruction *, 2>::const_iterator
3317                    RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3318                    RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3319                    RI != RE; ++RI) {
3320                 Instruction *RIP = *RI;
3321                 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3322                   PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3323                   NewDelta += PathCount;
3324                   NewCount += PathCount;
3325                 }
3326               }
3327             NewRetains.push_back(NewReleaseRetain);
3328           }
3329         }
3330       }
3331       NewReleases.clear();
3332       if (NewRetains.empty()) break;
3333     }
3334
3335     // If the pointer is known incremented or nested, we can safely delete the
3336     // pair regardless of what's between them.
3337     if (KnownSafeTD || KnownSafeBU) {
3338       RetainsToMove.ReverseInsertPts.clear();
3339       ReleasesToMove.ReverseInsertPts.clear();
3340       NewCount = 0;
3341     } else {
3342       // Determine whether the new insertion points we computed preserve the
3343       // balance of retain and release calls through the program.
3344       // TODO: If the fully aggressive solution isn't valid, try to find a
3345       // less aggressive solution which is.
3346       if (NewDelta != 0)
3347         goto next_retain;
3348     }
3349
3350     // Determine whether the original call points are balanced in the retain and
3351     // release calls through the program. If not, conservatively don't touch
3352     // them.
3353     // TODO: It's theoretically possible to do code motion in this case, as
3354     // long as the existing imbalances are maintained.
3355     if (OldDelta != 0)
3356       goto next_retain;
3357
3358     // Ok, everything checks out and we're all set. Let's move some code!
3359     Changed = true;
3360     assert(OldCount != 0 && "Unreachable code?");
3361     AnyPairsCompletelyEliminated = NewCount == 0;
3362     NumRRs += OldCount - NewCount;
3363     MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3364               Retains, Releases, DeadInsts, M);
3365
3366   next_retain:
3367     NewReleases.clear();
3368     NewRetains.clear();
3369     RetainsToMove.clear();
3370     ReleasesToMove.clear();
3371   }
3372
3373   // Now that we're done moving everything, we can delete the newly dead
3374   // instructions, as we no longer need them as insert points.
3375   while (!DeadInsts.empty())
3376     EraseInstruction(DeadInsts.pop_back_val());
3377
3378   return AnyPairsCompletelyEliminated;
3379 }
3380
3381 /// OptimizeWeakCalls - Weak pointer optimizations.
3382 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3383   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3384   // itself because it uses AliasAnalysis and we need to do provenance
3385   // queries instead.
3386   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3387     Instruction *Inst = &*I++;
3388     InstructionClass Class = GetBasicInstructionClass(Inst);
3389     if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3390       continue;
3391
3392     // Delete objc_loadWeak calls with no users.
3393     if (Class == IC_LoadWeak && Inst->use_empty()) {
3394       Inst->eraseFromParent();
3395       continue;
3396     }
3397
3398     // TODO: For now, just look for an earlier available version of this value
3399     // within the same block. Theoretically, we could do memdep-style non-local
3400     // analysis too, but that would want caching. A better approach would be to
3401     // use the technique that EarlyCSE uses.
3402     inst_iterator Current = llvm::prior(I);
3403     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3404     for (BasicBlock::iterator B = CurrentBB->begin(),
3405                               J = Current.getInstructionIterator();
3406          J != B; --J) {
3407       Instruction *EarlierInst = &*llvm::prior(J);
3408       InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3409       switch (EarlierClass) {
3410       case IC_LoadWeak:
3411       case IC_LoadWeakRetained: {
3412         // If this is loading from the same pointer, replace this load's value
3413         // with that one.
3414         CallInst *Call = cast<CallInst>(Inst);
3415         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3416         Value *Arg = Call->getArgOperand(0);
3417         Value *EarlierArg = EarlierCall->getArgOperand(0);
3418         switch (PA.getAA()->alias(Arg, EarlierArg)) {
3419         case AliasAnalysis::MustAlias:
3420           Changed = true;
3421           // If the load has a builtin retain, insert a plain retain for it.
3422           if (Class == IC_LoadWeakRetained) {
3423             CallInst *CI =
3424               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3425                                "", Call);
3426             CI->setTailCall();
3427           }
3428           // Zap the fully redundant load.
3429           Call->replaceAllUsesWith(EarlierCall);
3430           Call->eraseFromParent();
3431           goto clobbered;
3432         case AliasAnalysis::MayAlias:
3433         case AliasAnalysis::PartialAlias:
3434           goto clobbered;
3435         case AliasAnalysis::NoAlias:
3436           break;
3437         }
3438         break;
3439       }
3440       case IC_StoreWeak:
3441       case IC_InitWeak: {
3442         // If this is storing to the same pointer and has the same size etc.
3443         // replace this load's value with the stored value.
3444         CallInst *Call = cast<CallInst>(Inst);
3445         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3446         Value *Arg = Call->getArgOperand(0);
3447         Value *EarlierArg = EarlierCall->getArgOperand(0);
3448         switch (PA.getAA()->alias(Arg, EarlierArg)) {
3449         case AliasAnalysis::MustAlias:
3450           Changed = true;
3451           // If the load has a builtin retain, insert a plain retain for it.
3452           if (Class == IC_LoadWeakRetained) {
3453             CallInst *CI =
3454               CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3455                                "", Call);
3456             CI->setTailCall();
3457           }
3458           // Zap the fully redundant load.
3459           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3460           Call->eraseFromParent();
3461           goto clobbered;
3462         case AliasAnalysis::MayAlias:
3463         case AliasAnalysis::PartialAlias:
3464           goto clobbered;
3465         case AliasAnalysis::NoAlias:
3466           break;
3467         }
3468         break;
3469       }
3470       case IC_MoveWeak:
3471       case IC_CopyWeak:
3472         // TOOD: Grab the copied value.
3473         goto clobbered;
3474       case IC_AutoreleasepoolPush:
3475       case IC_None:
3476       case IC_User:
3477         // Weak pointers are only modified through the weak entry points
3478         // (and arbitrary calls, which could call the weak entry points).
3479         break;
3480       default:
3481         // Anything else could modify the weak pointer.
3482         goto clobbered;
3483       }
3484     }
3485   clobbered:;
3486   }
3487
3488   // Then, for each destroyWeak with an alloca operand, check to see if
3489   // the alloca and all its users can be zapped.
3490   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3491     Instruction *Inst = &*I++;
3492     InstructionClass Class = GetBasicInstructionClass(Inst);
3493     if (Class != IC_DestroyWeak)
3494       continue;
3495
3496     CallInst *Call = cast<CallInst>(Inst);
3497     Value *Arg = Call->getArgOperand(0);
3498     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3499       for (Value::use_iterator UI = Alloca->use_begin(),
3500            UE = Alloca->use_end(); UI != UE; ++UI) {
3501         Instruction *UserInst = cast<Instruction>(*UI);
3502         switch (GetBasicInstructionClass(UserInst)) {
3503         case IC_InitWeak:
3504         case IC_StoreWeak:
3505         case IC_DestroyWeak:
3506           continue;
3507         default:
3508           goto done;
3509         }
3510       }
3511       Changed = true;
3512       for (Value::use_iterator UI = Alloca->use_begin(),
3513            UE = Alloca->use_end(); UI != UE; ) {
3514         CallInst *UserInst = cast<CallInst>(*UI++);
3515         if (!UserInst->use_empty())
3516           UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3517         UserInst->eraseFromParent();
3518       }
3519       Alloca->eraseFromParent();
3520     done:;
3521     }
3522   }
3523 }
3524
3525 /// OptimizeSequences - Identify program paths which execute sequences of
3526 /// retains and releases which can be eliminated.
3527 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3528   /// Releases, Retains - These are used to store the results of the main flow
3529   /// analysis. These use Value* as the key instead of Instruction* so that the
3530   /// map stays valid when we get around to rewriting code and calls get
3531   /// replaced by arguments.
3532   DenseMap<Value *, RRInfo> Releases;
3533   MapVector<Value *, RRInfo> Retains;
3534
3535   /// BBStates, This is used during the traversal of the function to track the
3536   /// states for each identified object at each block.
3537   DenseMap<const BasicBlock *, BBState> BBStates;
3538
3539   // Analyze the CFG of the function, and all instructions.
3540   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3541
3542   // Transform.
3543   return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3544          NestingDetected;
3545 }
3546
3547 /// OptimizeReturns - Look for this pattern:
3548 ///
3549 ///    %call = call i8* @something(...)
3550 ///    %2 = call i8* @objc_retain(i8* %call)
3551 ///    %3 = call i8* @objc_autorelease(i8* %2)
3552 ///    ret i8* %3
3553 ///
3554 /// And delete the retain and autorelease.
3555 ///
3556 /// Otherwise if it's just this:
3557 ///
3558 ///    %3 = call i8* @objc_autorelease(i8* %2)
3559 ///    ret i8* %3
3560 ///
3561 /// convert the autorelease to autoreleaseRV.
3562 void ObjCARCOpt::OptimizeReturns(Function &F) {
3563   if (!F.getReturnType()->isPointerTy())
3564     return;
3565
3566   SmallPtrSet<Instruction *, 4> DependingInstructions;
3567   SmallPtrSet<const BasicBlock *, 4> Visited;
3568   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3569     BasicBlock *BB = FI;
3570     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3571     if (!Ret) continue;
3572
3573     const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3574     FindDependencies(NeedsPositiveRetainCount, Arg,
3575                      BB, Ret, DependingInstructions, Visited, PA);
3576     if (DependingInstructions.size() != 1)
3577       goto next_block;
3578
3579     {
3580       CallInst *Autorelease =
3581         dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3582       if (!Autorelease)
3583         goto next_block;
3584       InstructionClass AutoreleaseClass =
3585         GetBasicInstructionClass(Autorelease);
3586       if (!IsAutorelease(AutoreleaseClass))
3587         goto next_block;
3588       if (GetObjCArg(Autorelease) != Arg)
3589         goto next_block;
3590
3591       DependingInstructions.clear();
3592       Visited.clear();
3593
3594       // Check that there is nothing that can affect the reference
3595       // count between the autorelease and the retain.
3596       FindDependencies(CanChangeRetainCount, Arg,
3597                        BB, Autorelease, DependingInstructions, Visited, PA);
3598       if (DependingInstructions.size() != 1)
3599         goto next_block;
3600
3601       {
3602         CallInst *Retain =
3603           dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3604
3605         // Check that we found a retain with the same argument.
3606         if (!Retain ||
3607             !IsRetain(GetBasicInstructionClass(Retain)) ||
3608             GetObjCArg(Retain) != Arg)
3609           goto next_block;
3610
3611         DependingInstructions.clear();
3612         Visited.clear();
3613
3614         // Convert the autorelease to an autoreleaseRV, since it's
3615         // returning the value.
3616         if (AutoreleaseClass == IC_Autorelease) {
3617           Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3618           AutoreleaseClass = IC_AutoreleaseRV;
3619         }
3620
3621         // Check that there is nothing that can affect the reference
3622         // count between the retain and the call.
3623         // Note that Retain need not be in BB.
3624         FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3625                          DependingInstructions, Visited, PA);
3626         if (DependingInstructions.size() != 1)
3627           goto next_block;
3628
3629         {
3630           CallInst *Call =
3631             dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3632
3633           // Check that the pointer is the return value of the call.
3634           if (!Call || Arg != Call)
3635             goto next_block;
3636
3637           // Check that the call is a regular call.
3638           InstructionClass Class = GetBasicInstructionClass(Call);
3639           if (Class != IC_CallOrUser && Class != IC_Call)
3640             goto next_block;
3641
3642           // If so, we can zap the retain and autorelease.
3643           Changed = true;
3644           ++NumRets;
3645           EraseInstruction(Retain);
3646           EraseInstruction(Autorelease);
3647         }
3648       }
3649     }
3650
3651   next_block:
3652     DependingInstructions.clear();
3653     Visited.clear();
3654   }
3655 }
3656
3657 bool ObjCARCOpt::doInitialization(Module &M) {
3658   if (!EnableARCOpts)
3659     return false;
3660
3661   // If nothing in the Module uses ARC, don't do anything.
3662   Run = ModuleHasARC(M);
3663   if (!Run)
3664     return false;
3665
3666   // Identify the imprecise release metadata kind.
3667   ImpreciseReleaseMDKind =
3668     M.getContext().getMDKindID("clang.imprecise_release");
3669   CopyOnEscapeMDKind =
3670     M.getContext().getMDKindID("clang.arc.copy_on_escape");
3671   NoObjCARCExceptionsMDKind =
3672     M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3673
3674   // Intuitively, objc_retain and others are nocapture, however in practice
3675   // they are not, because they return their argument value. And objc_release
3676   // calls finalizers.
3677
3678   // These are initialized lazily.
3679   RetainRVCallee = 0;
3680   AutoreleaseRVCallee = 0;
3681   ReleaseCallee = 0;
3682   RetainCallee = 0;
3683   RetainBlockCallee = 0;
3684   AutoreleaseCallee = 0;
3685
3686   return false;
3687 }
3688
3689 bool ObjCARCOpt::runOnFunction(Function &F) {
3690   if (!EnableARCOpts)
3691     return false;
3692
3693   // If nothing in the Module uses ARC, don't do anything.
3694   if (!Run)
3695     return false;
3696
3697   Changed = false;
3698
3699   PA.setAA(&getAnalysis<AliasAnalysis>());
3700
3701   // This pass performs several distinct transformations. As a compile-time aid
3702   // when compiling code that isn't ObjC, skip these if the relevant ObjC
3703   // library functions aren't declared.
3704
3705   // Preliminary optimizations. This also computs UsedInThisFunction.
3706   OptimizeIndividualCalls(F);
3707
3708   // Optimizations for weak pointers.
3709   if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3710                             (1 << IC_LoadWeakRetained) |
3711                             (1 << IC_StoreWeak) |
3712                             (1 << IC_InitWeak) |
3713                             (1 << IC_CopyWeak) |
3714                             (1 << IC_MoveWeak) |
3715                             (1 << IC_DestroyWeak)))
3716     OptimizeWeakCalls(F);
3717
3718   // Optimizations for retain+release pairs.
3719   if (UsedInThisFunction & ((1 << IC_Retain) |
3720                             (1 << IC_RetainRV) |
3721                             (1 << IC_RetainBlock)))
3722     if (UsedInThisFunction & (1 << IC_Release))
3723       // Run OptimizeSequences until it either stops making changes or
3724       // no retain+release pair nesting is detected.
3725       while (OptimizeSequences(F)) {}
3726
3727   // Optimizations if objc_autorelease is used.
3728   if (UsedInThisFunction &
3729       ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3730     OptimizeReturns(F);
3731
3732   return Changed;
3733 }
3734
3735 void ObjCARCOpt::releaseMemory() {
3736   PA.clear();
3737 }
3738
3739 //===----------------------------------------------------------------------===//
3740 // ARC contraction.
3741 //===----------------------------------------------------------------------===//
3742
3743 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3744 // dominated by single calls.
3745
3746 #include "llvm/Operator.h"
3747 #include "llvm/InlineAsm.h"
3748 #include "llvm/Analysis/Dominators.h"
3749
3750 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3751
3752 namespace {
3753   /// ObjCARCContract - Late ARC optimizations.  These change the IR in a way
3754   /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3755   class ObjCARCContract : public FunctionPass {
3756     bool Changed;
3757     AliasAnalysis *AA;
3758     DominatorTree *DT;
3759     ProvenanceAnalysis PA;
3760
3761     /// Run - A flag indicating whether this optimization pass should run.
3762     bool Run;
3763
3764     /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3765     /// functions, for use in creating calls to them. These are initialized
3766     /// lazily to avoid cluttering up the Module with unused declarations.
3767     Constant *StoreStrongCallee,
3768              *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3769
3770     /// RetainRVMarker - The inline asm string to insert between calls and
3771     /// RetainRV calls to make the optimization work on targets which need it.
3772     const MDString *RetainRVMarker;
3773
3774     /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3775     /// at the end of walking the function we have found no alloca
3776     /// instructions, these calls can be marked "tail".
3777     DenseSet<CallInst *> StoreStrongCalls;
3778
3779     Constant *getStoreStrongCallee(Module *M);
3780     Constant *getRetainAutoreleaseCallee(Module *M);
3781     Constant *getRetainAutoreleaseRVCallee(Module *M);
3782
3783     bool ContractAutorelease(Function &F, Instruction *Autorelease,
3784                              InstructionClass Class,
3785                              SmallPtrSet<Instruction *, 4>
3786                                &DependingInstructions,
3787                              SmallPtrSet<const BasicBlock *, 4>
3788                                &Visited);
3789
3790     void ContractRelease(Instruction *Release,
3791                          inst_iterator &Iter);
3792
3793     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3794     virtual bool doInitialization(Module &M);
3795     virtual bool runOnFunction(Function &F);
3796
3797   public:
3798     static char ID;
3799     ObjCARCContract() : FunctionPass(ID) {
3800       initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3801     }
3802   };
3803 }
3804
3805 char ObjCARCContract::ID = 0;
3806 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3807                       "objc-arc-contract", "ObjC ARC contraction", false, false)
3808 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3809 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3810 INITIALIZE_PASS_END(ObjCARCContract,
3811                     "objc-arc-contract", "ObjC ARC contraction", false, false)
3812
3813 Pass *llvm::createObjCARCContractPass() {
3814   return new ObjCARCContract();
3815 }
3816
3817 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3818   AU.addRequired<AliasAnalysis>();
3819   AU.addRequired<DominatorTree>();
3820   AU.setPreservesCFG();
3821 }
3822
3823 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3824   if (!StoreStrongCallee) {
3825     LLVMContext &C = M->getContext();
3826     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3827     Type *I8XX = PointerType::getUnqual(I8X);
3828     std::vector<Type *> Params;
3829     Params.push_back(I8XX);
3830     Params.push_back(I8X);
3831
3832     AttrListPtr Attributes;
3833     Attributes.addAttr(~0u, Attribute::NoUnwind);
3834     Attributes.addAttr(1, Attribute::NoCapture);
3835
3836     StoreStrongCallee =
3837       M->getOrInsertFunction(
3838         "objc_storeStrong",
3839         FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3840         Attributes);
3841   }
3842   return StoreStrongCallee;
3843 }
3844
3845 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3846   if (!RetainAutoreleaseCallee) {
3847     LLVMContext &C = M->getContext();
3848     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3849     std::vector<Type *> Params;
3850     Params.push_back(I8X);
3851     FunctionType *FTy =
3852       FunctionType::get(I8X, Params, /*isVarArg=*/false);
3853     AttrListPtr Attributes;
3854     Attributes.addAttr(~0u, Attribute::NoUnwind);
3855     RetainAutoreleaseCallee =
3856       M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3857   }
3858   return RetainAutoreleaseCallee;
3859 }
3860
3861 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3862   if (!RetainAutoreleaseRVCallee) {
3863     LLVMContext &C = M->getContext();
3864     Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3865     std::vector<Type *> Params;
3866     Params.push_back(I8X);
3867     FunctionType *FTy =
3868       FunctionType::get(I8X, Params, /*isVarArg=*/false);
3869     AttrListPtr Attributes;
3870     Attributes.addAttr(~0u, Attribute::NoUnwind);
3871     RetainAutoreleaseRVCallee =
3872       M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3873                              Attributes);
3874   }
3875   return RetainAutoreleaseRVCallee;
3876 }
3877
3878 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3879 /// call.
3880 bool
3881 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3882                                      InstructionClass Class,
3883                                      SmallPtrSet<Instruction *, 4>
3884                                        &DependingInstructions,
3885                                      SmallPtrSet<const BasicBlock *, 4>
3886                                        &Visited) {
3887   const Value *Arg = GetObjCArg(Autorelease);
3888
3889   // Check that there are no instructions between the retain and the autorelease
3890   // (such as an autorelease_pop) which may change the count.
3891   CallInst *Retain = 0;
3892   if (Class == IC_AutoreleaseRV)
3893     FindDependencies(RetainAutoreleaseRVDep, Arg,
3894                      Autorelease->getParent(), Autorelease,
3895                      DependingInstructions, Visited, PA);
3896   else
3897     FindDependencies(RetainAutoreleaseDep, Arg,
3898                      Autorelease->getParent(), Autorelease,
3899                      DependingInstructions, Visited, PA);
3900
3901   Visited.clear();
3902   if (DependingInstructions.size() != 1) {
3903     DependingInstructions.clear();
3904     return false;
3905   }
3906
3907   Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3908   DependingInstructions.clear();
3909
3910   if (!Retain ||
3911       GetBasicInstructionClass(Retain) != IC_Retain ||
3912       GetObjCArg(Retain) != Arg)
3913     return false;
3914
3915   Changed = true;
3916   ++NumPeeps;
3917
3918   if (Class == IC_AutoreleaseRV)
3919     Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3920   else
3921     Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3922
3923   EraseInstruction(Autorelease);
3924   return true;
3925 }
3926
3927 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3928 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3929 /// the instructions don't always appear in order, and there may be unrelated
3930 /// intervening instructions.
3931 void ObjCARCContract::ContractRelease(Instruction *Release,
3932                                       inst_iterator &Iter) {
3933   LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3934   if (!Load || !Load->isSimple()) return;
3935
3936   // For now, require everything to be in one basic block.
3937   BasicBlock *BB = Release->getParent();
3938   if (Load->getParent() != BB) return;
3939
3940   // Walk down to find the store.
3941   BasicBlock::iterator I = Load, End = BB->end();
3942   ++I;
3943   AliasAnalysis::Location Loc = AA->getLocation(Load);
3944   while (I != End &&
3945          (&*I == Release ||
3946           IsRetain(GetBasicInstructionClass(I)) ||
3947           !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3948     ++I;
3949   StoreInst *Store = dyn_cast<StoreInst>(I);
3950   if (!Store || !Store->isSimple()) return;
3951   if (Store->getPointerOperand() != Loc.Ptr) return;
3952
3953   Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3954
3955   // Walk up to find the retain.
3956   I = Store;
3957   BasicBlock::iterator Begin = BB->begin();
3958   while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3959     --I;
3960   Instruction *Retain = I;
3961   if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3962   if (GetObjCArg(Retain) != New) return;
3963
3964   Changed = true;
3965   ++NumStoreStrongs;
3966
3967   LLVMContext &C = Release->getContext();
3968   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3969   Type *I8XX = PointerType::getUnqual(I8X);
3970
3971   Value *Args[] = { Load->getPointerOperand(), New };
3972   if (Args[0]->getType() != I8XX)
3973     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3974   if (Args[1]->getType() != I8X)
3975     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3976   CallInst *StoreStrong =
3977     CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3978                      Args, "", Store);
3979   StoreStrong->setDoesNotThrow();
3980   StoreStrong->setDebugLoc(Store->getDebugLoc());
3981
3982   // We can't set the tail flag yet, because we haven't yet determined
3983   // whether there are any escaping allocas. Remember this call, so that
3984   // we can set the tail flag once we know it's safe.
3985   StoreStrongCalls.insert(StoreStrong);
3986
3987   if (&*Iter == Store) ++Iter;
3988   Store->eraseFromParent();
3989   Release->eraseFromParent();
3990   EraseInstruction(Retain);
3991   if (Load->use_empty())
3992     Load->eraseFromParent();
3993 }
3994
3995 bool ObjCARCContract::doInitialization(Module &M) {
3996   // If nothing in the Module uses ARC, don't do anything.
3997   Run = ModuleHasARC(M);
3998   if (!Run)
3999     return false;
4000
4001   // These are initialized lazily.
4002   StoreStrongCallee = 0;
4003   RetainAutoreleaseCallee = 0;
4004   RetainAutoreleaseRVCallee = 0;
4005
4006   // Initialize RetainRVMarker.
4007   RetainRVMarker = 0;
4008   if (NamedMDNode *NMD =
4009         M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4010     if (NMD->getNumOperands() == 1) {
4011       const MDNode *N = NMD->getOperand(0);
4012       if (N->getNumOperands() == 1)
4013         if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4014           RetainRVMarker = S;
4015     }
4016
4017   return false;
4018 }
4019
4020 bool ObjCARCContract::runOnFunction(Function &F) {
4021   if (!EnableARCOpts)
4022     return false;
4023
4024   // If nothing in the Module uses ARC, don't do anything.
4025   if (!Run)
4026     return false;
4027
4028   Changed = false;
4029   AA = &getAnalysis<AliasAnalysis>();
4030   DT = &getAnalysis<DominatorTree>();
4031
4032   PA.setAA(&getAnalysis<AliasAnalysis>());
4033
4034   // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4035   // keyword. Be conservative if the function has variadic arguments.
4036   // It seems that functions which "return twice" are also unsafe for the
4037   // "tail" argument, because they are setjmp, which could need to
4038   // return to an earlier stack state.
4039   bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
4040
4041   // For ObjC library calls which return their argument, replace uses of the
4042   // argument with uses of the call return value, if it dominates the use. This
4043   // reduces register pressure.
4044   SmallPtrSet<Instruction *, 4> DependingInstructions;
4045   SmallPtrSet<const BasicBlock *, 4> Visited;
4046   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4047     Instruction *Inst = &*I++;
4048
4049     // Only these library routines return their argument. In particular,
4050     // objc_retainBlock does not necessarily return its argument.
4051     InstructionClass Class = GetBasicInstructionClass(Inst);
4052     switch (Class) {
4053     case IC_Retain:
4054     case IC_FusedRetainAutorelease:
4055     case IC_FusedRetainAutoreleaseRV:
4056       break;
4057     case IC_Autorelease:
4058     case IC_AutoreleaseRV:
4059       if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4060         continue;
4061       break;
4062     case IC_RetainRV: {
4063       // If we're compiling for a target which needs a special inline-asm
4064       // marker to do the retainAutoreleasedReturnValue optimization,
4065       // insert it now.
4066       if (!RetainRVMarker)
4067         break;
4068       BasicBlock::iterator BBI = Inst;
4069       --BBI;
4070       while (isNoopInstruction(BBI)) --BBI;
4071       if (&*BBI == GetObjCArg(Inst)) {
4072         Changed = true;
4073         InlineAsm *IA =
4074           InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4075                                            /*isVarArg=*/false),
4076                          RetainRVMarker->getString(),
4077                          /*Constraints=*/"", /*hasSideEffects=*/true);
4078         CallInst::Create(IA, "", Inst);
4079       }
4080       break;
4081     }
4082     case IC_InitWeak: {
4083       // objc_initWeak(p, null) => *p = null
4084       CallInst *CI = cast<CallInst>(Inst);
4085       if (isNullOrUndef(CI->getArgOperand(1))) {
4086         Value *Null =
4087           ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4088         Changed = true;
4089         new StoreInst(Null, CI->getArgOperand(0), CI);
4090         CI->replaceAllUsesWith(Null);
4091         CI->eraseFromParent();
4092       }
4093       continue;
4094     }
4095     case IC_Release:
4096       ContractRelease(Inst, I);
4097       continue;
4098     case IC_User:
4099       // Be conservative if the function has any alloca instructions.
4100       // Technically we only care about escaping alloca instructions,
4101       // but this is sufficient to handle some interesting cases.
4102       if (isa<AllocaInst>(Inst))
4103         TailOkForStoreStrongs = false;
4104       continue;
4105     default:
4106       continue;
4107     }
4108
4109     // Don't use GetObjCArg because we don't want to look through bitcasts
4110     // and such; to do the replacement, the argument must have type i8*.
4111     const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4112     for (;;) {
4113       // If we're compiling bugpointed code, don't get in trouble.
4114       if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4115         break;
4116       // Look through the uses of the pointer.
4117       for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4118            UI != UE; ) {
4119         Use &U = UI.getUse();
4120         unsigned OperandNo = UI.getOperandNo();
4121         ++UI; // Increment UI now, because we may unlink its element.
4122
4123         // If the call's return value dominates a use of the call's argument
4124         // value, rewrite the use to use the return value. We check for
4125         // reachability here because an unreachable call is considered to
4126         // trivially dominate itself, which would lead us to rewriting its
4127         // argument in terms of its return value, which would lead to
4128         // infinite loops in GetObjCArg.
4129         if (DT->isReachableFromEntry(U) &&
4130             DT->dominates(Inst, U)) {
4131           Changed = true;
4132           Instruction *Replacement = Inst;
4133           Type *UseTy = U.get()->getType();
4134           if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4135             // For PHI nodes, insert the bitcast in the predecessor block.
4136             unsigned ValNo =
4137               PHINode::getIncomingValueNumForOperand(OperandNo);
4138             BasicBlock *BB =
4139               PHI->getIncomingBlock(ValNo);
4140             if (Replacement->getType() != UseTy)
4141               Replacement = new BitCastInst(Replacement, UseTy, "",
4142                                             &BB->back());
4143             // While we're here, rewrite all edges for this PHI, rather
4144             // than just one use at a time, to minimize the number of
4145             // bitcasts we emit.
4146             for (unsigned i = 0, e = PHI->getNumIncomingValues();
4147                  i != e; ++i)
4148               if (PHI->getIncomingBlock(i) == BB) {
4149                 // Keep the UI iterator valid.
4150                 if (&PHI->getOperandUse(
4151                       PHINode::getOperandNumForIncomingValue(i)) ==
4152                     &UI.getUse())
4153                   ++UI;
4154                 PHI->setIncomingValue(i, Replacement);
4155               }
4156           } else {
4157             if (Replacement->getType() != UseTy)
4158               Replacement = new BitCastInst(Replacement, UseTy, "",
4159                                             cast<Instruction>(U.getUser()));
4160             U.set(Replacement);
4161           }
4162         }
4163       }
4164
4165       // If Arg is a no-op casted pointer, strip one level of casts and
4166       // iterate.
4167       if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4168         Arg = BI->getOperand(0);
4169       else if (isa<GEPOperator>(Arg) &&
4170                cast<GEPOperator>(Arg)->hasAllZeroIndices())
4171         Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4172       else if (isa<GlobalAlias>(Arg) &&
4173                !cast<GlobalAlias>(Arg)->mayBeOverridden())
4174         Arg = cast<GlobalAlias>(Arg)->getAliasee();
4175       else
4176         break;
4177     }
4178   }
4179
4180   // If this function has no escaping allocas or suspicious vararg usage,
4181   // objc_storeStrong calls can be marked with the "tail" keyword.
4182   if (TailOkForStoreStrongs)
4183     for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
4184          E = StoreStrongCalls.end(); I != E; ++I)
4185       (*I)->setTailCall();
4186   StoreStrongCalls.clear();
4187
4188   return Changed;
4189 }