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