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