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