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