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