1 //===- ObjCARCOpts.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, and numerous minor simplifications.
17 ///
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
20 ///
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
24 ///
25 //===----------------------------------------------------------------------===//
26 
27 #include "ARCRuntimeEntryPoints.h"
28 #include "BlotMapVector.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARC.h"
31 #include "ProvenanceAnalysis.h"
32 #include "PtrState.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/raw_ostream.h"
44 
45 using namespace llvm;
46 using namespace llvm::objcarc;
47 
48 #define DEBUG_TYPE "objc-arc-opts"
49 
50 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
51 /// @{
52 
53 /// \brief This is similar to GetRCIdentityRoot but it stops as soon
54 /// as it finds a value with multiple uses.
55 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
56   // ConstantData (like ConstantPointerNull and UndefValue) is used across
57   // modules.  It's never a single-use value.
58   if (isa<ConstantData>(Arg))
59     return nullptr;
60 
61   if (Arg->hasOneUse()) {
62     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
63       return FindSingleUseIdentifiedObject(BC->getOperand(0));
64     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
65       if (GEP->hasAllZeroIndices())
66         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
67     if (IsForwarding(GetBasicARCInstKind(Arg)))
68       return FindSingleUseIdentifiedObject(
69                cast<CallInst>(Arg)->getArgOperand(0));
70     if (!IsObjCIdentifiedObject(Arg))
71       return nullptr;
72     return Arg;
73   }
74 
75   // If we found an identifiable object but it has multiple uses, but they are
76   // trivial uses, we can still consider this to be a single-use value.
77   if (IsObjCIdentifiedObject(Arg)) {
78     for (const User *U : Arg->users())
79       if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
80          return nullptr;
81 
82     return Arg;
83   }
84 
85   return nullptr;
86 }
87 
88 /// @}
89 ///
90 /// \defgroup ARCOpt ARC Optimization.
91 /// @{
92 
93 // TODO: On code like this:
94 //
95 // objc_retain(%x)
96 // stuff_that_cannot_release()
97 // objc_autorelease(%x)
98 // stuff_that_cannot_release()
99 // objc_retain(%x)
100 // stuff_that_cannot_release()
101 // objc_autorelease(%x)
102 //
103 // The second retain and autorelease can be deleted.
104 
105 // TODO: It should be possible to delete
106 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
107 // pairs if nothing is actually autoreleased between them. Also, autorelease
108 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
109 // after inlining) can be turned into plain release calls.
110 
111 // TODO: Critical-edge splitting. If the optimial insertion point is
112 // a critical edge, the current algorithm has to fail, because it doesn't
113 // know how to split edges. It should be possible to make the optimizer
114 // think in terms of edges, rather than blocks, and then split critical
115 // edges on demand.
116 
117 // TODO: OptimizeSequences could generalized to be Interprocedural.
118 
119 // TODO: Recognize that a bunch of other objc runtime calls have
120 // non-escaping arguments and non-releasing arguments, and may be
121 // non-autoreleasing.
122 
123 // TODO: Sink autorelease calls as far as possible. Unfortunately we
124 // usually can't sink them past other calls, which would be the main
125 // case where it would be useful.
126 
127 // TODO: The pointer returned from objc_loadWeakRetained is retained.
128 
129 // TODO: Delete release+retain pairs (rare).
130 
131 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
132 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
133 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
134 STATISTIC(NumRets,        "Number of return value forwarding "
135                           "retain+autoreleases eliminated");
136 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
137 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
138 #ifndef NDEBUG
139 STATISTIC(NumRetainsBeforeOpt,
140           "Number of retains before optimization");
141 STATISTIC(NumReleasesBeforeOpt,
142           "Number of releases before optimization");
143 STATISTIC(NumRetainsAfterOpt,
144           "Number of retains after optimization");
145 STATISTIC(NumReleasesAfterOpt,
146           "Number of releases after optimization");
147 #endif
148 
149 namespace {
150   /// \brief Per-BasicBlock state.
151   class BBState {
152     /// The number of unique control paths from the entry which can reach this
153     /// block.
154     unsigned TopDownPathCount;
155 
156     /// The number of unique control paths to exits from this block.
157     unsigned BottomUpPathCount;
158 
159     /// The top-down traversal uses this to record information known about a
160     /// pointer at the bottom of each block.
161     BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown;
162 
163     /// The bottom-up traversal uses this to record information known about a
164     /// pointer at the top of each block.
165     BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp;
166 
167     /// Effective predecessors of the current block ignoring ignorable edges and
168     /// ignored backedges.
169     SmallVector<BasicBlock *, 2> Preds;
170 
171     /// Effective successors of the current block ignoring ignorable edges and
172     /// ignored backedges.
173     SmallVector<BasicBlock *, 2> Succs;
174 
175   public:
176     static const unsigned OverflowOccurredValue;
177 
178     BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
179 
180     typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
181     typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
182 
183     top_down_ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
184     top_down_ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
185     const_top_down_ptr_iterator top_down_ptr_begin() const {
186       return PerPtrTopDown.begin();
187     }
188     const_top_down_ptr_iterator top_down_ptr_end() const {
189       return PerPtrTopDown.end();
190     }
191     bool hasTopDownPtrs() const {
192       return !PerPtrTopDown.empty();
193     }
194 
195     typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
196     typedef decltype(
197         PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
198 
199     bottom_up_ptr_iterator bottom_up_ptr_begin() {
200       return PerPtrBottomUp.begin();
201     }
202     bottom_up_ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
203     const_bottom_up_ptr_iterator bottom_up_ptr_begin() const {
204       return PerPtrBottomUp.begin();
205     }
206     const_bottom_up_ptr_iterator bottom_up_ptr_end() const {
207       return PerPtrBottomUp.end();
208     }
209     bool hasBottomUpPtrs() const {
210       return !PerPtrBottomUp.empty();
211     }
212 
213     /// Mark this block as being an entry block, which has one path from the
214     /// entry by definition.
215     void SetAsEntry() { TopDownPathCount = 1; }
216 
217     /// Mark this block as being an exit block, which has one path to an exit by
218     /// definition.
219     void SetAsExit()  { BottomUpPathCount = 1; }
220 
221     /// Attempt to find the PtrState object describing the top down state for
222     /// pointer Arg. Return a new initialized PtrState describing the top down
223     /// state for Arg if we do not find one.
224     TopDownPtrState &getPtrTopDownState(const Value *Arg) {
225       return PerPtrTopDown[Arg];
226     }
227 
228     /// Attempt to find the PtrState object describing the bottom up state for
229     /// pointer Arg. Return a new initialized PtrState describing the bottom up
230     /// state for Arg if we do not find one.
231     BottomUpPtrState &getPtrBottomUpState(const Value *Arg) {
232       return PerPtrBottomUp[Arg];
233     }
234 
235     /// Attempt to find the PtrState object describing the bottom up state for
236     /// pointer Arg.
237     bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) {
238       return PerPtrBottomUp.find(Arg);
239     }
240 
241     void clearBottomUpPointers() {
242       PerPtrBottomUp.clear();
243     }
244 
245     void clearTopDownPointers() {
246       PerPtrTopDown.clear();
247     }
248 
249     void InitFromPred(const BBState &Other);
250     void InitFromSucc(const BBState &Other);
251     void MergePred(const BBState &Other);
252     void MergeSucc(const BBState &Other);
253 
254     /// Compute the number of possible unique paths from an entry to an exit
255     /// which pass through this block. This is only valid after both the
256     /// top-down and bottom-up traversals are complete.
257     ///
258     /// Returns true if overflow occurred. Returns false if overflow did not
259     /// occur.
260     bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
261       if (TopDownPathCount == OverflowOccurredValue ||
262           BottomUpPathCount == OverflowOccurredValue)
263         return true;
264       unsigned long long Product =
265         (unsigned long long)TopDownPathCount*BottomUpPathCount;
266       // Overflow occurred if any of the upper bits of Product are set or if all
267       // the lower bits of Product are all set.
268       return (Product >> 32) ||
269              ((PathCount = Product) == OverflowOccurredValue);
270     }
271 
272     // Specialized CFG utilities.
273     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
274     edge_iterator pred_begin() const { return Preds.begin(); }
275     edge_iterator pred_end() const { return Preds.end(); }
276     edge_iterator succ_begin() const { return Succs.begin(); }
277     edge_iterator succ_end() const { return Succs.end(); }
278 
279     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
280     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
281 
282     bool isExit() const { return Succs.empty(); }
283   };
284 
285   const unsigned BBState::OverflowOccurredValue = 0xffffffff;
286 }
287 
288 namespace llvm {
289 raw_ostream &operator<<(raw_ostream &OS,
290                         BBState &BBState) LLVM_ATTRIBUTE_UNUSED;
291 }
292 
293 void BBState::InitFromPred(const BBState &Other) {
294   PerPtrTopDown = Other.PerPtrTopDown;
295   TopDownPathCount = Other.TopDownPathCount;
296 }
297 
298 void BBState::InitFromSucc(const BBState &Other) {
299   PerPtrBottomUp = Other.PerPtrBottomUp;
300   BottomUpPathCount = Other.BottomUpPathCount;
301 }
302 
303 /// The top-down traversal uses this to merge information about predecessors to
304 /// form the initial state for a new block.
305 void BBState::MergePred(const BBState &Other) {
306   if (TopDownPathCount == OverflowOccurredValue)
307     return;
308 
309   // Other.TopDownPathCount can be 0, in which case it is either dead or a
310   // loop backedge. Loop backedges are special.
311   TopDownPathCount += Other.TopDownPathCount;
312 
313   // In order to be consistent, we clear the top down pointers when by adding
314   // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
315   // has not occurred.
316   if (TopDownPathCount == OverflowOccurredValue) {
317     clearTopDownPointers();
318     return;
319   }
320 
321   // Check for overflow. If we have overflow, fall back to conservative
322   // behavior.
323   if (TopDownPathCount < Other.TopDownPathCount) {
324     TopDownPathCount = OverflowOccurredValue;
325     clearTopDownPointers();
326     return;
327   }
328 
329   // For each entry in the other set, if our set has an entry with the same key,
330   // merge the entries. Otherwise, copy the entry and merge it with an empty
331   // entry.
332   for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
333        MI != ME; ++MI) {
334     auto Pair = PerPtrTopDown.insert(*MI);
335     Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second,
336                              /*TopDown=*/true);
337   }
338 
339   // For each entry in our set, if the other set doesn't have an entry with the
340   // same key, force it to merge with an empty entry.
341   for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
342     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
343       MI->second.Merge(TopDownPtrState(), /*TopDown=*/true);
344 }
345 
346 /// The bottom-up traversal uses this to merge information about successors to
347 /// form the initial state for a new block.
348 void BBState::MergeSucc(const BBState &Other) {
349   if (BottomUpPathCount == OverflowOccurredValue)
350     return;
351 
352   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
353   // loop backedge. Loop backedges are special.
354   BottomUpPathCount += Other.BottomUpPathCount;
355 
356   // In order to be consistent, we clear the top down pointers when by adding
357   // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
358   // has not occurred.
359   if (BottomUpPathCount == OverflowOccurredValue) {
360     clearBottomUpPointers();
361     return;
362   }
363 
364   // Check for overflow. If we have overflow, fall back to conservative
365   // behavior.
366   if (BottomUpPathCount < Other.BottomUpPathCount) {
367     BottomUpPathCount = OverflowOccurredValue;
368     clearBottomUpPointers();
369     return;
370   }
371 
372   // For each entry in the other set, if our set has an entry with the
373   // same key, merge the entries. Otherwise, copy the entry and merge
374   // it with an empty entry.
375   for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
376        MI != ME; ++MI) {
377     auto Pair = PerPtrBottomUp.insert(*MI);
378     Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second,
379                              /*TopDown=*/false);
380   }
381 
382   // For each entry in our set, if the other set doesn't have an entry
383   // with the same key, force it to merge with an empty entry.
384   for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
385        ++MI)
386     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
387       MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false);
388 }
389 
390 raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) {
391   // Dump the pointers we are tracking.
392   OS << "    TopDown State:\n";
393   if (!BBInfo.hasTopDownPtrs()) {
394     DEBUG(llvm::dbgs() << "        NONE!\n");
395   } else {
396     for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end();
397          I != E; ++I) {
398       const PtrState &P = I->second;
399       OS << "        Ptr: " << *I->first
400          << "\n            KnownSafe:        " << (P.IsKnownSafe()?"true":"false")
401          << "\n            ImpreciseRelease: "
402            << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
403          << "            HasCFGHazards:    "
404            << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
405          << "            KnownPositive:    "
406            << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
407          << "            Seq:              "
408          << P.GetSeq() << "\n";
409     }
410   }
411 
412   OS << "    BottomUp State:\n";
413   if (!BBInfo.hasBottomUpPtrs()) {
414     DEBUG(llvm::dbgs() << "        NONE!\n");
415   } else {
416     for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end();
417          I != E; ++I) {
418       const PtrState &P = I->second;
419       OS << "        Ptr: " << *I->first
420          << "\n            KnownSafe:        " << (P.IsKnownSafe()?"true":"false")
421          << "\n            ImpreciseRelease: "
422            << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n"
423          << "            HasCFGHazards:    "
424            << (P.IsCFGHazardAfflicted()?"true":"false") << "\n"
425          << "            KnownPositive:    "
426            << (P.HasKnownPositiveRefCount()?"true":"false") << "\n"
427          << "            Seq:              "
428          << P.GetSeq() << "\n";
429     }
430   }
431 
432   return OS;
433 }
434 
435 namespace {
436 
437   /// \brief The main ARC optimization pass.
438   class ObjCARCOpt : public FunctionPass {
439     bool Changed;
440     ProvenanceAnalysis PA;
441 
442     /// A cache of references to runtime entry point constants.
443     ARCRuntimeEntryPoints EP;
444 
445     /// A cache of MDKinds that can be passed into other functions to propagate
446     /// MDKind identifiers.
447     ARCMDKindCache MDKindCache;
448 
449     /// A flag indicating whether this optimization pass should run.
450     bool Run;
451 
452     /// Flags which determine whether each of the interesting runtime functions
453     /// is in fact used in the current function.
454     unsigned UsedInThisFunction;
455 
456     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
457     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
458                                    ARCInstKind &Class);
459     void OptimizeIndividualCalls(Function &F);
460 
461     void CheckForCFGHazards(const BasicBlock *BB,
462                             DenseMap<const BasicBlock *, BBState> &BBStates,
463                             BBState &MyStates) const;
464     bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
465                                   BlotMapVector<Value *, RRInfo> &Retains,
466                                   BBState &MyStates);
467     bool VisitBottomUp(BasicBlock *BB,
468                        DenseMap<const BasicBlock *, BBState> &BBStates,
469                        BlotMapVector<Value *, RRInfo> &Retains);
470     bool VisitInstructionTopDown(Instruction *Inst,
471                                  DenseMap<Value *, RRInfo> &Releases,
472                                  BBState &MyStates);
473     bool VisitTopDown(BasicBlock *BB,
474                       DenseMap<const BasicBlock *, BBState> &BBStates,
475                       DenseMap<Value *, RRInfo> &Releases);
476     bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
477                BlotMapVector<Value *, RRInfo> &Retains,
478                DenseMap<Value *, RRInfo> &Releases);
479 
480     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
481                    BlotMapVector<Value *, RRInfo> &Retains,
482                    DenseMap<Value *, RRInfo> &Releases,
483                    SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
484 
485     bool
486     PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates,
487                              BlotMapVector<Value *, RRInfo> &Retains,
488                              DenseMap<Value *, RRInfo> &Releases, Module *M,
489                              Instruction * Retain,
490                              SmallVectorImpl<Instruction *> &DeadInsts,
491                              RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
492                              Value *Arg, bool KnownSafe,
493                              bool &AnyPairsCompletelyEliminated);
494 
495     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
496                               BlotMapVector<Value *, RRInfo> &Retains,
497                               DenseMap<Value *, RRInfo> &Releases, Module *M);
498 
499     void OptimizeWeakCalls(Function &F);
500 
501     bool OptimizeSequences(Function &F);
502 
503     void OptimizeReturns(Function &F);
504 
505 #ifndef NDEBUG
506     void GatherStatistics(Function &F, bool AfterOptimization = false);
507 #endif
508 
509     void getAnalysisUsage(AnalysisUsage &AU) const override;
510     bool doInitialization(Module &M) override;
511     bool runOnFunction(Function &F) override;
512     void releaseMemory() override;
513 
514   public:
515     static char ID;
516     ObjCARCOpt() : FunctionPass(ID) {
517       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
518     }
519   };
520 }
521 
522 char ObjCARCOpt::ID = 0;
523 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
524                       "objc-arc", "ObjC ARC optimization", false, false)
525 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass)
526 INITIALIZE_PASS_END(ObjCARCOpt,
527                     "objc-arc", "ObjC ARC optimization", false, false)
528 
529 Pass *llvm::createObjCARCOptPass() {
530   return new ObjCARCOpt();
531 }
532 
533 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
534   AU.addRequired<ObjCARCAAWrapperPass>();
535   AU.addRequired<AAResultsWrapperPass>();
536   // ARC optimization doesn't currently split critical edges.
537   AU.setPreservesCFG();
538 }
539 
540 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
541 /// not a return value.  Or, if it can be paired with an
542 /// objc_autoreleaseReturnValue, delete the pair and return true.
543 bool
544 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
545   // Check for the argument being from an immediately preceding call or invoke.
546   const Value *Arg = GetArgRCIdentityRoot(RetainRV);
547   ImmutableCallSite CS(Arg);
548   if (const Instruction *Call = CS.getInstruction()) {
549     if (Call->getParent() == RetainRV->getParent()) {
550       BasicBlock::const_iterator I(Call);
551       ++I;
552       while (IsNoopInstruction(&*I))
553         ++I;
554       if (&*I == RetainRV)
555         return false;
556     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
557       BasicBlock *RetainRVParent = RetainRV->getParent();
558       if (II->getNormalDest() == RetainRVParent) {
559         BasicBlock::const_iterator I = RetainRVParent->begin();
560         while (IsNoopInstruction(&*I))
561           ++I;
562         if (&*I == RetainRV)
563           return false;
564       }
565     }
566   }
567 
568   // Check for being preceded by an objc_autoreleaseReturnValue on the same
569   // pointer. In this case, we can delete the pair.
570   BasicBlock::iterator I = RetainRV->getIterator(),
571                        Begin = RetainRV->getParent()->begin();
572   if (I != Begin) {
573     do
574       --I;
575     while (I != Begin && IsNoopInstruction(&*I));
576     if (GetBasicARCInstKind(&*I) == ARCInstKind::AutoreleaseRV &&
577         GetArgRCIdentityRoot(&*I) == Arg) {
578       Changed = true;
579       ++NumPeeps;
580 
581       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
582                    << "Erasing " << *RetainRV << "\n");
583 
584       EraseInstruction(&*I);
585       EraseInstruction(RetainRV);
586       return true;
587     }
588   }
589 
590   // Turn it to a plain objc_retain.
591   Changed = true;
592   ++NumPeeps;
593 
594   DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
595                   "objc_retain since the operand is not a return value.\n"
596                   "Old = " << *RetainRV << "\n");
597 
598   Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain);
599   cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
600 
601   DEBUG(dbgs() << "New = " << *RetainRV << "\n");
602 
603   return false;
604 }
605 
606 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
607 /// used as a return value.
608 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
609                                            Instruction *AutoreleaseRV,
610                                            ARCInstKind &Class) {
611   // Check for a return of the pointer value.
612   const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
613 
614   // If the argument is ConstantPointerNull or UndefValue, its other users
615   // aren't actually interesting to look at.
616   if (isa<ConstantData>(Ptr))
617     return;
618 
619   SmallVector<const Value *, 2> Users;
620   Users.push_back(Ptr);
621   do {
622     Ptr = Users.pop_back_val();
623     for (const User *U : Ptr->users()) {
624       if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
625         return;
626       if (isa<BitCastInst>(U))
627         Users.push_back(U);
628     }
629   } while (!Users.empty());
630 
631   Changed = true;
632   ++NumPeeps;
633 
634   DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
635                   "objc_autorelease since its operand is not used as a return "
636                   "value.\n"
637                   "Old = " << *AutoreleaseRV << "\n");
638 
639   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
640   Constant *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease);
641   AutoreleaseRVCI->setCalledFunction(NewDecl);
642   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
643   Class = ARCInstKind::Autorelease;
644 
645   DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
646 
647 }
648 
649 /// Visit each call, one at a time, and make simplifications without doing any
650 /// additional analysis.
651 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
652   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
653   // Reset all the flags in preparation for recomputing them.
654   UsedInThisFunction = 0;
655 
656   // Visit all objc_* calls in F.
657   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
658     Instruction *Inst = &*I++;
659 
660     ARCInstKind Class = GetBasicARCInstKind(Inst);
661 
662     DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
663 
664     switch (Class) {
665     default: break;
666 
667     // Delete no-op casts. These function calls have special semantics, but
668     // the semantics are entirely implemented via lowering in the front-end,
669     // so by the time they reach the optimizer, they are just no-op calls
670     // which return their argument.
671     //
672     // There are gray areas here, as the ability to cast reference-counted
673     // pointers to raw void* and back allows code to break ARC assumptions,
674     // however these are currently considered to be unimportant.
675     case ARCInstKind::NoopCast:
676       Changed = true;
677       ++NumNoops;
678       DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
679       EraseInstruction(Inst);
680       continue;
681 
682     // If the pointer-to-weak-pointer is null, it's undefined behavior.
683     case ARCInstKind::StoreWeak:
684     case ARCInstKind::LoadWeak:
685     case ARCInstKind::LoadWeakRetained:
686     case ARCInstKind::InitWeak:
687     case ARCInstKind::DestroyWeak: {
688       CallInst *CI = cast<CallInst>(Inst);
689       if (IsNullOrUndef(CI->getArgOperand(0))) {
690         Changed = true;
691         Type *Ty = CI->getArgOperand(0)->getType();
692         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
693                       Constant::getNullValue(Ty),
694                       CI);
695         llvm::Value *NewValue = UndefValue::get(CI->getType());
696         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
697                        "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
698         CI->replaceAllUsesWith(NewValue);
699         CI->eraseFromParent();
700         continue;
701       }
702       break;
703     }
704     case ARCInstKind::CopyWeak:
705     case ARCInstKind::MoveWeak: {
706       CallInst *CI = cast<CallInst>(Inst);
707       if (IsNullOrUndef(CI->getArgOperand(0)) ||
708           IsNullOrUndef(CI->getArgOperand(1))) {
709         Changed = true;
710         Type *Ty = CI->getArgOperand(0)->getType();
711         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
712                       Constant::getNullValue(Ty),
713                       CI);
714 
715         llvm::Value *NewValue = UndefValue::get(CI->getType());
716         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
717                         "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
718 
719         CI->replaceAllUsesWith(NewValue);
720         CI->eraseFromParent();
721         continue;
722       }
723       break;
724     }
725     case ARCInstKind::RetainRV:
726       if (OptimizeRetainRVCall(F, Inst))
727         continue;
728       break;
729     case ARCInstKind::AutoreleaseRV:
730       OptimizeAutoreleaseRVCall(F, Inst, Class);
731       break;
732     }
733 
734     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
735     if (IsAutorelease(Class) && Inst->use_empty()) {
736       CallInst *Call = cast<CallInst>(Inst);
737       const Value *Arg = Call->getArgOperand(0);
738       Arg = FindSingleUseIdentifiedObject(Arg);
739       if (Arg) {
740         Changed = true;
741         ++NumAutoreleases;
742 
743         // Create the declaration lazily.
744         LLVMContext &C = Inst->getContext();
745 
746         Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
747         CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
748                                              Call);
749         NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease),
750                              MDNode::get(C, None));
751 
752         DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
753               "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
754               << *NewCall << "\n");
755 
756         EraseInstruction(Call);
757         Inst = NewCall;
758         Class = ARCInstKind::Release;
759       }
760     }
761 
762     // For functions which can never be passed stack arguments, add
763     // a tail keyword.
764     if (IsAlwaysTail(Class)) {
765       Changed = true;
766       DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
767                       "passed stack args: " << *Inst << "\n");
768       cast<CallInst>(Inst)->setTailCall();
769     }
770 
771     // Ensure that functions that can never have a "tail" keyword due to the
772     // semantics of ARC truly do not do so.
773     if (IsNeverTail(Class)) {
774       Changed = true;
775       DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
776             "\n");
777       cast<CallInst>(Inst)->setTailCall(false);
778     }
779 
780     // Set nounwind as needed.
781     if (IsNoThrow(Class)) {
782       Changed = true;
783       DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
784                    << "\n");
785       cast<CallInst>(Inst)->setDoesNotThrow();
786     }
787 
788     if (!IsNoopOnNull(Class)) {
789       UsedInThisFunction |= 1 << unsigned(Class);
790       continue;
791     }
792 
793     const Value *Arg = GetArgRCIdentityRoot(Inst);
794 
795     // ARC calls with null are no-ops. Delete them.
796     if (IsNullOrUndef(Arg)) {
797       Changed = true;
798       ++NumNoops;
799       DEBUG(dbgs() << "ARC calls with  null are no-ops. Erasing: " << *Inst
800             << "\n");
801       EraseInstruction(Inst);
802       continue;
803     }
804 
805     // Keep track of which of retain, release, autorelease, and retain_block
806     // are actually present in this function.
807     UsedInThisFunction |= 1 << unsigned(Class);
808 
809     // If Arg is a PHI, and one or more incoming values to the
810     // PHI are null, and the call is control-equivalent to the PHI, and there
811     // are no relevant side effects between the PHI and the call, and the call
812     // is not a release that doesn't have the clang.imprecise_release tag, the
813     // call could be pushed up to just those paths with non-null incoming
814     // values. For now, don't bother splitting critical edges for this.
815     if (Class == ARCInstKind::Release &&
816         !Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease)))
817       continue;
818 
819     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
820     Worklist.push_back(std::make_pair(Inst, Arg));
821     do {
822       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
823       Inst = Pair.first;
824       Arg = Pair.second;
825 
826       const PHINode *PN = dyn_cast<PHINode>(Arg);
827       if (!PN) continue;
828 
829       // Determine if the PHI has any null operands, or any incoming
830       // critical edges.
831       bool HasNull = false;
832       bool HasCriticalEdges = false;
833       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
834         Value *Incoming =
835           GetRCIdentityRoot(PN->getIncomingValue(i));
836         if (IsNullOrUndef(Incoming))
837           HasNull = true;
838         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
839                    .getNumSuccessors() != 1) {
840           HasCriticalEdges = true;
841           break;
842         }
843       }
844       // If we have null operands and no critical edges, optimize.
845       if (!HasCriticalEdges && HasNull) {
846         SmallPtrSet<Instruction *, 4> DependingInstructions;
847         SmallPtrSet<const BasicBlock *, 4> Visited;
848 
849         // Check that there is nothing that cares about the reference
850         // count between the call and the phi.
851         switch (Class) {
852         case ARCInstKind::Retain:
853         case ARCInstKind::RetainBlock:
854           // These can always be moved up.
855           break;
856         case ARCInstKind::Release:
857           // These can't be moved across things that care about the retain
858           // count.
859           FindDependencies(NeedsPositiveRetainCount, Arg,
860                            Inst->getParent(), Inst,
861                            DependingInstructions, Visited, PA);
862           break;
863         case ARCInstKind::Autorelease:
864           // These can't be moved across autorelease pool scope boundaries.
865           FindDependencies(AutoreleasePoolBoundary, Arg,
866                            Inst->getParent(), Inst,
867                            DependingInstructions, Visited, PA);
868           break;
869         case ARCInstKind::ClaimRV:
870         case ARCInstKind::RetainRV:
871         case ARCInstKind::AutoreleaseRV:
872           // Don't move these; the RV optimization depends on the autoreleaseRV
873           // being tail called, and the retainRV being immediately after a call
874           // (which might still happen if we get lucky with codegen layout, but
875           // it's not worth taking the chance).
876           continue;
877         default:
878           llvm_unreachable("Invalid dependence flavor");
879         }
880 
881         if (DependingInstructions.size() == 1 &&
882             *DependingInstructions.begin() == PN) {
883           Changed = true;
884           ++NumPartialNoops;
885           // Clone the call into each predecessor that has a non-null value.
886           CallInst *CInst = cast<CallInst>(Inst);
887           Type *ParamTy = CInst->getArgOperand(0)->getType();
888           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
889             Value *Incoming =
890               GetRCIdentityRoot(PN->getIncomingValue(i));
891             if (!IsNullOrUndef(Incoming)) {
892               CallInst *Clone = cast<CallInst>(CInst->clone());
893               Value *Op = PN->getIncomingValue(i);
894               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
895               if (Op->getType() != ParamTy)
896                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
897               Clone->setArgOperand(0, Op);
898               Clone->insertBefore(InsertPos);
899 
900               DEBUG(dbgs() << "Cloning "
901                            << *CInst << "\n"
902                            "And inserting clone at " << *InsertPos << "\n");
903               Worklist.push_back(std::make_pair(Clone, Incoming));
904             }
905           }
906           // Erase the original call.
907           DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
908           EraseInstruction(CInst);
909           continue;
910         }
911       }
912     } while (!Worklist.empty());
913   }
914 }
915 
916 /// If we have a top down pointer in the S_Use state, make sure that there are
917 /// no CFG hazards by checking the states of various bottom up pointers.
918 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
919                                  const bool SuccSRRIKnownSafe,
920                                  TopDownPtrState &S,
921                                  bool &SomeSuccHasSame,
922                                  bool &AllSuccsHaveSame,
923                                  bool &NotAllSeqEqualButKnownSafe,
924                                  bool &ShouldContinue) {
925   switch (SuccSSeq) {
926   case S_CanRelease: {
927     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
928       S.ClearSequenceProgress();
929       break;
930     }
931     S.SetCFGHazardAfflicted(true);
932     ShouldContinue = true;
933     break;
934   }
935   case S_Use:
936     SomeSuccHasSame = true;
937     break;
938   case S_Stop:
939   case S_Release:
940   case S_MovableRelease:
941     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
942       AllSuccsHaveSame = false;
943     else
944       NotAllSeqEqualButKnownSafe = true;
945     break;
946   case S_Retain:
947     llvm_unreachable("bottom-up pointer in retain state!");
948   case S_None:
949     llvm_unreachable("This should have been handled earlier.");
950   }
951 }
952 
953 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
954 /// there are no CFG hazards by checking the states of various bottom up
955 /// pointers.
956 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
957                                         const bool SuccSRRIKnownSafe,
958                                         TopDownPtrState &S,
959                                         bool &SomeSuccHasSame,
960                                         bool &AllSuccsHaveSame,
961                                         bool &NotAllSeqEqualButKnownSafe) {
962   switch (SuccSSeq) {
963   case S_CanRelease:
964     SomeSuccHasSame = true;
965     break;
966   case S_Stop:
967   case S_Release:
968   case S_MovableRelease:
969   case S_Use:
970     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
971       AllSuccsHaveSame = false;
972     else
973       NotAllSeqEqualButKnownSafe = true;
974     break;
975   case S_Retain:
976     llvm_unreachable("bottom-up pointer in retain state!");
977   case S_None:
978     llvm_unreachable("This should have been handled earlier.");
979   }
980 }
981 
982 /// Check for critical edges, loop boundaries, irreducible control flow, or
983 /// other CFG structures where moving code across the edge would result in it
984 /// being executed more.
985 void
986 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
987                                DenseMap<const BasicBlock *, BBState> &BBStates,
988                                BBState &MyStates) const {
989   // If any top-down local-use or possible-dec has a succ which is earlier in
990   // the sequence, forget it.
991   for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end();
992        I != E; ++I) {
993     TopDownPtrState &S = I->second;
994     const Sequence Seq = I->second.GetSeq();
995 
996     // We only care about S_Retain, S_CanRelease, and S_Use.
997     if (Seq == S_None)
998       continue;
999 
1000     // Make sure that if extra top down states are added in the future that this
1001     // code is updated to handle it.
1002     assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1003            "Unknown top down sequence state.");
1004 
1005     const Value *Arg = I->first;
1006     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1007     bool SomeSuccHasSame = false;
1008     bool AllSuccsHaveSame = true;
1009     bool NotAllSeqEqualButKnownSafe = false;
1010 
1011     succ_const_iterator SI(TI), SE(TI, false);
1012 
1013     for (; SI != SE; ++SI) {
1014       // If VisitBottomUp has pointer information for this successor, take
1015       // what we know about it.
1016       const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1017         BBStates.find(*SI);
1018       assert(BBI != BBStates.end());
1019       const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1020       const Sequence SuccSSeq = SuccS.GetSeq();
1021 
1022       // If bottom up, the pointer is in an S_None state, clear the sequence
1023       // progress since the sequence in the bottom up state finished
1024       // suggesting a mismatch in between retains/releases. This is true for
1025       // all three cases that we are handling here: S_Retain, S_Use, and
1026       // S_CanRelease.
1027       if (SuccSSeq == S_None) {
1028         S.ClearSequenceProgress();
1029         continue;
1030       }
1031 
1032       // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1033       // checks.
1034       const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1035 
1036       // *NOTE* We do not use Seq from above here since we are allowing for
1037       // S.GetSeq() to change while we are visiting basic blocks.
1038       switch(S.GetSeq()) {
1039       case S_Use: {
1040         bool ShouldContinue = false;
1041         CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1042                              AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1043                              ShouldContinue);
1044         if (ShouldContinue)
1045           continue;
1046         break;
1047       }
1048       case S_CanRelease: {
1049         CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1050                                     SomeSuccHasSame, AllSuccsHaveSame,
1051                                     NotAllSeqEqualButKnownSafe);
1052         break;
1053       }
1054       case S_Retain:
1055       case S_None:
1056       case S_Stop:
1057       case S_Release:
1058       case S_MovableRelease:
1059         break;
1060       }
1061     }
1062 
1063     // If the state at the other end of any of the successor edges
1064     // matches the current state, require all edges to match. This
1065     // guards against loops in the middle of a sequence.
1066     if (SomeSuccHasSame && !AllSuccsHaveSame) {
1067       S.ClearSequenceProgress();
1068     } else if (NotAllSeqEqualButKnownSafe) {
1069       // If we would have cleared the state foregoing the fact that we are known
1070       // safe, stop code motion. This is because whether or not it is safe to
1071       // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1072       // are allowed to perform code motion.
1073       S.SetCFGHazardAfflicted(true);
1074     }
1075   }
1076 }
1077 
1078 bool ObjCARCOpt::VisitInstructionBottomUp(
1079     Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1080     BBState &MyStates) {
1081   bool NestingDetected = false;
1082   ARCInstKind Class = GetARCInstKind(Inst);
1083   const Value *Arg = nullptr;
1084 
1085   DEBUG(dbgs() << "        Class: " << Class << "\n");
1086 
1087   switch (Class) {
1088   case ARCInstKind::Release: {
1089     Arg = GetArgRCIdentityRoot(Inst);
1090 
1091     BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
1092     NestingDetected |= S.InitBottomUp(MDKindCache, Inst);
1093     break;
1094   }
1095   case ARCInstKind::RetainBlock:
1096     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1097     // objc_retainBlocks to objc_retains. Thus at this point any
1098     // objc_retainBlocks that we see are not optimizable.
1099     break;
1100   case ARCInstKind::Retain:
1101   case ARCInstKind::RetainRV: {
1102     Arg = GetArgRCIdentityRoot(Inst);
1103     BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg);
1104     if (S.MatchWithRetain()) {
1105       // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1106       // it's better to let it remain as the first instruction after a call.
1107       if (Class != ARCInstKind::RetainRV) {
1108         DEBUG(llvm::dbgs() << "        Matching with: " << *Inst << "\n");
1109         Retains[Inst] = S.GetRRInfo();
1110       }
1111       S.ClearSequenceProgress();
1112     }
1113     // A retain moving bottom up can be a use.
1114     break;
1115   }
1116   case ARCInstKind::AutoreleasepoolPop:
1117     // Conservatively, clear MyStates for all known pointers.
1118     MyStates.clearBottomUpPointers();
1119     return NestingDetected;
1120   case ARCInstKind::AutoreleasepoolPush:
1121   case ARCInstKind::None:
1122     // These are irrelevant.
1123     return NestingDetected;
1124   default:
1125     break;
1126   }
1127 
1128   // Consider any other possible effects of this instruction on each
1129   // pointer being tracked.
1130   for (auto MI = MyStates.bottom_up_ptr_begin(),
1131             ME = MyStates.bottom_up_ptr_end();
1132        MI != ME; ++MI) {
1133     const Value *Ptr = MI->first;
1134     if (Ptr == Arg)
1135       continue; // Handled above.
1136     BottomUpPtrState &S = MI->second;
1137 
1138     if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1139       continue;
1140 
1141     S.HandlePotentialUse(BB, Inst, Ptr, PA, Class);
1142   }
1143 
1144   return NestingDetected;
1145 }
1146 
1147 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1148                                DenseMap<const BasicBlock *, BBState> &BBStates,
1149                                BlotMapVector<Value *, RRInfo> &Retains) {
1150 
1151   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1152 
1153   bool NestingDetected = false;
1154   BBState &MyStates = BBStates[BB];
1155 
1156   // Merge the states from each successor to compute the initial state
1157   // for the current block.
1158   BBState::edge_iterator SI(MyStates.succ_begin()),
1159                          SE(MyStates.succ_end());
1160   if (SI != SE) {
1161     const BasicBlock *Succ = *SI;
1162     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1163     assert(I != BBStates.end());
1164     MyStates.InitFromSucc(I->second);
1165     ++SI;
1166     for (; SI != SE; ++SI) {
1167       Succ = *SI;
1168       I = BBStates.find(Succ);
1169       assert(I != BBStates.end());
1170       MyStates.MergeSucc(I->second);
1171     }
1172   }
1173 
1174   DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB] << "\n"
1175                      << "Performing Dataflow:\n");
1176 
1177   // Visit all the instructions, bottom-up.
1178   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1179     Instruction *Inst = &*std::prev(I);
1180 
1181     // Invoke instructions are visited as part of their successors (below).
1182     if (isa<InvokeInst>(Inst))
1183       continue;
1184 
1185     DEBUG(dbgs() << "    Visiting " << *Inst << "\n");
1186 
1187     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1188   }
1189 
1190   // If there's a predecessor with an invoke, visit the invoke as if it were
1191   // part of this block, since we can't insert code after an invoke in its own
1192   // block, and we don't want to split critical edges.
1193   for (BBState::edge_iterator PI(MyStates.pred_begin()),
1194        PE(MyStates.pred_end()); PI != PE; ++PI) {
1195     BasicBlock *Pred = *PI;
1196     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1197       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1198   }
1199 
1200   DEBUG(llvm::dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n");
1201 
1202   return NestingDetected;
1203 }
1204 
1205 bool
1206 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1207                                     DenseMap<Value *, RRInfo> &Releases,
1208                                     BBState &MyStates) {
1209   bool NestingDetected = false;
1210   ARCInstKind Class = GetARCInstKind(Inst);
1211   const Value *Arg = nullptr;
1212 
1213   DEBUG(llvm::dbgs() << "        Class: " << Class << "\n");
1214 
1215   switch (Class) {
1216   case ARCInstKind::RetainBlock:
1217     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1218     // objc_retainBlocks to objc_retains. Thus at this point any
1219     // objc_retainBlocks that we see are not optimizable. We need to break since
1220     // a retain can be a potential use.
1221     break;
1222   case ARCInstKind::Retain:
1223   case ARCInstKind::RetainRV: {
1224     Arg = GetArgRCIdentityRoot(Inst);
1225     TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
1226     NestingDetected |= S.InitTopDown(Class, Inst);
1227     // A retain can be a potential use; proceed to the generic checking
1228     // code below.
1229     break;
1230   }
1231   case ARCInstKind::Release: {
1232     Arg = GetArgRCIdentityRoot(Inst);
1233     TopDownPtrState &S = MyStates.getPtrTopDownState(Arg);
1234     // Try to form a tentative pair in between this release instruction and the
1235     // top down pointers that we are tracking.
1236     if (S.MatchWithRelease(MDKindCache, Inst)) {
1237       // If we succeed, copy S's RRInfo into the Release -> {Retain Set
1238       // Map}. Then we clear S.
1239       DEBUG(llvm::dbgs() << "        Matching with: " << *Inst << "\n");
1240       Releases[Inst] = S.GetRRInfo();
1241       S.ClearSequenceProgress();
1242     }
1243     break;
1244   }
1245   case ARCInstKind::AutoreleasepoolPop:
1246     // Conservatively, clear MyStates for all known pointers.
1247     MyStates.clearTopDownPointers();
1248     return false;
1249   case ARCInstKind::AutoreleasepoolPush:
1250   case ARCInstKind::None:
1251     // These can not be uses of
1252     return false;
1253   default:
1254     break;
1255   }
1256 
1257   // Consider any other possible effects of this instruction on each
1258   // pointer being tracked.
1259   for (auto MI = MyStates.top_down_ptr_begin(),
1260             ME = MyStates.top_down_ptr_end();
1261        MI != ME; ++MI) {
1262     const Value *Ptr = MI->first;
1263     if (Ptr == Arg)
1264       continue; // Handled above.
1265     TopDownPtrState &S = MI->second;
1266     if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class))
1267       continue;
1268 
1269     S.HandlePotentialUse(Inst, Ptr, PA, Class);
1270   }
1271 
1272   return NestingDetected;
1273 }
1274 
1275 bool
1276 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1277                          DenseMap<const BasicBlock *, BBState> &BBStates,
1278                          DenseMap<Value *, RRInfo> &Releases) {
1279   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
1280   bool NestingDetected = false;
1281   BBState &MyStates = BBStates[BB];
1282 
1283   // Merge the states from each predecessor to compute the initial state
1284   // for the current block.
1285   BBState::edge_iterator PI(MyStates.pred_begin()),
1286                          PE(MyStates.pred_end());
1287   if (PI != PE) {
1288     const BasicBlock *Pred = *PI;
1289     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1290     assert(I != BBStates.end());
1291     MyStates.InitFromPred(I->second);
1292     ++PI;
1293     for (; PI != PE; ++PI) {
1294       Pred = *PI;
1295       I = BBStates.find(Pred);
1296       assert(I != BBStates.end());
1297       MyStates.MergePred(I->second);
1298     }
1299   }
1300 
1301   DEBUG(llvm::dbgs() << "Before:\n" << BBStates[BB]  << "\n"
1302                      << "Performing Dataflow:\n");
1303 
1304   // Visit all the instructions, top-down.
1305   for (Instruction &Inst : *BB) {
1306     DEBUG(dbgs() << "    Visiting " << Inst << "\n");
1307 
1308     NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
1309   }
1310 
1311   DEBUG(llvm::dbgs() << "\nState Before Checking for CFG Hazards:\n"
1312                      << BBStates[BB] << "\n\n");
1313   CheckForCFGHazards(BB, BBStates, MyStates);
1314   DEBUG(llvm::dbgs() << "Final State:\n" << BBStates[BB] << "\n");
1315   return NestingDetected;
1316 }
1317 
1318 static void
1319 ComputePostOrders(Function &F,
1320                   SmallVectorImpl<BasicBlock *> &PostOrder,
1321                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1322                   unsigned NoObjCARCExceptionsMDKind,
1323                   DenseMap<const BasicBlock *, BBState> &BBStates) {
1324   /// The visited set, for doing DFS walks.
1325   SmallPtrSet<BasicBlock *, 16> Visited;
1326 
1327   // Do DFS, computing the PostOrder.
1328   SmallPtrSet<BasicBlock *, 16> OnStack;
1329   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
1330 
1331   // Functions always have exactly one entry block, and we don't have
1332   // any other block that we treat like an entry block.
1333   BasicBlock *EntryBB = &F.getEntryBlock();
1334   BBState &MyStates = BBStates[EntryBB];
1335   MyStates.SetAsEntry();
1336   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1337   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
1338   Visited.insert(EntryBB);
1339   OnStack.insert(EntryBB);
1340   do {
1341   dfs_next_succ:
1342     BasicBlock *CurrBB = SuccStack.back().first;
1343     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1344     succ_iterator SE(TI, false);
1345 
1346     while (SuccStack.back().second != SE) {
1347       BasicBlock *SuccBB = *SuccStack.back().second++;
1348       if (Visited.insert(SuccBB).second) {
1349         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1350         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
1351         BBStates[CurrBB].addSucc(SuccBB);
1352         BBState &SuccStates = BBStates[SuccBB];
1353         SuccStates.addPred(CurrBB);
1354         OnStack.insert(SuccBB);
1355         goto dfs_next_succ;
1356       }
1357 
1358       if (!OnStack.count(SuccBB)) {
1359         BBStates[CurrBB].addSucc(SuccBB);
1360         BBStates[SuccBB].addPred(CurrBB);
1361       }
1362     }
1363     OnStack.erase(CurrBB);
1364     PostOrder.push_back(CurrBB);
1365     SuccStack.pop_back();
1366   } while (!SuccStack.empty());
1367 
1368   Visited.clear();
1369 
1370   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
1371   // Functions may have many exits, and there also blocks which we treat
1372   // as exits due to ignored edges.
1373   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1374   for (BasicBlock &ExitBB : F) {
1375     BBState &MyStates = BBStates[&ExitBB];
1376     if (!MyStates.isExit())
1377       continue;
1378 
1379     MyStates.SetAsExit();
1380 
1381     PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1382     Visited.insert(&ExitBB);
1383     while (!PredStack.empty()) {
1384     reverse_dfs_next_succ:
1385       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1386       while (PredStack.back().second != PE) {
1387         BasicBlock *BB = *PredStack.back().second++;
1388         if (Visited.insert(BB).second) {
1389           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
1390           goto reverse_dfs_next_succ;
1391         }
1392       }
1393       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1394     }
1395   }
1396 }
1397 
1398 // Visit the function both top-down and bottom-up.
1399 bool ObjCARCOpt::Visit(Function &F,
1400                        DenseMap<const BasicBlock *, BBState> &BBStates,
1401                        BlotMapVector<Value *, RRInfo> &Retains,
1402                        DenseMap<Value *, RRInfo> &Releases) {
1403 
1404   // Use reverse-postorder traversals, because we magically know that loops
1405   // will be well behaved, i.e. they won't repeatedly call retain on a single
1406   // pointer without doing a release. We can't use the ReversePostOrderTraversal
1407   // class here because we want the reverse-CFG postorder to consider each
1408   // function exit point, and we want to ignore selected cycle edges.
1409   SmallVector<BasicBlock *, 16> PostOrder;
1410   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
1411   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1412                     MDKindCache.get(ARCMDKindID::NoObjCARCExceptions),
1413                     BBStates);
1414 
1415   // Use reverse-postorder on the reverse CFG for bottom-up.
1416   bool BottomUpNestingDetected = false;
1417   for (BasicBlock *BB : reverse(ReverseCFGPostOrder))
1418     BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
1419 
1420   // Use reverse-postorder for top-down.
1421   bool TopDownNestingDetected = false;
1422   for (BasicBlock *BB : reverse(PostOrder))
1423     TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
1424 
1425   return TopDownNestingDetected && BottomUpNestingDetected;
1426 }
1427 
1428 /// Move the calls in RetainsToMove and ReleasesToMove.
1429 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
1430                            RRInfo &ReleasesToMove,
1431                            BlotMapVector<Value *, RRInfo> &Retains,
1432                            DenseMap<Value *, RRInfo> &Releases,
1433                            SmallVectorImpl<Instruction *> &DeadInsts,
1434                            Module *M) {
1435   Type *ArgTy = Arg->getType();
1436   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
1437 
1438   DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
1439 
1440   // Insert the new retain and release calls.
1441   for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
1442     Value *MyArg = ArgTy == ParamTy ? Arg :
1443                    new BitCastInst(Arg, ParamTy, "", InsertPt);
1444     Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1445     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1446     Call->setDoesNotThrow();
1447     Call->setTailCall();
1448 
1449     DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
1450                     "At insertion point: " << *InsertPt << "\n");
1451   }
1452   for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
1453     Value *MyArg = ArgTy == ParamTy ? Arg :
1454                    new BitCastInst(Arg, ParamTy, "", InsertPt);
1455     Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Release);
1456     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1457     // Attach a clang.imprecise_release metadata tag, if appropriate.
1458     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
1459       Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M);
1460     Call->setDoesNotThrow();
1461     if (ReleasesToMove.IsTailCallRelease)
1462       Call->setTailCall();
1463 
1464     DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1465                     "At insertion point: " << *InsertPt << "\n");
1466   }
1467 
1468   // Delete the original retain and release calls.
1469   for (Instruction *OrigRetain : RetainsToMove.Calls) {
1470     Retains.blot(OrigRetain);
1471     DeadInsts.push_back(OrigRetain);
1472     DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
1473   }
1474   for (Instruction *OrigRelease : ReleasesToMove.Calls) {
1475     Releases.erase(OrigRelease);
1476     DeadInsts.push_back(OrigRelease);
1477     DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
1478   }
1479 
1480 }
1481 
1482 bool ObjCARCOpt::PairUpRetainsAndReleases(
1483     DenseMap<const BasicBlock *, BBState> &BBStates,
1484     BlotMapVector<Value *, RRInfo> &Retains,
1485     DenseMap<Value *, RRInfo> &Releases, Module *M,
1486     Instruction *Retain,
1487     SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1488     RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1489     bool &AnyPairsCompletelyEliminated) {
1490   // If a pair happens in a region where it is known that the reference count
1491   // is already incremented, we can similarly ignore possible decrements unless
1492   // we are dealing with a retainable object with multiple provenance sources.
1493   bool KnownSafeTD = true, KnownSafeBU = true;
1494   bool CFGHazardAfflicted = false;
1495 
1496   // Connect the dots between the top-down-collected RetainsToMove and
1497   // bottom-up-collected ReleasesToMove to form sets of related calls.
1498   // This is an iterative process so that we connect multiple releases
1499   // to multiple retains if needed.
1500   unsigned OldDelta = 0;
1501   unsigned NewDelta = 0;
1502   unsigned OldCount = 0;
1503   unsigned NewCount = 0;
1504   bool FirstRelease = true;
1505   for (SmallVector<Instruction *, 4> NewRetains{Retain};;) {
1506     SmallVector<Instruction *, 4> NewReleases;
1507     for (Instruction *NewRetain : NewRetains) {
1508       auto It = Retains.find(NewRetain);
1509       assert(It != Retains.end());
1510       const RRInfo &NewRetainRRI = It->second;
1511       KnownSafeTD &= NewRetainRRI.KnownSafe;
1512       for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1513         auto Jt = Releases.find(NewRetainRelease);
1514         if (Jt == Releases.end())
1515           return false;
1516         const RRInfo &NewRetainReleaseRRI = Jt->second;
1517 
1518         // If the release does not have a reference to the retain as well,
1519         // something happened which is unaccounted for. Do not do anything.
1520         //
1521         // This can happen if we catch an additive overflow during path count
1522         // merging.
1523         if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1524           return false;
1525 
1526         if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
1527 
1528           // If we overflow when we compute the path count, don't remove/move
1529           // anything.
1530           const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
1531           unsigned PathCount = BBState::OverflowOccurredValue;
1532           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1533             return false;
1534           assert(PathCount != BBState::OverflowOccurredValue &&
1535                  "PathCount at this point can not be "
1536                  "OverflowOccurredValue.");
1537           OldDelta -= PathCount;
1538 
1539           // Merge the ReleaseMetadata and IsTailCallRelease values.
1540           if (FirstRelease) {
1541             ReleasesToMove.ReleaseMetadata =
1542               NewRetainReleaseRRI.ReleaseMetadata;
1543             ReleasesToMove.IsTailCallRelease =
1544               NewRetainReleaseRRI.IsTailCallRelease;
1545             FirstRelease = false;
1546           } else {
1547             if (ReleasesToMove.ReleaseMetadata !=
1548                 NewRetainReleaseRRI.ReleaseMetadata)
1549               ReleasesToMove.ReleaseMetadata = nullptr;
1550             if (ReleasesToMove.IsTailCallRelease !=
1551                 NewRetainReleaseRRI.IsTailCallRelease)
1552               ReleasesToMove.IsTailCallRelease = false;
1553           }
1554 
1555           // Collect the optimal insertion points.
1556           if (!KnownSafe)
1557             for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
1558               if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
1559                 // If we overflow when we compute the path count, don't
1560                 // remove/move anything.
1561                 const BBState &RIPBBState = BBStates[RIP->getParent()];
1562                 PathCount = BBState::OverflowOccurredValue;
1563                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1564                   return false;
1565                 assert(PathCount != BBState::OverflowOccurredValue &&
1566                        "PathCount at this point can not be "
1567                        "OverflowOccurredValue.");
1568                 NewDelta -= PathCount;
1569               }
1570             }
1571           NewReleases.push_back(NewRetainRelease);
1572         }
1573       }
1574     }
1575     NewRetains.clear();
1576     if (NewReleases.empty()) break;
1577 
1578     // Back the other way.
1579     for (Instruction *NewRelease : NewReleases) {
1580       auto It = Releases.find(NewRelease);
1581       assert(It != Releases.end());
1582       const RRInfo &NewReleaseRRI = It->second;
1583       KnownSafeBU &= NewReleaseRRI.KnownSafe;
1584       CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
1585       for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
1586         auto Jt = Retains.find(NewReleaseRetain);
1587         if (Jt == Retains.end())
1588           return false;
1589         const RRInfo &NewReleaseRetainRRI = Jt->second;
1590 
1591         // If the retain does not have a reference to the release as well,
1592         // something happened which is unaccounted for. Do not do anything.
1593         //
1594         // This can happen if we catch an additive overflow during path count
1595         // merging.
1596         if (!NewReleaseRetainRRI.Calls.count(NewRelease))
1597           return false;
1598 
1599         if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
1600           // If we overflow when we compute the path count, don't remove/move
1601           // anything.
1602           const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
1603           unsigned PathCount = BBState::OverflowOccurredValue;
1604           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1605             return false;
1606           assert(PathCount != BBState::OverflowOccurredValue &&
1607                  "PathCount at this point can not be "
1608                  "OverflowOccurredValue.");
1609           OldDelta += PathCount;
1610           OldCount += PathCount;
1611 
1612           // Collect the optimal insertion points.
1613           if (!KnownSafe)
1614             for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
1615               if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
1616                 // If we overflow when we compute the path count, don't
1617                 // remove/move anything.
1618                 const BBState &RIPBBState = BBStates[RIP->getParent()];
1619 
1620                 PathCount = BBState::OverflowOccurredValue;
1621                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1622                   return false;
1623                 assert(PathCount != BBState::OverflowOccurredValue &&
1624                        "PathCount at this point can not be "
1625                        "OverflowOccurredValue.");
1626                 NewDelta += PathCount;
1627                 NewCount += PathCount;
1628               }
1629             }
1630           NewRetains.push_back(NewReleaseRetain);
1631         }
1632       }
1633     }
1634     if (NewRetains.empty()) break;
1635   }
1636 
1637   // We can only remove pointers if we are known safe in both directions.
1638   bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
1639   if (UnconditionallySafe) {
1640     RetainsToMove.ReverseInsertPts.clear();
1641     ReleasesToMove.ReverseInsertPts.clear();
1642     NewCount = 0;
1643   } else {
1644     // Determine whether the new insertion points we computed preserve the
1645     // balance of retain and release calls through the program.
1646     // TODO: If the fully aggressive solution isn't valid, try to find a
1647     // less aggressive solution which is.
1648     if (NewDelta != 0)
1649       return false;
1650 
1651     // At this point, we are not going to remove any RR pairs, but we still are
1652     // able to move RR pairs. If one of our pointers is afflicted with
1653     // CFGHazards, we cannot perform such code motion so exit early.
1654     const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
1655       ReleasesToMove.ReverseInsertPts.size();
1656     if (CFGHazardAfflicted && WillPerformCodeMotion)
1657       return false;
1658   }
1659 
1660   // Determine whether the original call points are balanced in the retain and
1661   // release calls through the program. If not, conservatively don't touch
1662   // them.
1663   // TODO: It's theoretically possible to do code motion in this case, as
1664   // long as the existing imbalances are maintained.
1665   if (OldDelta != 0)
1666     return false;
1667 
1668   Changed = true;
1669   assert(OldCount != 0 && "Unreachable code?");
1670   NumRRs += OldCount - NewCount;
1671   // Set to true if we completely removed any RR pairs.
1672   AnyPairsCompletelyEliminated = NewCount == 0;
1673 
1674   // We can move calls!
1675   return true;
1676 }
1677 
1678 /// Identify pairings between the retains and releases, and delete and/or move
1679 /// them.
1680 bool ObjCARCOpt::PerformCodePlacement(
1681     DenseMap<const BasicBlock *, BBState> &BBStates,
1682     BlotMapVector<Value *, RRInfo> &Retains,
1683     DenseMap<Value *, RRInfo> &Releases, Module *M) {
1684   DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
1685 
1686   bool AnyPairsCompletelyEliminated = false;
1687   SmallVector<Instruction *, 8> DeadInsts;
1688 
1689   // Visit each retain.
1690   for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
1691                                                       E = Retains.end();
1692        I != E; ++I) {
1693     Value *V = I->first;
1694     if (!V) continue; // blotted
1695 
1696     Instruction *Retain = cast<Instruction>(V);
1697 
1698     DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
1699 
1700     Value *Arg = GetArgRCIdentityRoot(Retain);
1701 
1702     // If the object being released is in static or stack storage, we know it's
1703     // not being managed by ObjC reference counting, so we can delete pairs
1704     // regardless of what possible decrements or uses lie between them.
1705     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
1706 
1707     // A constant pointer can't be pointing to an object on the heap. It may
1708     // be reference-counted, but it won't be deleted.
1709     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1710       if (const GlobalVariable *GV =
1711             dyn_cast<GlobalVariable>(
1712               GetRCIdentityRoot(LI->getPointerOperand())))
1713         if (GV->isConstant())
1714           KnownSafe = true;
1715 
1716     // Connect the dots between the top-down-collected RetainsToMove and
1717     // bottom-up-collected ReleasesToMove to form sets of related calls.
1718     RRInfo RetainsToMove, ReleasesToMove;
1719 
1720     bool PerformMoveCalls = PairUpRetainsAndReleases(
1721         BBStates, Retains, Releases, M, Retain, DeadInsts,
1722         RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1723         AnyPairsCompletelyEliminated);
1724 
1725     if (PerformMoveCalls) {
1726       // Ok, everything checks out and we're all set. Let's move/delete some
1727       // code!
1728       MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1729                 Retains, Releases, DeadInsts, M);
1730     }
1731   }
1732 
1733   // Now that we're done moving everything, we can delete the newly dead
1734   // instructions, as we no longer need them as insert points.
1735   while (!DeadInsts.empty())
1736     EraseInstruction(DeadInsts.pop_back_val());
1737 
1738   return AnyPairsCompletelyEliminated;
1739 }
1740 
1741 /// Weak pointer optimizations.
1742 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
1743   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
1744 
1745   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
1746   // itself because it uses AliasAnalysis and we need to do provenance
1747   // queries instead.
1748   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1749     Instruction *Inst = &*I++;
1750 
1751     DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
1752 
1753     ARCInstKind Class = GetBasicARCInstKind(Inst);
1754     if (Class != ARCInstKind::LoadWeak &&
1755         Class != ARCInstKind::LoadWeakRetained)
1756       continue;
1757 
1758     // Delete objc_loadWeak calls with no users.
1759     if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
1760       Inst->eraseFromParent();
1761       continue;
1762     }
1763 
1764     // TODO: For now, just look for an earlier available version of this value
1765     // within the same block. Theoretically, we could do memdep-style non-local
1766     // analysis too, but that would want caching. A better approach would be to
1767     // use the technique that EarlyCSE uses.
1768     inst_iterator Current = std::prev(I);
1769     BasicBlock *CurrentBB = &*Current.getBasicBlockIterator();
1770     for (BasicBlock::iterator B = CurrentBB->begin(),
1771                               J = Current.getInstructionIterator();
1772          J != B; --J) {
1773       Instruction *EarlierInst = &*std::prev(J);
1774       ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
1775       switch (EarlierClass) {
1776       case ARCInstKind::LoadWeak:
1777       case ARCInstKind::LoadWeakRetained: {
1778         // If this is loading from the same pointer, replace this load's value
1779         // with that one.
1780         CallInst *Call = cast<CallInst>(Inst);
1781         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1782         Value *Arg = Call->getArgOperand(0);
1783         Value *EarlierArg = EarlierCall->getArgOperand(0);
1784         switch (PA.getAA()->alias(Arg, EarlierArg)) {
1785         case MustAlias:
1786           Changed = true;
1787           // If the load has a builtin retain, insert a plain retain for it.
1788           if (Class == ARCInstKind::LoadWeakRetained) {
1789             Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1790             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
1791             CI->setTailCall();
1792           }
1793           // Zap the fully redundant load.
1794           Call->replaceAllUsesWith(EarlierCall);
1795           Call->eraseFromParent();
1796           goto clobbered;
1797         case MayAlias:
1798         case PartialAlias:
1799           goto clobbered;
1800         case NoAlias:
1801           break;
1802         }
1803         break;
1804       }
1805       case ARCInstKind::StoreWeak:
1806       case ARCInstKind::InitWeak: {
1807         // If this is storing to the same pointer and has the same size etc.
1808         // replace this load's value with the stored value.
1809         CallInst *Call = cast<CallInst>(Inst);
1810         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1811         Value *Arg = Call->getArgOperand(0);
1812         Value *EarlierArg = EarlierCall->getArgOperand(0);
1813         switch (PA.getAA()->alias(Arg, EarlierArg)) {
1814         case MustAlias:
1815           Changed = true;
1816           // If the load has a builtin retain, insert a plain retain for it.
1817           if (Class == ARCInstKind::LoadWeakRetained) {
1818             Constant *Decl = EP.get(ARCRuntimeEntryPointKind::Retain);
1819             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
1820             CI->setTailCall();
1821           }
1822           // Zap the fully redundant load.
1823           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
1824           Call->eraseFromParent();
1825           goto clobbered;
1826         case MayAlias:
1827         case PartialAlias:
1828           goto clobbered;
1829         case NoAlias:
1830           break;
1831         }
1832         break;
1833       }
1834       case ARCInstKind::MoveWeak:
1835       case ARCInstKind::CopyWeak:
1836         // TOOD: Grab the copied value.
1837         goto clobbered;
1838       case ARCInstKind::AutoreleasepoolPush:
1839       case ARCInstKind::None:
1840       case ARCInstKind::IntrinsicUser:
1841       case ARCInstKind::User:
1842         // Weak pointers are only modified through the weak entry points
1843         // (and arbitrary calls, which could call the weak entry points).
1844         break;
1845       default:
1846         // Anything else could modify the weak pointer.
1847         goto clobbered;
1848       }
1849     }
1850   clobbered:;
1851   }
1852 
1853   // Then, for each destroyWeak with an alloca operand, check to see if
1854   // the alloca and all its users can be zapped.
1855   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1856     Instruction *Inst = &*I++;
1857     ARCInstKind Class = GetBasicARCInstKind(Inst);
1858     if (Class != ARCInstKind::DestroyWeak)
1859       continue;
1860 
1861     CallInst *Call = cast<CallInst>(Inst);
1862     Value *Arg = Call->getArgOperand(0);
1863     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
1864       for (User *U : Alloca->users()) {
1865         const Instruction *UserInst = cast<Instruction>(U);
1866         switch (GetBasicARCInstKind(UserInst)) {
1867         case ARCInstKind::InitWeak:
1868         case ARCInstKind::StoreWeak:
1869         case ARCInstKind::DestroyWeak:
1870           continue;
1871         default:
1872           goto done;
1873         }
1874       }
1875       Changed = true;
1876       for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
1877         CallInst *UserInst = cast<CallInst>(*UI++);
1878         switch (GetBasicARCInstKind(UserInst)) {
1879         case ARCInstKind::InitWeak:
1880         case ARCInstKind::StoreWeak:
1881           // These functions return their second argument.
1882           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
1883           break;
1884         case ARCInstKind::DestroyWeak:
1885           // No return value.
1886           break;
1887         default:
1888           llvm_unreachable("alloca really is used!");
1889         }
1890         UserInst->eraseFromParent();
1891       }
1892       Alloca->eraseFromParent();
1893     done:;
1894     }
1895   }
1896 }
1897 
1898 /// Identify program paths which execute sequences of retains and releases which
1899 /// can be eliminated.
1900 bool ObjCARCOpt::OptimizeSequences(Function &F) {
1901   // Releases, Retains - These are used to store the results of the main flow
1902   // analysis. These use Value* as the key instead of Instruction* so that the
1903   // map stays valid when we get around to rewriting code and calls get
1904   // replaced by arguments.
1905   DenseMap<Value *, RRInfo> Releases;
1906   BlotMapVector<Value *, RRInfo> Retains;
1907 
1908   // This is used during the traversal of the function to track the
1909   // states for each identified object at each block.
1910   DenseMap<const BasicBlock *, BBState> BBStates;
1911 
1912   // Analyze the CFG of the function, and all instructions.
1913   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1914 
1915   // Transform.
1916   bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1917                                                            Releases,
1918                                                            F.getParent());
1919 
1920   return AnyPairsCompletelyEliminated && NestingDetected;
1921 }
1922 
1923 /// Check if there is a dependent call earlier that does not have anything in
1924 /// between the Retain and the call that can affect the reference count of their
1925 /// shared pointer argument. Note that Retain need not be in BB.
1926 static bool
1927 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
1928                              SmallPtrSetImpl<Instruction *> &DepInsts,
1929                              SmallPtrSetImpl<const BasicBlock *> &Visited,
1930                              ProvenanceAnalysis &PA) {
1931   FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
1932                    DepInsts, Visited, PA);
1933   if (DepInsts.size() != 1)
1934     return false;
1935 
1936   auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1937 
1938   // Check that the pointer is the return value of the call.
1939   if (!Call || Arg != Call)
1940     return false;
1941 
1942   // Check that the call is a regular call.
1943   ARCInstKind Class = GetBasicARCInstKind(Call);
1944   return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call;
1945 }
1946 
1947 /// Find a dependent retain that precedes the given autorelease for which there
1948 /// is nothing in between the two instructions that can affect the ref count of
1949 /// Arg.
1950 static CallInst *
1951 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
1952                                   Instruction *Autorelease,
1953                                   SmallPtrSetImpl<Instruction *> &DepInsts,
1954                                   SmallPtrSetImpl<const BasicBlock *> &Visited,
1955                                   ProvenanceAnalysis &PA) {
1956   FindDependencies(CanChangeRetainCount, Arg,
1957                    BB, Autorelease, DepInsts, Visited, PA);
1958   if (DepInsts.size() != 1)
1959     return nullptr;
1960 
1961   auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1962 
1963   // Check that we found a retain with the same argument.
1964   if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
1965       GetArgRCIdentityRoot(Retain) != Arg) {
1966     return nullptr;
1967   }
1968 
1969   return Retain;
1970 }
1971 
1972 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
1973 /// no instructions dependent on Arg that need a positive ref count in between
1974 /// the autorelease and the ret.
1975 static CallInst *
1976 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
1977                                        ReturnInst *Ret,
1978                                        SmallPtrSetImpl<Instruction *> &DepInsts,
1979                                        SmallPtrSetImpl<const BasicBlock *> &V,
1980                                        ProvenanceAnalysis &PA) {
1981   FindDependencies(NeedsPositiveRetainCount, Arg,
1982                    BB, Ret, DepInsts, V, PA);
1983   if (DepInsts.size() != 1)
1984     return nullptr;
1985 
1986   auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1987   if (!Autorelease)
1988     return nullptr;
1989   ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
1990   if (!IsAutorelease(AutoreleaseClass))
1991     return nullptr;
1992   if (GetArgRCIdentityRoot(Autorelease) != Arg)
1993     return nullptr;
1994 
1995   return Autorelease;
1996 }
1997 
1998 /// Look for this pattern:
1999 /// \code
2000 ///    %call = call i8* @something(...)
2001 ///    %2 = call i8* @objc_retain(i8* %call)
2002 ///    %3 = call i8* @objc_autorelease(i8* %2)
2003 ///    ret i8* %3
2004 /// \endcode
2005 /// And delete the retain and autorelease.
2006 void ObjCARCOpt::OptimizeReturns(Function &F) {
2007   if (!F.getReturnType()->isPointerTy())
2008     return;
2009 
2010   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2011 
2012   SmallPtrSet<Instruction *, 4> DependingInstructions;
2013   SmallPtrSet<const BasicBlock *, 4> Visited;
2014   for (BasicBlock &BB: F) {
2015     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back());
2016     if (!Ret)
2017       continue;
2018 
2019     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2020 
2021     const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
2022 
2023     // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2024     // dependent on Arg such that there are no instructions dependent on Arg
2025     // that need a positive ref count in between the autorelease and Ret.
2026     CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath(
2027         Arg, &BB, Ret, DependingInstructions, Visited, PA);
2028     DependingInstructions.clear();
2029     Visited.clear();
2030 
2031     if (!Autorelease)
2032       continue;
2033 
2034     CallInst *Retain = FindPredecessorRetainWithSafePath(
2035         Arg, Autorelease->getParent(), Autorelease, DependingInstructions,
2036         Visited, PA);
2037     DependingInstructions.clear();
2038     Visited.clear();
2039 
2040     if (!Retain)
2041       continue;
2042 
2043     // Check that there is nothing that can affect the reference count
2044     // between the retain and the call.  Note that Retain need not be in BB.
2045     bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2046                                                           DependingInstructions,
2047                                                           Visited, PA);
2048     DependingInstructions.clear();
2049     Visited.clear();
2050 
2051     if (!HasSafePathToCall)
2052       continue;
2053 
2054     // If so, we can zap the retain and autorelease.
2055     Changed = true;
2056     ++NumRets;
2057     DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2058           << *Autorelease << "\n");
2059     EraseInstruction(Retain);
2060     EraseInstruction(Autorelease);
2061   }
2062 }
2063 
2064 #ifndef NDEBUG
2065 void
2066 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2067   llvm::Statistic &NumRetains =
2068     AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2069   llvm::Statistic &NumReleases =
2070     AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2071 
2072   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2073     Instruction *Inst = &*I++;
2074     switch (GetBasicARCInstKind(Inst)) {
2075     default:
2076       break;
2077     case ARCInstKind::Retain:
2078       ++NumRetains;
2079       break;
2080     case ARCInstKind::Release:
2081       ++NumReleases;
2082       break;
2083     }
2084   }
2085 }
2086 #endif
2087 
2088 bool ObjCARCOpt::doInitialization(Module &M) {
2089   if (!EnableARCOpts)
2090     return false;
2091 
2092   // If nothing in the Module uses ARC, don't do anything.
2093   Run = ModuleHasARC(M);
2094   if (!Run)
2095     return false;
2096 
2097   // Intuitively, objc_retain and others are nocapture, however in practice
2098   // they are not, because they return their argument value. And objc_release
2099   // calls finalizers which can have arbitrary side effects.
2100   MDKindCache.init(&M);
2101 
2102   // Initialize our runtime entry point cache.
2103   EP.init(&M);
2104 
2105   return false;
2106 }
2107 
2108 bool ObjCARCOpt::runOnFunction(Function &F) {
2109   if (!EnableARCOpts)
2110     return false;
2111 
2112   // If nothing in the Module uses ARC, don't do anything.
2113   if (!Run)
2114     return false;
2115 
2116   Changed = false;
2117 
2118   DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2119         "\n");
2120 
2121   PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
2122 
2123 #ifndef NDEBUG
2124   if (AreStatisticsEnabled()) {
2125     GatherStatistics(F, false);
2126   }
2127 #endif
2128 
2129   // This pass performs several distinct transformations. As a compile-time aid
2130   // when compiling code that isn't ObjC, skip these if the relevant ObjC
2131   // library functions aren't declared.
2132 
2133   // Preliminary optimizations. This also computes UsedInThisFunction.
2134   OptimizeIndividualCalls(F);
2135 
2136   // Optimizations for weak pointers.
2137   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2138                             (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2139                             (1 << unsigned(ARCInstKind::StoreWeak)) |
2140                             (1 << unsigned(ARCInstKind::InitWeak)) |
2141                             (1 << unsigned(ARCInstKind::CopyWeak)) |
2142                             (1 << unsigned(ARCInstKind::MoveWeak)) |
2143                             (1 << unsigned(ARCInstKind::DestroyWeak))))
2144     OptimizeWeakCalls(F);
2145 
2146   // Optimizations for retain+release pairs.
2147   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2148                             (1 << unsigned(ARCInstKind::RetainRV)) |
2149                             (1 << unsigned(ARCInstKind::RetainBlock))))
2150     if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
2151       // Run OptimizeSequences until it either stops making changes or
2152       // no retain+release pair nesting is detected.
2153       while (OptimizeSequences(F)) {}
2154 
2155   // Optimizations if objc_autorelease is used.
2156   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2157                             (1 << unsigned(ARCInstKind::AutoreleaseRV))))
2158     OptimizeReturns(F);
2159 
2160   // Gather statistics after optimization.
2161 #ifndef NDEBUG
2162   if (AreStatisticsEnabled()) {
2163     GatherStatistics(F, true);
2164   }
2165 #endif
2166 
2167   DEBUG(dbgs() << "\n");
2168 
2169   return Changed;
2170 }
2171 
2172 void ObjCARCOpt::releaseMemory() {
2173   PA.clear();
2174 }
2175 
2176 /// @}
2177 ///
2178