[objc-arc] Change some casts and loop iterators to use auto.
[oota-llvm.git] / lib / Transforms / ObjCARC / ObjCARCOpts.cpp
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 "ObjCARC.h"
28 #include "ARCRuntimeEntryPoints.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "BlotMapVector.h"
33 #include "PtrState.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/DenseSet.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/Statistic.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   if (Arg->hasOneUse()) {
57     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
58       return FindSingleUseIdentifiedObject(BC->getOperand(0));
59     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
60       if (GEP->hasAllZeroIndices())
61         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
62     if (IsForwarding(GetBasicARCInstKind(Arg)))
63       return FindSingleUseIdentifiedObject(
64                cast<CallInst>(Arg)->getArgOperand(0));
65     if (!IsObjCIdentifiedObject(Arg))
66       return nullptr;
67     return Arg;
68   }
69
70   // If we found an identifiable object but it has multiple uses, but they are
71   // trivial uses, we can still consider this to be a single-use value.
72   if (IsObjCIdentifiedObject(Arg)) {
73     for (const User *U : Arg->users())
74       if (!U->use_empty() || GetRCIdentityRoot(U) != Arg)
75          return nullptr;
76
77     return Arg;
78   }
79
80   return nullptr;
81 }
82
83 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
84 /// GetUnderlyingObjects except that it returns early when it sees the first
85 /// alloca.
86 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
87   SmallPtrSet<const Value *, 4> Visited;
88   SmallVector<const Value *, 4> Worklist;
89   Worklist.push_back(V);
90   do {
91     const Value *P = Worklist.pop_back_val();
92     P = GetUnderlyingObjCPtr(P);
93
94     if (isa<AllocaInst>(P))
95       return true;
96
97     if (!Visited.insert(P).second)
98       continue;
99
100     if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
101       Worklist.push_back(SI->getTrueValue());
102       Worklist.push_back(SI->getFalseValue());
103       continue;
104     }
105
106     if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
107       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
108         Worklist.push_back(PN->getIncomingValue(i));
109       continue;
110     }
111   } while (!Worklist.empty());
112
113   return false;
114 }
115
116
117 /// @}
118 ///
119 /// \defgroup ARCOpt ARC Optimization.
120 /// @{
121
122 // TODO: On code like this:
123 //
124 // objc_retain(%x)
125 // stuff_that_cannot_release()
126 // objc_autorelease(%x)
127 // stuff_that_cannot_release()
128 // objc_retain(%x)
129 // stuff_that_cannot_release()
130 // objc_autorelease(%x)
131 //
132 // The second retain and autorelease can be deleted.
133
134 // TODO: It should be possible to delete
135 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
136 // pairs if nothing is actually autoreleased between them. Also, autorelease
137 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
138 // after inlining) can be turned into plain release calls.
139
140 // TODO: Critical-edge splitting. If the optimial insertion point is
141 // a critical edge, the current algorithm has to fail, because it doesn't
142 // know how to split edges. It should be possible to make the optimizer
143 // think in terms of edges, rather than blocks, and then split critical
144 // edges on demand.
145
146 // TODO: OptimizeSequences could generalized to be Interprocedural.
147
148 // TODO: Recognize that a bunch of other objc runtime calls have
149 // non-escaping arguments and non-releasing arguments, and may be
150 // non-autoreleasing.
151
152 // TODO: Sink autorelease calls as far as possible. Unfortunately we
153 // usually can't sink them past other calls, which would be the main
154 // case where it would be useful.
155
156 // TODO: The pointer returned from objc_loadWeakRetained is retained.
157
158 // TODO: Delete release+retain pairs (rare).
159
160 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
161 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
162 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
163 STATISTIC(NumRets,        "Number of return value forwarding "
164                           "retain+autoreleases eliminated");
165 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
166 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
167 #ifndef NDEBUG
168 STATISTIC(NumRetainsBeforeOpt,
169           "Number of retains before optimization");
170 STATISTIC(NumReleasesBeforeOpt,
171           "Number of releases before optimization");
172 STATISTIC(NumRetainsAfterOpt,
173           "Number of retains after optimization");
174 STATISTIC(NumReleasesAfterOpt,
175           "Number of releases after optimization");
176 #endif
177
178 namespace {
179   /// \brief Per-BasicBlock state.
180   class BBState {
181     /// The number of unique control paths from the entry which can reach this
182     /// block.
183     unsigned TopDownPathCount;
184
185     /// The number of unique control paths to exits from this block.
186     unsigned BottomUpPathCount;
187
188     /// A type for PerPtrTopDown and PerPtrBottomUp.
189     typedef BlotMapVector<const Value *, PtrState> MapTy;
190
191     /// The top-down traversal uses this to record information known about a
192     /// pointer at the bottom of each block.
193     MapTy PerPtrTopDown;
194
195     /// The bottom-up traversal uses this to record information known about a
196     /// pointer at the top of each block.
197     MapTy PerPtrBottomUp;
198
199     /// Effective predecessors of the current block ignoring ignorable edges and
200     /// ignored backedges.
201     SmallVector<BasicBlock *, 2> Preds;
202     /// Effective successors of the current block ignoring ignorable edges and
203     /// ignored backedges.
204     SmallVector<BasicBlock *, 2> Succs;
205
206   public:
207     static const unsigned OverflowOccurredValue;
208
209     BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
210
211     typedef MapTy::iterator ptr_iterator;
212     typedef MapTy::const_iterator ptr_const_iterator;
213
214     ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
215     ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
216     ptr_const_iterator top_down_ptr_begin() const {
217       return PerPtrTopDown.begin();
218     }
219     ptr_const_iterator top_down_ptr_end() const {
220       return PerPtrTopDown.end();
221     }
222
223     ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
224     ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
225     ptr_const_iterator bottom_up_ptr_begin() const {
226       return PerPtrBottomUp.begin();
227     }
228     ptr_const_iterator bottom_up_ptr_end() const {
229       return PerPtrBottomUp.end();
230     }
231
232     /// Mark this block as being an entry block, which has one path from the
233     /// entry by definition.
234     void SetAsEntry() { TopDownPathCount = 1; }
235
236     /// Mark this block as being an exit block, which has one path to an exit by
237     /// definition.
238     void SetAsExit()  { BottomUpPathCount = 1; }
239
240     /// Attempt to find the PtrState object describing the top down state for
241     /// pointer Arg. Return a new initialized PtrState describing the top down
242     /// state for Arg if we do not find one.
243     PtrState &getPtrTopDownState(const Value *Arg) {
244       return PerPtrTopDown[Arg];
245     }
246
247     /// Attempt to find the PtrState object describing the bottom up state for
248     /// pointer Arg. Return a new initialized PtrState describing the bottom up
249     /// state for Arg if we do not find one.
250     PtrState &getPtrBottomUpState(const Value *Arg) {
251       return PerPtrBottomUp[Arg];
252     }
253
254     /// Attempt to find the PtrState object describing the bottom up state for
255     /// pointer Arg.
256     ptr_iterator findPtrBottomUpState(const Value *Arg) {
257       return PerPtrBottomUp.find(Arg);
258     }
259
260     void clearBottomUpPointers() {
261       PerPtrBottomUp.clear();
262     }
263
264     void clearTopDownPointers() {
265       PerPtrTopDown.clear();
266     }
267
268     void InitFromPred(const BBState &Other);
269     void InitFromSucc(const BBState &Other);
270     void MergePred(const BBState &Other);
271     void MergeSucc(const BBState &Other);
272
273     /// Compute the number of possible unique paths from an entry to an exit
274     /// which pass through this block. This is only valid after both the
275     /// top-down and bottom-up traversals are complete.
276     ///
277     /// Returns true if overflow occurred. Returns false if overflow did not
278     /// occur.
279     bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
280       if (TopDownPathCount == OverflowOccurredValue ||
281           BottomUpPathCount == OverflowOccurredValue)
282         return true;
283       unsigned long long Product =
284         (unsigned long long)TopDownPathCount*BottomUpPathCount;
285       // Overflow occurred if any of the upper bits of Product are set or if all
286       // the lower bits of Product are all set.
287       return (Product >> 32) ||
288              ((PathCount = Product) == OverflowOccurredValue);
289     }
290
291     // Specialized CFG utilities.
292     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
293     edge_iterator pred_begin() const { return Preds.begin(); }
294     edge_iterator pred_end() const { return Preds.end(); }
295     edge_iterator succ_begin() const { return Succs.begin(); }
296     edge_iterator succ_end() const { return Succs.end(); }
297
298     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
299     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
300
301     bool isExit() const { return Succs.empty(); }
302   };
303
304   const unsigned BBState::OverflowOccurredValue = 0xffffffff;
305 }
306
307 void BBState::InitFromPred(const BBState &Other) {
308   PerPtrTopDown = Other.PerPtrTopDown;
309   TopDownPathCount = Other.TopDownPathCount;
310 }
311
312 void BBState::InitFromSucc(const BBState &Other) {
313   PerPtrBottomUp = Other.PerPtrBottomUp;
314   BottomUpPathCount = Other.BottomUpPathCount;
315 }
316
317 /// The top-down traversal uses this to merge information about predecessors to
318 /// form the initial state for a new block.
319 void BBState::MergePred(const BBState &Other) {
320   if (TopDownPathCount == OverflowOccurredValue)
321     return;
322
323   // Other.TopDownPathCount can be 0, in which case it is either dead or a
324   // loop backedge. Loop backedges are special.
325   TopDownPathCount += Other.TopDownPathCount;
326
327   // In order to be consistent, we clear the top down pointers when by adding
328   // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
329   // has not occurred.
330   if (TopDownPathCount == OverflowOccurredValue) {
331     clearTopDownPointers();
332     return;
333   }
334
335   // Check for overflow. If we have overflow, fall back to conservative
336   // behavior.
337   if (TopDownPathCount < Other.TopDownPathCount) {
338     TopDownPathCount = OverflowOccurredValue;
339     clearTopDownPointers();
340     return;
341   }
342
343   // For each entry in the other set, if our set has an entry with the same key,
344   // merge the entries. Otherwise, copy the entry and merge it with an empty
345   // entry.
346   for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
347        MI != ME; ++MI) {
348     std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
349     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
350                              /*TopDown=*/true);
351   }
352
353   // For each entry in our set, if the other set doesn't have an entry with the
354   // same key, force it to merge with an empty entry.
355   for (auto MI = top_down_ptr_begin(), ME = top_down_ptr_end(); MI != ME; ++MI)
356     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
357       MI->second.Merge(PtrState(), /*TopDown=*/true);
358 }
359
360 /// The bottom-up traversal uses this to merge information about successors to
361 /// form the initial state for a new block.
362 void BBState::MergeSucc(const BBState &Other) {
363   if (BottomUpPathCount == OverflowOccurredValue)
364     return;
365
366   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
367   // loop backedge. Loop backedges are special.
368   BottomUpPathCount += Other.BottomUpPathCount;
369
370   // In order to be consistent, we clear the top down pointers when by adding
371   // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
372   // has not occurred.
373   if (BottomUpPathCount == OverflowOccurredValue) {
374     clearBottomUpPointers();
375     return;
376   }
377
378   // Check for overflow. If we have overflow, fall back to conservative
379   // behavior.
380   if (BottomUpPathCount < Other.BottomUpPathCount) {
381     BottomUpPathCount = OverflowOccurredValue;
382     clearBottomUpPointers();
383     return;
384   }
385
386   // For each entry in the other set, if our set has an entry with the
387   // same key, merge the entries. Otherwise, copy the entry and merge
388   // it with an empty entry.
389   for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
390        MI != ME; ++MI) {
391     std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
392     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
393                              /*TopDown=*/false);
394   }
395
396   // For each entry in our set, if the other set doesn't have an entry
397   // with the same key, force it to merge with an empty entry.
398   for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME;
399        ++MI)
400     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
401       MI->second.Merge(PtrState(), /*TopDown=*/false);
402 }
403
404 // Only enable ARC Annotations if we are building a debug version of
405 // libObjCARCOpts.
406 #ifndef NDEBUG
407 #define ARC_ANNOTATIONS
408 #endif
409
410 // Define some macros along the lines of DEBUG and some helper functions to make
411 // it cleaner to create annotations in the source code and to no-op when not
412 // building in debug mode.
413 #ifdef ARC_ANNOTATIONS
414
415 #include "llvm/Support/CommandLine.h"
416
417 /// Enable/disable ARC sequence annotations.
418 static cl::opt<bool>
419 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
420                      cl::desc("Enable emission of arc data flow analysis "
421                               "annotations"));
422 static cl::opt<bool>
423 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
424                           cl::desc("Disable check for cfg hazards when "
425                                    "annotating"));
426 static cl::opt<std::string>
427 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
428                               cl::init(""),
429                               cl::desc("filter out all data flow annotations "
430                                        "but those that apply to the given "
431                                        "target llvm identifier."));
432
433 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
434 /// instruction so that we can track backwards when post processing via the llvm
435 /// arc annotation processor tool. If the function is an
436 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
437                                          Value *Ptr) {
438   MDString *Hash = nullptr;
439
440   // If pointer is a result of an instruction and it does not have a source
441   // MDNode it, attach a new MDNode onto it. If pointer is a result of
442   // an instruction and does have a source MDNode attached to it, return a
443   // reference to said Node. Otherwise just return 0.
444   if (auto *Inst = dyn_cast<Instruction>(Ptr)) {
445     MDNode *Node;
446     if (!(Node = Inst->getMetadata(NodeId))) {
447       // We do not have any node. Generate and attatch the hash MDString to the
448       // instruction.
449
450       // We just use an MDString to ensure that this metadata gets written out
451       // of line at the module level and to provide a very simple format
452       // encoding the information herein. Both of these makes it simpler to
453       // parse the annotations by a simple external program.
454       std::string Str;
455       raw_string_ostream os(Str);
456       os << "(" << Inst->getParent()->getParent()->getName() << ",%"
457          << Inst->getName() << ")";
458
459       Hash = MDString::get(Inst->getContext(), os.str());
460       Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
461     } else {
462       // We have a node. Grab its hash and return it.
463       assert(Node->getNumOperands() == 1 &&
464         "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
465       Hash = cast<MDString>(Node->getOperand(0));
466     }
467   } else if (auto *Arg = dyn_cast<Argument>(Ptr)) {
468     std::string str;
469     raw_string_ostream os(str);
470     os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
471        << ")";
472     Hash = MDString::get(Arg->getContext(), os.str());
473   }
474
475   return Hash;
476 }
477
478 static std::string SequenceToString(Sequence A) {
479   std::string str;
480   raw_string_ostream os(str);
481   os << A;
482   return os.str();
483 }
484
485 /// Helper function to change a Sequence into a String object using our overload
486 /// for raw_ostream so we only have printing code in one location.
487 static MDString *SequenceToMDString(LLVMContext &Context,
488                                     Sequence A) {
489   return MDString::get(Context, SequenceToString(A));
490 }
491
492 /// A simple function to generate a MDNode which describes the change in state
493 /// for Value *Ptr caused by Instruction *Inst.
494 static void AppendMDNodeToInstForPtr(unsigned NodeId,
495                                      Instruction *Inst,
496                                      Value *Ptr,
497                                      MDString *PtrSourceMDNodeID,
498                                      Sequence OldSeq,
499                                      Sequence NewSeq) {
500   MDNode *Node = nullptr;
501   Metadata *tmp[3] = {PtrSourceMDNodeID,
502                       SequenceToMDString(Inst->getContext(), OldSeq),
503                       SequenceToMDString(Inst->getContext(), NewSeq)};
504   Node = MDNode::get(Inst->getContext(), tmp);
505
506   Inst->setMetadata(NodeId, Node);
507 }
508
509 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
510 /// state of a pointer at the entrance to a basic block.
511 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
512                                             Value *Ptr, Sequence Seq) {
513   // If we have a target identifier, make sure that we match it before
514   // continuing.
515   if(!ARCAnnotationTargetIdentifier.empty() &&
516      !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
517     return;
518
519   Module *M = BB->getParent()->getParent();
520   LLVMContext &C = M->getContext();
521   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
522   Type *I8XX = PointerType::getUnqual(I8X);
523   Type *Params[] = {I8XX, I8XX};
524   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
525                                         /*isVarArg=*/false);
526   Constant *Callee = M->getOrInsertFunction(Name, FTy);
527
528   IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
529
530   Value *PtrName;
531   StringRef Tmp = Ptr->getName();
532   if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
533     Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
534                                                          Tmp + "_STR");
535     PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
536                                  cast<Constant>(ActualPtrName), Tmp);
537   }
538
539   Value *S;
540   std::string SeqStr = SequenceToString(Seq);
541   if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
542     Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
543                                                          SeqStr + "_STR");
544     S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
545                            cast<Constant>(ActualPtrName), SeqStr);
546   }
547
548   Builder.CreateCall2(Callee, PtrName, S);
549 }
550
551 /// Add to the end of the basic block llvm.ptr.annotations which show the state
552 /// of the pointer at the bottom of the basic block.
553 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
554                                               Value *Ptr, Sequence Seq) {
555   // If we have a target identifier, make sure that we match it before emitting
556   // an annotation.
557   if(!ARCAnnotationTargetIdentifier.empty() &&
558      !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
559     return;
560
561   Module *M = BB->getParent()->getParent();
562   LLVMContext &C = M->getContext();
563   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
564   Type *I8XX = PointerType::getUnqual(I8X);
565   Type *Params[] = {I8XX, I8XX};
566   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C), Params,
567                                         /*isVarArg=*/false);
568   Constant *Callee = M->getOrInsertFunction(Name, FTy);
569
570   IRBuilder<> Builder(BB, std::prev(BB->end()));
571
572   Value *PtrName;
573   StringRef Tmp = Ptr->getName();
574   if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
575     Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
576                                                          Tmp + "_STR");
577     PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
578                                  cast<Constant>(ActualPtrName), Tmp);
579   }
580
581   Value *S;
582   std::string SeqStr = SequenceToString(Seq);
583   if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
584     Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
585                                                          SeqStr + "_STR");
586     S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
587                            cast<Constant>(ActualPtrName), SeqStr);
588   }
589   Builder.CreateCall2(Callee, PtrName, S);
590 }
591
592 /// Adds a source annotation to pointer and a state change annotation to Inst
593 /// referencing the source annotation and the old/new state of pointer.
594 static void GenerateARCAnnotation(unsigned InstMDId,
595                                   unsigned PtrMDId,
596                                   Instruction *Inst,
597                                   Value *Ptr,
598                                   Sequence OldSeq,
599                                   Sequence NewSeq) {
600   if (EnableARCAnnotations) {
601     // If we have a target identifier, make sure that we match it before
602     // emitting an annotation.
603     if(!ARCAnnotationTargetIdentifier.empty() &&
604        !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
605       return;
606
607     // First generate the source annotation on our pointer. This will return an
608     // MDString* if Ptr actually comes from an instruction implying we can put
609     // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
610     // then we know that our pointer is from an Argument so we put a reference
611     // to the argument number.
612     //
613     // The point of this is to make it easy for the
614     // llvm-arc-annotation-processor tool to cross reference where the source
615     // pointer is in the LLVM IR since the LLVM IR parser does not submit such
616     // information via debug info for backends to use (since why would anyone
617     // need such a thing from LLVM IR besides in non-standard cases
618     // [i.e. this]).
619     MDString *SourcePtrMDNode =
620       AppendMDNodeToSourcePtr(PtrMDId, Ptr);
621     AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
622                              NewSeq);
623   }
624 }
625
626 // The actual interface for accessing the above functionality is defined via
627 // some simple macros which are defined below. We do this so that the user does
628 // not need to pass in what metadata id is needed resulting in cleaner code and
629 // additionally since it provides an easy way to conditionally no-op all
630 // annotation support in a non-debug build.
631
632 /// Use this macro to annotate a sequence state change when processing
633 /// instructions bottom up,
634 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)                          \
635   GenerateARCAnnotation(ARCAnnotationBottomUpMDKind,                    \
636                         ARCAnnotationProvenanceSourceMDKind, (inst),    \
637                         const_cast<Value*>(ptr), (old), (new))
638 /// Use this macro to annotate a sequence state change when processing
639 /// instructions top down.
640 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)                           \
641   GenerateARCAnnotation(ARCAnnotationTopDownMDKind,                     \
642                         ARCAnnotationProvenanceSourceMDKind, (inst),    \
643                         const_cast<Value*>(ptr), (old), (new))
644
645 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction)                   \
646   do {                                                                        \
647     if (EnableARCAnnotations) {                                               \
648       for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
649           E = (_states)._direction##_ptr_end(); I != E; ++I) {                \
650         Value *Ptr = const_cast<Value*>(I->first);                            \
651         Sequence Seq = I->second.GetSeq();                                    \
652         GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq);         \
653       }                                                                       \
654     }                                                                         \
655   } while (0)
656
657 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock)                       \
658     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
659                 Entrance, bottom_up)
660 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock)                         \
661     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend",   \
662                 Terminator, bottom_up)
663 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock)                        \
664     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart",  \
665                 Entrance, top_down)
666 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock)                          \
667     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend",    \
668                 Terminator, top_down)
669
670 #else // !ARC_ANNOTATION
671 // If annotations are off, noop.
672 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
673 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
674 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
675 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
676 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
677 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
678 #endif // !ARC_ANNOTATION
679
680 namespace {
681   /// \brief The main ARC optimization pass.
682   class ObjCARCOpt : public FunctionPass {
683     bool Changed;
684     ProvenanceAnalysis PA;
685     ARCRuntimeEntryPoints EP;
686
687     // This is used to track if a pointer is stored into an alloca.
688     DenseSet<const Value *> MultiOwnersSet;
689
690     /// A flag indicating whether this optimization pass should run.
691     bool Run;
692
693     /// Flags which determine whether each of the interesting runtine functions
694     /// is in fact used in the current function.
695     unsigned UsedInThisFunction;
696
697     /// The Metadata Kind for clang.imprecise_release metadata.
698     unsigned ImpreciseReleaseMDKind;
699
700     /// The Metadata Kind for clang.arc.copy_on_escape metadata.
701     unsigned CopyOnEscapeMDKind;
702
703     /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
704     unsigned NoObjCARCExceptionsMDKind;
705
706 #ifdef ARC_ANNOTATIONS
707     /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
708     unsigned ARCAnnotationBottomUpMDKind;
709     /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
710     unsigned ARCAnnotationTopDownMDKind;
711     /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
712     unsigned ARCAnnotationProvenanceSourceMDKind;
713 #endif // ARC_ANNOATIONS
714
715     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
716     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
717                                    ARCInstKind &Class);
718     void OptimizeIndividualCalls(Function &F);
719
720     void CheckForCFGHazards(const BasicBlock *BB,
721                             DenseMap<const BasicBlock *, BBState> &BBStates,
722                             BBState &MyStates) const;
723     bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB,
724                                   BlotMapVector<Value *, RRInfo> &Retains,
725                                   BBState &MyStates);
726     bool VisitBottomUp(BasicBlock *BB,
727                        DenseMap<const BasicBlock *, BBState> &BBStates,
728                        BlotMapVector<Value *, RRInfo> &Retains);
729     bool VisitInstructionTopDown(Instruction *Inst,
730                                  DenseMap<Value *, RRInfo> &Releases,
731                                  BBState &MyStates);
732     bool VisitTopDown(BasicBlock *BB,
733                       DenseMap<const BasicBlock *, BBState> &BBStates,
734                       DenseMap<Value *, RRInfo> &Releases);
735     bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates,
736                BlotMapVector<Value *, RRInfo> &Retains,
737                DenseMap<Value *, RRInfo> &Releases);
738
739     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
740                    BlotMapVector<Value *, RRInfo> &Retains,
741                    DenseMap<Value *, RRInfo> &Releases,
742                    SmallVectorImpl<Instruction *> &DeadInsts, Module *M);
743
744     bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
745                                BlotMapVector<Value *, RRInfo> &Retains,
746                                DenseMap<Value *, RRInfo> &Releases, Module *M,
747                                SmallVectorImpl<Instruction *> &NewRetains,
748                                SmallVectorImpl<Instruction *> &NewReleases,
749                                SmallVectorImpl<Instruction *> &DeadInsts,
750                                RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
751                                Value *Arg, bool KnownSafe,
752                                bool &AnyPairsCompletelyEliminated);
753
754     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
755                               BlotMapVector<Value *, RRInfo> &Retains,
756                               DenseMap<Value *, RRInfo> &Releases, Module *M);
757
758     void OptimizeWeakCalls(Function &F);
759
760     bool OptimizeSequences(Function &F);
761
762     void OptimizeReturns(Function &F);
763
764 #ifndef NDEBUG
765     void GatherStatistics(Function &F, bool AfterOptimization = false);
766 #endif
767
768     void getAnalysisUsage(AnalysisUsage &AU) const override;
769     bool doInitialization(Module &M) override;
770     bool runOnFunction(Function &F) override;
771     void releaseMemory() override;
772
773   public:
774     static char ID;
775     ObjCARCOpt() : FunctionPass(ID) {
776       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
777     }
778   };
779 }
780
781 char ObjCARCOpt::ID = 0;
782 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
783                       "objc-arc", "ObjC ARC optimization", false, false)
784 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
785 INITIALIZE_PASS_END(ObjCARCOpt,
786                     "objc-arc", "ObjC ARC optimization", false, false)
787
788 Pass *llvm::createObjCARCOptPass() {
789   return new ObjCARCOpt();
790 }
791
792 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
793   AU.addRequired<ObjCARCAliasAnalysis>();
794   AU.addRequired<AliasAnalysis>();
795   // ARC optimization doesn't currently split critical edges.
796   AU.setPreservesCFG();
797 }
798
799 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
800 /// not a return value.  Or, if it can be paired with an
801 /// objc_autoreleaseReturnValue, delete the pair and return true.
802 bool
803 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
804   // Check for the argument being from an immediately preceding call or invoke.
805   const Value *Arg = GetArgRCIdentityRoot(RetainRV);
806   ImmutableCallSite CS(Arg);
807   if (const Instruction *Call = CS.getInstruction()) {
808     if (Call->getParent() == RetainRV->getParent()) {
809       BasicBlock::const_iterator I = Call;
810       ++I;
811       while (IsNoopInstruction(I)) ++I;
812       if (&*I == RetainRV)
813         return false;
814     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
815       BasicBlock *RetainRVParent = RetainRV->getParent();
816       if (II->getNormalDest() == RetainRVParent) {
817         BasicBlock::const_iterator I = RetainRVParent->begin();
818         while (IsNoopInstruction(I)) ++I;
819         if (&*I == RetainRV)
820           return false;
821       }
822     }
823   }
824
825   // Check for being preceded by an objc_autoreleaseReturnValue on the same
826   // pointer. In this case, we can delete the pair.
827   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
828   if (I != Begin) {
829     do --I; while (I != Begin && IsNoopInstruction(I));
830     if (GetBasicARCInstKind(I) == ARCInstKind::AutoreleaseRV &&
831         GetArgRCIdentityRoot(I) == Arg) {
832       Changed = true;
833       ++NumPeeps;
834
835       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
836                    << "Erasing " << *RetainRV << "\n");
837
838       EraseInstruction(I);
839       EraseInstruction(RetainRV);
840       return true;
841     }
842   }
843
844   // Turn it to a plain objc_retain.
845   Changed = true;
846   ++NumPeeps;
847
848   DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
849                   "objc_retain since the operand is not a return value.\n"
850                   "Old = " << *RetainRV << "\n");
851
852   Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
853   cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
854
855   DEBUG(dbgs() << "New = " << *RetainRV << "\n");
856
857   return false;
858 }
859
860 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
861 /// used as a return value.
862 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F,
863                                            Instruction *AutoreleaseRV,
864                                            ARCInstKind &Class) {
865   // Check for a return of the pointer value.
866   const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV);
867   SmallVector<const Value *, 2> Users;
868   Users.push_back(Ptr);
869   do {
870     Ptr = Users.pop_back_val();
871     for (const User *U : Ptr->users()) {
872       if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV)
873         return;
874       if (isa<BitCastInst>(U))
875         Users.push_back(U);
876     }
877   } while (!Users.empty());
878
879   Changed = true;
880   ++NumPeeps;
881
882   DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
883                   "objc_autorelease since its operand is not used as a return "
884                   "value.\n"
885                   "Old = " << *AutoreleaseRV << "\n");
886
887   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
888   Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
889   AutoreleaseRVCI->setCalledFunction(NewDecl);
890   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
891   Class = ARCInstKind::Autorelease;
892
893   DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
894
895 }
896
897 /// Visit each call, one at a time, and make simplifications without doing any
898 /// additional analysis.
899 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
900   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
901   // Reset all the flags in preparation for recomputing them.
902   UsedInThisFunction = 0;
903
904   // Visit all objc_* calls in F.
905   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
906     Instruction *Inst = &*I++;
907
908     ARCInstKind Class = GetBasicARCInstKind(Inst);
909
910     DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
911
912     switch (Class) {
913     default: break;
914
915     // Delete no-op casts. These function calls have special semantics, but
916     // the semantics are entirely implemented via lowering in the front-end,
917     // so by the time they reach the optimizer, they are just no-op calls
918     // which return their argument.
919     //
920     // There are gray areas here, as the ability to cast reference-counted
921     // pointers to raw void* and back allows code to break ARC assumptions,
922     // however these are currently considered to be unimportant.
923     case ARCInstKind::NoopCast:
924       Changed = true;
925       ++NumNoops;
926       DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
927       EraseInstruction(Inst);
928       continue;
929
930     // If the pointer-to-weak-pointer is null, it's undefined behavior.
931     case ARCInstKind::StoreWeak:
932     case ARCInstKind::LoadWeak:
933     case ARCInstKind::LoadWeakRetained:
934     case ARCInstKind::InitWeak:
935     case ARCInstKind::DestroyWeak: {
936       CallInst *CI = cast<CallInst>(Inst);
937       if (IsNullOrUndef(CI->getArgOperand(0))) {
938         Changed = true;
939         Type *Ty = CI->getArgOperand(0)->getType();
940         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
941                       Constant::getNullValue(Ty),
942                       CI);
943         llvm::Value *NewValue = UndefValue::get(CI->getType());
944         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
945                        "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
946         CI->replaceAllUsesWith(NewValue);
947         CI->eraseFromParent();
948         continue;
949       }
950       break;
951     }
952     case ARCInstKind::CopyWeak:
953     case ARCInstKind::MoveWeak: {
954       CallInst *CI = cast<CallInst>(Inst);
955       if (IsNullOrUndef(CI->getArgOperand(0)) ||
956           IsNullOrUndef(CI->getArgOperand(1))) {
957         Changed = true;
958         Type *Ty = CI->getArgOperand(0)->getType();
959         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
960                       Constant::getNullValue(Ty),
961                       CI);
962
963         llvm::Value *NewValue = UndefValue::get(CI->getType());
964         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
965                         "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
966
967         CI->replaceAllUsesWith(NewValue);
968         CI->eraseFromParent();
969         continue;
970       }
971       break;
972     }
973     case ARCInstKind::RetainRV:
974       if (OptimizeRetainRVCall(F, Inst))
975         continue;
976       break;
977     case ARCInstKind::AutoreleaseRV:
978       OptimizeAutoreleaseRVCall(F, Inst, Class);
979       break;
980     }
981
982     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
983     if (IsAutorelease(Class) && Inst->use_empty()) {
984       CallInst *Call = cast<CallInst>(Inst);
985       const Value *Arg = Call->getArgOperand(0);
986       Arg = FindSingleUseIdentifiedObject(Arg);
987       if (Arg) {
988         Changed = true;
989         ++NumAutoreleases;
990
991         // Create the declaration lazily.
992         LLVMContext &C = Inst->getContext();
993
994         Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
995         CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
996                                              Call);
997         NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
998
999         DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1000               "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1001               << *NewCall << "\n");
1002
1003         EraseInstruction(Call);
1004         Inst = NewCall;
1005         Class = ARCInstKind::Release;
1006       }
1007     }
1008
1009     // For functions which can never be passed stack arguments, add
1010     // a tail keyword.
1011     if (IsAlwaysTail(Class)) {
1012       Changed = true;
1013       DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1014                       "passed stack args: " << *Inst << "\n");
1015       cast<CallInst>(Inst)->setTailCall();
1016     }
1017
1018     // Ensure that functions that can never have a "tail" keyword due to the
1019     // semantics of ARC truly do not do so.
1020     if (IsNeverTail(Class)) {
1021       Changed = true;
1022       DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1023             "\n");
1024       cast<CallInst>(Inst)->setTailCall(false);
1025     }
1026
1027     // Set nounwind as needed.
1028     if (IsNoThrow(Class)) {
1029       Changed = true;
1030       DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1031                    << "\n");
1032       cast<CallInst>(Inst)->setDoesNotThrow();
1033     }
1034
1035     if (!IsNoopOnNull(Class)) {
1036       UsedInThisFunction |= 1 << unsigned(Class);
1037       continue;
1038     }
1039
1040     const Value *Arg = GetArgRCIdentityRoot(Inst);
1041
1042     // ARC calls with null are no-ops. Delete them.
1043     if (IsNullOrUndef(Arg)) {
1044       Changed = true;
1045       ++NumNoops;
1046       DEBUG(dbgs() << "ARC calls with  null are no-ops. Erasing: " << *Inst
1047             << "\n");
1048       EraseInstruction(Inst);
1049       continue;
1050     }
1051
1052     // Keep track of which of retain, release, autorelease, and retain_block
1053     // are actually present in this function.
1054     UsedInThisFunction |= 1 << unsigned(Class);
1055
1056     // If Arg is a PHI, and one or more incoming values to the
1057     // PHI are null, and the call is control-equivalent to the PHI, and there
1058     // are no relevant side effects between the PHI and the call, the call
1059     // could be pushed up to just those paths with non-null incoming values.
1060     // For now, don't bother splitting critical edges for this.
1061     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1062     Worklist.push_back(std::make_pair(Inst, Arg));
1063     do {
1064       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1065       Inst = Pair.first;
1066       Arg = Pair.second;
1067
1068       const PHINode *PN = dyn_cast<PHINode>(Arg);
1069       if (!PN) continue;
1070
1071       // Determine if the PHI has any null operands, or any incoming
1072       // critical edges.
1073       bool HasNull = false;
1074       bool HasCriticalEdges = false;
1075       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1076         Value *Incoming =
1077           GetRCIdentityRoot(PN->getIncomingValue(i));
1078         if (IsNullOrUndef(Incoming))
1079           HasNull = true;
1080         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1081                    .getNumSuccessors() != 1) {
1082           HasCriticalEdges = true;
1083           break;
1084         }
1085       }
1086       // If we have null operands and no critical edges, optimize.
1087       if (!HasCriticalEdges && HasNull) {
1088         SmallPtrSet<Instruction *, 4> DependingInstructions;
1089         SmallPtrSet<const BasicBlock *, 4> Visited;
1090
1091         // Check that there is nothing that cares about the reference
1092         // count between the call and the phi.
1093         switch (Class) {
1094         case ARCInstKind::Retain:
1095         case ARCInstKind::RetainBlock:
1096           // These can always be moved up.
1097           break;
1098         case ARCInstKind::Release:
1099           // These can't be moved across things that care about the retain
1100           // count.
1101           FindDependencies(NeedsPositiveRetainCount, Arg,
1102                            Inst->getParent(), Inst,
1103                            DependingInstructions, Visited, PA);
1104           break;
1105         case ARCInstKind::Autorelease:
1106           // These can't be moved across autorelease pool scope boundaries.
1107           FindDependencies(AutoreleasePoolBoundary, Arg,
1108                            Inst->getParent(), Inst,
1109                            DependingInstructions, Visited, PA);
1110           break;
1111         case ARCInstKind::RetainRV:
1112         case ARCInstKind::AutoreleaseRV:
1113           // Don't move these; the RV optimization depends on the autoreleaseRV
1114           // being tail called, and the retainRV being immediately after a call
1115           // (which might still happen if we get lucky with codegen layout, but
1116           // it's not worth taking the chance).
1117           continue;
1118         default:
1119           llvm_unreachable("Invalid dependence flavor");
1120         }
1121
1122         if (DependingInstructions.size() == 1 &&
1123             *DependingInstructions.begin() == PN) {
1124           Changed = true;
1125           ++NumPartialNoops;
1126           // Clone the call into each predecessor that has a non-null value.
1127           CallInst *CInst = cast<CallInst>(Inst);
1128           Type *ParamTy = CInst->getArgOperand(0)->getType();
1129           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1130             Value *Incoming =
1131               GetRCIdentityRoot(PN->getIncomingValue(i));
1132             if (!IsNullOrUndef(Incoming)) {
1133               CallInst *Clone = cast<CallInst>(CInst->clone());
1134               Value *Op = PN->getIncomingValue(i);
1135               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1136               if (Op->getType() != ParamTy)
1137                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1138               Clone->setArgOperand(0, Op);
1139               Clone->insertBefore(InsertPos);
1140
1141               DEBUG(dbgs() << "Cloning "
1142                            << *CInst << "\n"
1143                            "And inserting clone at " << *InsertPos << "\n");
1144               Worklist.push_back(std::make_pair(Clone, Incoming));
1145             }
1146           }
1147           // Erase the original call.
1148           DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1149           EraseInstruction(CInst);
1150           continue;
1151         }
1152       }
1153     } while (!Worklist.empty());
1154   }
1155 }
1156
1157 /// If we have a top down pointer in the S_Use state, make sure that there are
1158 /// no CFG hazards by checking the states of various bottom up pointers.
1159 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1160                                  const bool SuccSRRIKnownSafe,
1161                                  PtrState &S,
1162                                  bool &SomeSuccHasSame,
1163                                  bool &AllSuccsHaveSame,
1164                                  bool &NotAllSeqEqualButKnownSafe,
1165                                  bool &ShouldContinue) {
1166   switch (SuccSSeq) {
1167   case S_CanRelease: {
1168     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
1169       S.ClearSequenceProgress();
1170       break;
1171     }
1172     S.SetCFGHazardAfflicted(true);
1173     ShouldContinue = true;
1174     break;
1175   }
1176   case S_Use:
1177     SomeSuccHasSame = true;
1178     break;
1179   case S_Stop:
1180   case S_Release:
1181   case S_MovableRelease:
1182     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1183       AllSuccsHaveSame = false;
1184     else
1185       NotAllSeqEqualButKnownSafe = true;
1186     break;
1187   case S_Retain:
1188     llvm_unreachable("bottom-up pointer in retain state!");
1189   case S_None:
1190     llvm_unreachable("This should have been handled earlier.");
1191   }
1192 }
1193
1194 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1195 /// there are no CFG hazards by checking the states of various bottom up
1196 /// pointers.
1197 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1198                                         const bool SuccSRRIKnownSafe,
1199                                         PtrState &S,
1200                                         bool &SomeSuccHasSame,
1201                                         bool &AllSuccsHaveSame,
1202                                         bool &NotAllSeqEqualButKnownSafe) {
1203   switch (SuccSSeq) {
1204   case S_CanRelease:
1205     SomeSuccHasSame = true;
1206     break;
1207   case S_Stop:
1208   case S_Release:
1209   case S_MovableRelease:
1210   case S_Use:
1211     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1212       AllSuccsHaveSame = false;
1213     else
1214       NotAllSeqEqualButKnownSafe = true;
1215     break;
1216   case S_Retain:
1217     llvm_unreachable("bottom-up pointer in retain state!");
1218   case S_None:
1219     llvm_unreachable("This should have been handled earlier.");
1220   }
1221 }
1222
1223 /// Check for critical edges, loop boundaries, irreducible control flow, or
1224 /// other CFG structures where moving code across the edge would result in it
1225 /// being executed more.
1226 void
1227 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1228                                DenseMap<const BasicBlock *, BBState> &BBStates,
1229                                BBState &MyStates) const {
1230   // If any top-down local-use or possible-dec has a succ which is earlier in
1231   // the sequence, forget it.
1232   for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1233          E = MyStates.top_down_ptr_end(); I != E; ++I) {
1234     PtrState &S = I->second;
1235     const Sequence Seq = I->second.GetSeq();
1236
1237     // We only care about S_Retain, S_CanRelease, and S_Use.
1238     if (Seq == S_None)
1239       continue;
1240
1241     // Make sure that if extra top down states are added in the future that this
1242     // code is updated to handle it.
1243     assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1244            "Unknown top down sequence state.");
1245
1246     const Value *Arg = I->first;
1247     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1248     bool SomeSuccHasSame = false;
1249     bool AllSuccsHaveSame = true;
1250     bool NotAllSeqEqualButKnownSafe = false;
1251
1252     succ_const_iterator SI(TI), SE(TI, false);
1253
1254     for (; SI != SE; ++SI) {
1255       // If VisitBottomUp has pointer information for this successor, take
1256       // what we know about it.
1257       const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1258         BBStates.find(*SI);
1259       assert(BBI != BBStates.end());
1260       const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1261       const Sequence SuccSSeq = SuccS.GetSeq();
1262
1263       // If bottom up, the pointer is in an S_None state, clear the sequence
1264       // progress since the sequence in the bottom up state finished
1265       // suggesting a mismatch in between retains/releases. This is true for
1266       // all three cases that we are handling here: S_Retain, S_Use, and
1267       // S_CanRelease.
1268       if (SuccSSeq == S_None) {
1269         S.ClearSequenceProgress();
1270         continue;
1271       }
1272
1273       // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1274       // checks.
1275       const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1276
1277       // *NOTE* We do not use Seq from above here since we are allowing for
1278       // S.GetSeq() to change while we are visiting basic blocks.
1279       switch(S.GetSeq()) {
1280       case S_Use: {
1281         bool ShouldContinue = false;
1282         CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1283                              AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1284                              ShouldContinue);
1285         if (ShouldContinue)
1286           continue;
1287         break;
1288       }
1289       case S_CanRelease: {
1290         CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1291                                     SomeSuccHasSame, AllSuccsHaveSame,
1292                                     NotAllSeqEqualButKnownSafe);
1293         break;
1294       }
1295       case S_Retain:
1296       case S_None:
1297       case S_Stop:
1298       case S_Release:
1299       case S_MovableRelease:
1300         break;
1301       }
1302     }
1303
1304     // If the state at the other end of any of the successor edges
1305     // matches the current state, require all edges to match. This
1306     // guards against loops in the middle of a sequence.
1307     if (SomeSuccHasSame && !AllSuccsHaveSame) {
1308       S.ClearSequenceProgress();
1309     } else if (NotAllSeqEqualButKnownSafe) {
1310       // If we would have cleared the state foregoing the fact that we are known
1311       // safe, stop code motion. This is because whether or not it is safe to
1312       // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1313       // are allowed to perform code motion.
1314       S.SetCFGHazardAfflicted(true);
1315     }
1316   }
1317 }
1318
1319 bool ObjCARCOpt::VisitInstructionBottomUp(
1320     Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains,
1321     BBState &MyStates) {
1322   bool NestingDetected = false;
1323   ARCInstKind Class = GetARCInstKind(Inst);
1324   const Value *Arg = nullptr;
1325
1326   DEBUG(dbgs() << "Class: " << Class << "\n");
1327
1328   switch (Class) {
1329   case ARCInstKind::Release: {
1330     Arg = GetArgRCIdentityRoot(Inst);
1331
1332     PtrState &S = MyStates.getPtrBottomUpState(Arg);
1333
1334     // If we see two releases in a row on the same pointer. If so, make
1335     // a note, and we'll cicle back to revisit it after we've
1336     // hopefully eliminated the second release, which may allow us to
1337     // eliminate the first release too.
1338     // Theoretically we could implement removal of nested retain+release
1339     // pairs by making PtrState hold a stack of states, but this is
1340     // simple and avoids adding overhead for the non-nested case.
1341     if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1342       DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1343       NestingDetected = true;
1344     }
1345
1346     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1347     Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1348     ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1349     S.ResetSequenceProgress(NewSeq);
1350     S.SetReleaseMetadata(ReleaseMetadata);
1351     S.SetKnownSafe(S.HasKnownPositiveRefCount());
1352     S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1353     S.InsertCall(Inst);
1354     S.SetKnownPositiveRefCount();
1355     break;
1356   }
1357   case ARCInstKind::RetainBlock:
1358     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1359     // objc_retainBlocks to objc_retains. Thus at this point any
1360     // objc_retainBlocks that we see are not optimizable.
1361     break;
1362   case ARCInstKind::Retain:
1363   case ARCInstKind::RetainRV: {
1364     Arg = GetArgRCIdentityRoot(Inst);
1365
1366     PtrState &S = MyStates.getPtrBottomUpState(Arg);
1367     S.SetKnownPositiveRefCount();
1368
1369     Sequence OldSeq = S.GetSeq();
1370     switch (OldSeq) {
1371     case S_Stop:
1372     case S_Release:
1373     case S_MovableRelease:
1374     case S_Use:
1375       // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1376       // imprecise release, clear our reverse insertion points.
1377       if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
1378         S.ClearReverseInsertPts();
1379       // FALL THROUGH
1380     case S_CanRelease:
1381       // Don't do retain+release tracking for ARCInstKind::RetainRV,
1382       // because it's
1383       // better to let it remain as the first instruction after a call.
1384       if (Class != ARCInstKind::RetainRV)
1385         Retains[Inst] = S.GetRRInfo();
1386       S.ClearSequenceProgress();
1387       break;
1388     case S_None:
1389       break;
1390     case S_Retain:
1391       llvm_unreachable("bottom-up pointer in retain state!");
1392     }
1393     ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1394     // A retain moving bottom up can be a use.
1395     break;
1396   }
1397   case ARCInstKind::AutoreleasepoolPop:
1398     // Conservatively, clear MyStates for all known pointers.
1399     MyStates.clearBottomUpPointers();
1400     return NestingDetected;
1401   case ARCInstKind::AutoreleasepoolPush:
1402   case ARCInstKind::None:
1403     // These are irrelevant.
1404     return NestingDetected;
1405   case ARCInstKind::User:
1406     // If we have a store into an alloca of a pointer we are tracking, the
1407     // pointer has multiple owners implying that we must be more conservative.
1408     //
1409     // This comes up in the context of a pointer being ``KnownSafe''. In the
1410     // presence of a block being initialized, the frontend will emit the
1411     // objc_retain on the original pointer and the release on the pointer loaded
1412     // from the alloca. The optimizer will through the provenance analysis
1413     // realize that the two are related, but since we only require KnownSafe in
1414     // one direction, will match the inner retain on the original pointer with
1415     // the guard release on the original pointer. This is fixed by ensuring that
1416     // in the presence of allocas we only unconditionally remove pointers if
1417     // both our retain and our release are KnownSafe.
1418     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1419       if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1420         BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1421           GetRCIdentityRoot(SI->getValueOperand()));
1422         if (I != MyStates.bottom_up_ptr_end())
1423           MultiOwnersSet.insert(I->first);
1424       }
1425     }
1426     break;
1427   default:
1428     break;
1429   }
1430
1431   // Consider any other possible effects of this instruction on each
1432   // pointer being tracked.
1433   for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1434        ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1435     const Value *Ptr = MI->first;
1436     if (Ptr == Arg)
1437       continue; // Handled above.
1438     PtrState &S = MI->second;
1439     Sequence Seq = S.GetSeq();
1440
1441     // Check for possible releases.
1442     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1443       DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1444             << "\n");
1445       S.ClearKnownPositiveRefCount();
1446       switch (Seq) {
1447       case S_Use:
1448         S.SetSeq(S_CanRelease);
1449         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1450         continue;
1451       case S_CanRelease:
1452       case S_Release:
1453       case S_MovableRelease:
1454       case S_Stop:
1455       case S_None:
1456         break;
1457       case S_Retain:
1458         llvm_unreachable("bottom-up pointer in retain state!");
1459       }
1460     }
1461
1462     // Check for possible direct uses.
1463     switch (Seq) {
1464     case S_Release:
1465     case S_MovableRelease:
1466       if (CanUse(Inst, Ptr, PA, Class)) {
1467         DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1468               << "\n");
1469         assert(!S.HasReverseInsertPts());
1470         // If this is an invoke instruction, we're scanning it as part of
1471         // one of its successor blocks, since we can't insert code after it
1472         // in its own block, and we don't want to split critical edges.
1473         if (isa<InvokeInst>(Inst))
1474           S.InsertReverseInsertPt(BB->getFirstInsertionPt());
1475         else
1476           S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
1477         S.SetSeq(S_Use);
1478         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1479       } else if (Seq == S_Release && IsUser(Class)) {
1480         DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1481               << "\n");
1482         // Non-movable releases depend on any possible objc pointer use.
1483         S.SetSeq(S_Stop);
1484         ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
1485         assert(!S.HasReverseInsertPts());
1486         // As above; handle invoke specially.
1487         if (isa<InvokeInst>(Inst))
1488           S.InsertReverseInsertPt(BB->getFirstInsertionPt());
1489         else
1490           S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
1491       }
1492       break;
1493     case S_Stop:
1494       if (CanUse(Inst, Ptr, PA, Class)) {
1495         DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1496               << "\n");
1497         S.SetSeq(S_Use);
1498         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1499       }
1500       break;
1501     case S_CanRelease:
1502     case S_Use:
1503     case S_None:
1504       break;
1505     case S_Retain:
1506       llvm_unreachable("bottom-up pointer in retain state!");
1507     }
1508   }
1509
1510   return NestingDetected;
1511 }
1512
1513 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1514                                DenseMap<const BasicBlock *, BBState> &BBStates,
1515                                BlotMapVector<Value *, RRInfo> &Retains) {
1516
1517   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1518
1519   bool NestingDetected = false;
1520   BBState &MyStates = BBStates[BB];
1521
1522   // Merge the states from each successor to compute the initial state
1523   // for the current block.
1524   BBState::edge_iterator SI(MyStates.succ_begin()),
1525                          SE(MyStates.succ_end());
1526   if (SI != SE) {
1527     const BasicBlock *Succ = *SI;
1528     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1529     assert(I != BBStates.end());
1530     MyStates.InitFromSucc(I->second);
1531     ++SI;
1532     for (; SI != SE; ++SI) {
1533       Succ = *SI;
1534       I = BBStates.find(Succ);
1535       assert(I != BBStates.end());
1536       MyStates.MergeSucc(I->second);
1537     }
1538   }
1539
1540   // If ARC Annotations are enabled, output the current state of pointers at the
1541   // bottom of the basic block.
1542   ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
1543
1544   // Visit all the instructions, bottom-up.
1545   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1546     Instruction *Inst = std::prev(I);
1547
1548     // Invoke instructions are visited as part of their successors (below).
1549     if (isa<InvokeInst>(Inst))
1550       continue;
1551
1552     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1553
1554     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1555   }
1556
1557   // If there's a predecessor with an invoke, visit the invoke as if it were
1558   // part of this block, since we can't insert code after an invoke in its own
1559   // block, and we don't want to split critical edges.
1560   for (BBState::edge_iterator PI(MyStates.pred_begin()),
1561        PE(MyStates.pred_end()); PI != PE; ++PI) {
1562     BasicBlock *Pred = *PI;
1563     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1564       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1565   }
1566
1567   // If ARC Annotations are enabled, output the current state of pointers at the
1568   // top of the basic block.
1569   ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
1570
1571   return NestingDetected;
1572 }
1573
1574 bool
1575 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1576                                     DenseMap<Value *, RRInfo> &Releases,
1577                                     BBState &MyStates) {
1578   bool NestingDetected = false;
1579   ARCInstKind Class = GetARCInstKind(Inst);
1580   const Value *Arg = nullptr;
1581
1582   switch (Class) {
1583   case ARCInstKind::RetainBlock:
1584     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1585     // objc_retainBlocks to objc_retains. Thus at this point any
1586     // objc_retainBlocks that we see are not optimizable.
1587     break;
1588   case ARCInstKind::Retain:
1589   case ARCInstKind::RetainRV: {
1590     Arg = GetArgRCIdentityRoot(Inst);
1591
1592     PtrState &S = MyStates.getPtrTopDownState(Arg);
1593
1594     // Don't do retain+release tracking for ARCInstKind::RetainRV, because
1595     // it's
1596     // better to let it remain as the first instruction after a call.
1597     if (Class != ARCInstKind::RetainRV) {
1598       // If we see two retains in a row on the same pointer. If so, make
1599       // a note, and we'll cicle back to revisit it after we've
1600       // hopefully eliminated the second retain, which may allow us to
1601       // eliminate the first retain too.
1602       // Theoretically we could implement removal of nested retain+release
1603       // pairs by making PtrState hold a stack of states, but this is
1604       // simple and avoids adding overhead for the non-nested case.
1605       if (S.GetSeq() == S_Retain)
1606         NestingDetected = true;
1607
1608       ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
1609       S.ResetSequenceProgress(S_Retain);
1610       S.SetKnownSafe(S.HasKnownPositiveRefCount());
1611       S.InsertCall(Inst);
1612     }
1613
1614     S.SetKnownPositiveRefCount();
1615
1616     // A retain can be a potential use; procede to the generic checking
1617     // code below.
1618     break;
1619   }
1620   case ARCInstKind::Release: {
1621     Arg = GetArgRCIdentityRoot(Inst);
1622
1623     PtrState &S = MyStates.getPtrTopDownState(Arg);
1624     S.ClearKnownPositiveRefCount();
1625
1626     Sequence OldSeq = S.GetSeq();
1627
1628     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1629
1630     switch (OldSeq) {
1631     case S_Retain:
1632     case S_CanRelease:
1633       if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
1634         S.ClearReverseInsertPts();
1635       // FALL THROUGH
1636     case S_Use:
1637       S.SetReleaseMetadata(ReleaseMetadata);
1638       S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1639       Releases[Inst] = S.GetRRInfo();
1640       ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
1641       S.ClearSequenceProgress();
1642       break;
1643     case S_None:
1644       break;
1645     case S_Stop:
1646     case S_Release:
1647     case S_MovableRelease:
1648       llvm_unreachable("top-down pointer in release state!");
1649     }
1650     break;
1651   }
1652   case ARCInstKind::AutoreleasepoolPop:
1653     // Conservatively, clear MyStates for all known pointers.
1654     MyStates.clearTopDownPointers();
1655     return NestingDetected;
1656   case ARCInstKind::AutoreleasepoolPush:
1657   case ARCInstKind::None:
1658     // These are irrelevant.
1659     return NestingDetected;
1660   default:
1661     break;
1662   }
1663
1664   // Consider any other possible effects of this instruction on each
1665   // pointer being tracked.
1666   for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
1667        ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
1668     const Value *Ptr = MI->first;
1669     if (Ptr == Arg)
1670       continue; // Handled above.
1671     PtrState &S = MI->second;
1672     Sequence Seq = S.GetSeq();
1673
1674     // Check for possible releases.
1675     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1676       DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1677             << "\n");
1678       S.ClearKnownPositiveRefCount();
1679       switch (Seq) {
1680       case S_Retain:
1681         S.SetSeq(S_CanRelease);
1682         ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
1683         assert(!S.HasReverseInsertPts());
1684         S.InsertReverseInsertPt(Inst);
1685
1686         // One call can't cause a transition from S_Retain to S_CanRelease
1687         // and S_CanRelease to S_Use. If we've made the first transition,
1688         // we're done.
1689         continue;
1690       case S_Use:
1691       case S_CanRelease:
1692       case S_None:
1693         break;
1694       case S_Stop:
1695       case S_Release:
1696       case S_MovableRelease:
1697         llvm_unreachable("top-down pointer in release state!");
1698       }
1699     }
1700
1701     // Check for possible direct uses.
1702     switch (Seq) {
1703     case S_CanRelease:
1704       if (CanUse(Inst, Ptr, PA, Class)) {
1705         DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1706               << "\n");
1707         S.SetSeq(S_Use);
1708         ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
1709       }
1710       break;
1711     case S_Retain:
1712     case S_Use:
1713     case S_None:
1714       break;
1715     case S_Stop:
1716     case S_Release:
1717     case S_MovableRelease:
1718       llvm_unreachable("top-down pointer in release state!");
1719     }
1720   }
1721
1722   return NestingDetected;
1723 }
1724
1725 bool
1726 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
1727                          DenseMap<const BasicBlock *, BBState> &BBStates,
1728                          DenseMap<Value *, RRInfo> &Releases) {
1729   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
1730   bool NestingDetected = false;
1731   BBState &MyStates = BBStates[BB];
1732
1733   // Merge the states from each predecessor to compute the initial state
1734   // for the current block.
1735   BBState::edge_iterator PI(MyStates.pred_begin()),
1736                          PE(MyStates.pred_end());
1737   if (PI != PE) {
1738     const BasicBlock *Pred = *PI;
1739     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
1740     assert(I != BBStates.end());
1741     MyStates.InitFromPred(I->second);
1742     ++PI;
1743     for (; PI != PE; ++PI) {
1744       Pred = *PI;
1745       I = BBStates.find(Pred);
1746       assert(I != BBStates.end());
1747       MyStates.MergePred(I->second);
1748     }
1749   }
1750
1751   // If ARC Annotations are enabled, output the current state of pointers at the
1752   // top of the basic block.
1753   ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
1754
1755   // Visit all the instructions, top-down.
1756   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1757     Instruction *Inst = I;
1758
1759     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1760
1761     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
1762   }
1763
1764   // If ARC Annotations are enabled, output the current state of pointers at the
1765   // bottom of the basic block.
1766   ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
1767
1768 #ifdef ARC_ANNOTATIONS
1769   if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
1770 #endif
1771   CheckForCFGHazards(BB, BBStates, MyStates);
1772   return NestingDetected;
1773 }
1774
1775 static void
1776 ComputePostOrders(Function &F,
1777                   SmallVectorImpl<BasicBlock *> &PostOrder,
1778                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
1779                   unsigned NoObjCARCExceptionsMDKind,
1780                   DenseMap<const BasicBlock *, BBState> &BBStates) {
1781   /// The visited set, for doing DFS walks.
1782   SmallPtrSet<BasicBlock *, 16> Visited;
1783
1784   // Do DFS, computing the PostOrder.
1785   SmallPtrSet<BasicBlock *, 16> OnStack;
1786   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
1787
1788   // Functions always have exactly one entry block, and we don't have
1789   // any other block that we treat like an entry block.
1790   BasicBlock *EntryBB = &F.getEntryBlock();
1791   BBState &MyStates = BBStates[EntryBB];
1792   MyStates.SetAsEntry();
1793   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
1794   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
1795   Visited.insert(EntryBB);
1796   OnStack.insert(EntryBB);
1797   do {
1798   dfs_next_succ:
1799     BasicBlock *CurrBB = SuccStack.back().first;
1800     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
1801     succ_iterator SE(TI, false);
1802
1803     while (SuccStack.back().second != SE) {
1804       BasicBlock *SuccBB = *SuccStack.back().second++;
1805       if (Visited.insert(SuccBB).second) {
1806         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
1807         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
1808         BBStates[CurrBB].addSucc(SuccBB);
1809         BBState &SuccStates = BBStates[SuccBB];
1810         SuccStates.addPred(CurrBB);
1811         OnStack.insert(SuccBB);
1812         goto dfs_next_succ;
1813       }
1814
1815       if (!OnStack.count(SuccBB)) {
1816         BBStates[CurrBB].addSucc(SuccBB);
1817         BBStates[SuccBB].addPred(CurrBB);
1818       }
1819     }
1820     OnStack.erase(CurrBB);
1821     PostOrder.push_back(CurrBB);
1822     SuccStack.pop_back();
1823   } while (!SuccStack.empty());
1824
1825   Visited.clear();
1826
1827   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
1828   // Functions may have many exits, and there also blocks which we treat
1829   // as exits due to ignored edges.
1830   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
1831   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1832     BasicBlock *ExitBB = I;
1833     BBState &MyStates = BBStates[ExitBB];
1834     if (!MyStates.isExit())
1835       continue;
1836
1837     MyStates.SetAsExit();
1838
1839     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
1840     Visited.insert(ExitBB);
1841     while (!PredStack.empty()) {
1842     reverse_dfs_next_succ:
1843       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
1844       while (PredStack.back().second != PE) {
1845         BasicBlock *BB = *PredStack.back().second++;
1846         if (Visited.insert(BB).second) {
1847           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
1848           goto reverse_dfs_next_succ;
1849         }
1850       }
1851       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
1852     }
1853   }
1854 }
1855
1856 // Visit the function both top-down and bottom-up.
1857 bool ObjCARCOpt::Visit(Function &F,
1858                        DenseMap<const BasicBlock *, BBState> &BBStates,
1859                        BlotMapVector<Value *, RRInfo> &Retains,
1860                        DenseMap<Value *, RRInfo> &Releases) {
1861
1862   // Use reverse-postorder traversals, because we magically know that loops
1863   // will be well behaved, i.e. they won't repeatedly call retain on a single
1864   // pointer without doing a release. We can't use the ReversePostOrderTraversal
1865   // class here because we want the reverse-CFG postorder to consider each
1866   // function exit point, and we want to ignore selected cycle edges.
1867   SmallVector<BasicBlock *, 16> PostOrder;
1868   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
1869   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
1870                     NoObjCARCExceptionsMDKind,
1871                     BBStates);
1872
1873   // Use reverse-postorder on the reverse CFG for bottom-up.
1874   bool BottomUpNestingDetected = false;
1875   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1876        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
1877        I != E; ++I)
1878     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
1879
1880   // Use reverse-postorder for top-down.
1881   bool TopDownNestingDetected = false;
1882   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
1883        PostOrder.rbegin(), E = PostOrder.rend();
1884        I != E; ++I)
1885     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
1886
1887   return TopDownNestingDetected && BottomUpNestingDetected;
1888 }
1889
1890 /// Move the calls in RetainsToMove and ReleasesToMove.
1891 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove,
1892                            RRInfo &ReleasesToMove,
1893                            BlotMapVector<Value *, RRInfo> &Retains,
1894                            DenseMap<Value *, RRInfo> &Releases,
1895                            SmallVectorImpl<Instruction *> &DeadInsts,
1896                            Module *M) {
1897   Type *ArgTy = Arg->getType();
1898   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
1899
1900   DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
1901
1902   // Insert the new retain and release calls.
1903   for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
1904     Value *MyArg = ArgTy == ParamTy ? Arg :
1905                    new BitCastInst(Arg, ParamTy, "", InsertPt);
1906     Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1907     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1908     Call->setDoesNotThrow();
1909     Call->setTailCall();
1910
1911     DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
1912                     "At insertion point: " << *InsertPt << "\n");
1913   }
1914   for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
1915     Value *MyArg = ArgTy == ParamTy ? Arg :
1916                    new BitCastInst(Arg, ParamTy, "", InsertPt);
1917     Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1918     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
1919     // Attach a clang.imprecise_release metadata tag, if appropriate.
1920     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
1921       Call->setMetadata(ImpreciseReleaseMDKind, M);
1922     Call->setDoesNotThrow();
1923     if (ReleasesToMove.IsTailCallRelease)
1924       Call->setTailCall();
1925
1926     DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
1927                     "At insertion point: " << *InsertPt << "\n");
1928   }
1929
1930   // Delete the original retain and release calls.
1931   for (Instruction *OrigRetain : RetainsToMove.Calls) {
1932     Retains.blot(OrigRetain);
1933     DeadInsts.push_back(OrigRetain);
1934     DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
1935   }
1936   for (Instruction *OrigRelease : ReleasesToMove.Calls) {
1937     Releases.erase(OrigRelease);
1938     DeadInsts.push_back(OrigRelease);
1939     DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
1940   }
1941
1942 }
1943
1944 bool ObjCARCOpt::ConnectTDBUTraversals(
1945     DenseMap<const BasicBlock *, BBState> &BBStates,
1946     BlotMapVector<Value *, RRInfo> &Retains,
1947     DenseMap<Value *, RRInfo> &Releases, Module *M,
1948     SmallVectorImpl<Instruction *> &NewRetains,
1949     SmallVectorImpl<Instruction *> &NewReleases,
1950     SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove,
1951     RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe,
1952     bool &AnyPairsCompletelyEliminated) {
1953   // If a pair happens in a region where it is known that the reference count
1954   // is already incremented, we can similarly ignore possible decrements unless
1955   // we are dealing with a retainable object with multiple provenance sources.
1956   bool KnownSafeTD = true, KnownSafeBU = true;
1957   bool MultipleOwners = false;
1958   bool CFGHazardAfflicted = false;
1959
1960   // Connect the dots between the top-down-collected RetainsToMove and
1961   // bottom-up-collected ReleasesToMove to form sets of related calls.
1962   // This is an iterative process so that we connect multiple releases
1963   // to multiple retains if needed.
1964   unsigned OldDelta = 0;
1965   unsigned NewDelta = 0;
1966   unsigned OldCount = 0;
1967   unsigned NewCount = 0;
1968   bool FirstRelease = true;
1969   for (;;) {
1970     for (SmallVectorImpl<Instruction *>::const_iterator
1971            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
1972       Instruction *NewRetain = *NI;
1973       BlotMapVector<Value *, RRInfo>::const_iterator It =
1974           Retains.find(NewRetain);
1975       assert(It != Retains.end());
1976       const RRInfo &NewRetainRRI = It->second;
1977       KnownSafeTD &= NewRetainRRI.KnownSafe;
1978       MultipleOwners =
1979         MultipleOwners || MultiOwnersSet.count(GetArgRCIdentityRoot(NewRetain));
1980       for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1981         DenseMap<Value *, RRInfo>::const_iterator Jt =
1982           Releases.find(NewRetainRelease);
1983         if (Jt == Releases.end())
1984           return false;
1985         const RRInfo &NewRetainReleaseRRI = Jt->second;
1986
1987         // If the release does not have a reference to the retain as well,
1988         // something happened which is unaccounted for. Do not do anything.
1989         //
1990         // This can happen if we catch an additive overflow during path count
1991         // merging.
1992         if (!NewRetainReleaseRRI.Calls.count(NewRetain))
1993           return false;
1994
1995         if (ReleasesToMove.Calls.insert(NewRetainRelease).second) {
1996
1997           // If we overflow when we compute the path count, don't remove/move
1998           // anything.
1999           const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2000           unsigned PathCount = BBState::OverflowOccurredValue;
2001           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2002             return false;
2003           assert(PathCount != BBState::OverflowOccurredValue &&
2004                  "PathCount at this point can not be "
2005                  "OverflowOccurredValue.");
2006           OldDelta -= PathCount;
2007
2008           // Merge the ReleaseMetadata and IsTailCallRelease values.
2009           if (FirstRelease) {
2010             ReleasesToMove.ReleaseMetadata =
2011               NewRetainReleaseRRI.ReleaseMetadata;
2012             ReleasesToMove.IsTailCallRelease =
2013               NewRetainReleaseRRI.IsTailCallRelease;
2014             FirstRelease = false;
2015           } else {
2016             if (ReleasesToMove.ReleaseMetadata !=
2017                 NewRetainReleaseRRI.ReleaseMetadata)
2018               ReleasesToMove.ReleaseMetadata = nullptr;
2019             if (ReleasesToMove.IsTailCallRelease !=
2020                 NewRetainReleaseRRI.IsTailCallRelease)
2021               ReleasesToMove.IsTailCallRelease = false;
2022           }
2023
2024           // Collect the optimal insertion points.
2025           if (!KnownSafe)
2026             for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
2027               if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) {
2028                 // If we overflow when we compute the path count, don't
2029                 // remove/move anything.
2030                 const BBState &RIPBBState = BBStates[RIP->getParent()];
2031                 PathCount = BBState::OverflowOccurredValue;
2032                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2033                   return false;
2034                 assert(PathCount != BBState::OverflowOccurredValue &&
2035                        "PathCount at this point can not be "
2036                        "OverflowOccurredValue.");
2037                 NewDelta -= PathCount;
2038               }
2039             }
2040           NewReleases.push_back(NewRetainRelease);
2041         }
2042       }
2043     }
2044     NewRetains.clear();
2045     if (NewReleases.empty()) break;
2046
2047     // Back the other way.
2048     for (SmallVectorImpl<Instruction *>::const_iterator
2049            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2050       Instruction *NewRelease = *NI;
2051       DenseMap<Value *, RRInfo>::const_iterator It =
2052         Releases.find(NewRelease);
2053       assert(It != Releases.end());
2054       const RRInfo &NewReleaseRRI = It->second;
2055       KnownSafeBU &= NewReleaseRRI.KnownSafe;
2056       CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2057       for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
2058         BlotMapVector<Value *, RRInfo>::const_iterator Jt =
2059             Retains.find(NewReleaseRetain);
2060         if (Jt == Retains.end())
2061           return false;
2062         const RRInfo &NewReleaseRetainRRI = Jt->second;
2063
2064         // If the retain does not have a reference to the release as well,
2065         // something happened which is unaccounted for. Do not do anything.
2066         //
2067         // This can happen if we catch an additive overflow during path count
2068         // merging.
2069         if (!NewReleaseRetainRRI.Calls.count(NewRelease))
2070           return false;
2071
2072         if (RetainsToMove.Calls.insert(NewReleaseRetain).second) {
2073           // If we overflow when we compute the path count, don't remove/move
2074           // anything.
2075           const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2076           unsigned PathCount = BBState::OverflowOccurredValue;
2077           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2078             return false;
2079           assert(PathCount != BBState::OverflowOccurredValue &&
2080                  "PathCount at this point can not be "
2081                  "OverflowOccurredValue.");
2082           OldDelta += PathCount;
2083           OldCount += PathCount;
2084
2085           // Collect the optimal insertion points.
2086           if (!KnownSafe)
2087             for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
2088               if (RetainsToMove.ReverseInsertPts.insert(RIP).second) {
2089                 // If we overflow when we compute the path count, don't
2090                 // remove/move anything.
2091                 const BBState &RIPBBState = BBStates[RIP->getParent()];
2092
2093                 PathCount = BBState::OverflowOccurredValue;
2094                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2095                   return false;
2096                 assert(PathCount != BBState::OverflowOccurredValue &&
2097                        "PathCount at this point can not be "
2098                        "OverflowOccurredValue.");
2099                 NewDelta += PathCount;
2100                 NewCount += PathCount;
2101               }
2102             }
2103           NewRetains.push_back(NewReleaseRetain);
2104         }
2105       }
2106     }
2107     NewReleases.clear();
2108     if (NewRetains.empty()) break;
2109   }
2110
2111   // If the pointer is known incremented in 1 direction and we do not have
2112   // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2113   // to be known safe in both directions.
2114   bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2115     ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2116   if (UnconditionallySafe) {
2117     RetainsToMove.ReverseInsertPts.clear();
2118     ReleasesToMove.ReverseInsertPts.clear();
2119     NewCount = 0;
2120   } else {
2121     // Determine whether the new insertion points we computed preserve the
2122     // balance of retain and release calls through the program.
2123     // TODO: If the fully aggressive solution isn't valid, try to find a
2124     // less aggressive solution which is.
2125     if (NewDelta != 0)
2126       return false;
2127
2128     // At this point, we are not going to remove any RR pairs, but we still are
2129     // able to move RR pairs. If one of our pointers is afflicted with
2130     // CFGHazards, we cannot perform such code motion so exit early.
2131     const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2132       ReleasesToMove.ReverseInsertPts.size();
2133     if (CFGHazardAfflicted && WillPerformCodeMotion)
2134       return false;
2135   }
2136
2137   // Determine whether the original call points are balanced in the retain and
2138   // release calls through the program. If not, conservatively don't touch
2139   // them.
2140   // TODO: It's theoretically possible to do code motion in this case, as
2141   // long as the existing imbalances are maintained.
2142   if (OldDelta != 0)
2143     return false;
2144
2145 #ifdef ARC_ANNOTATIONS
2146   // Do not move calls if ARC annotations are requested.
2147   if (EnableARCAnnotations)
2148     return false;
2149 #endif // ARC_ANNOTATIONS
2150
2151   Changed = true;
2152   assert(OldCount != 0 && "Unreachable code?");
2153   NumRRs += OldCount - NewCount;
2154   // Set to true if we completely removed any RR pairs.
2155   AnyPairsCompletelyEliminated = NewCount == 0;
2156
2157   // We can move calls!
2158   return true;
2159 }
2160
2161 /// Identify pairings between the retains and releases, and delete and/or move
2162 /// them.
2163 bool ObjCARCOpt::PerformCodePlacement(
2164     DenseMap<const BasicBlock *, BBState> &BBStates,
2165     BlotMapVector<Value *, RRInfo> &Retains,
2166     DenseMap<Value *, RRInfo> &Releases, Module *M) {
2167   DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2168
2169   bool AnyPairsCompletelyEliminated = false;
2170   RRInfo RetainsToMove;
2171   RRInfo ReleasesToMove;
2172   SmallVector<Instruction *, 4> NewRetains;
2173   SmallVector<Instruction *, 4> NewReleases;
2174   SmallVector<Instruction *, 8> DeadInsts;
2175
2176   // Visit each retain.
2177   for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2178                                                       E = Retains.end();
2179        I != E; ++I) {
2180     Value *V = I->first;
2181     if (!V) continue; // blotted
2182
2183     Instruction *Retain = cast<Instruction>(V);
2184
2185     DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2186
2187     Value *Arg = GetArgRCIdentityRoot(Retain);
2188
2189     // If the object being released is in static or stack storage, we know it's
2190     // not being managed by ObjC reference counting, so we can delete pairs
2191     // regardless of what possible decrements or uses lie between them.
2192     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2193
2194     // A constant pointer can't be pointing to an object on the heap. It may
2195     // be reference-counted, but it won't be deleted.
2196     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2197       if (const GlobalVariable *GV =
2198             dyn_cast<GlobalVariable>(
2199               GetRCIdentityRoot(LI->getPointerOperand())))
2200         if (GV->isConstant())
2201           KnownSafe = true;
2202
2203     // Connect the dots between the top-down-collected RetainsToMove and
2204     // bottom-up-collected ReleasesToMove to form sets of related calls.
2205     NewRetains.push_back(Retain);
2206     bool PerformMoveCalls =
2207       ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2208                             NewReleases, DeadInsts, RetainsToMove,
2209                             ReleasesToMove, Arg, KnownSafe,
2210                             AnyPairsCompletelyEliminated);
2211
2212     if (PerformMoveCalls) {
2213       // Ok, everything checks out and we're all set. Let's move/delete some
2214       // code!
2215       MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2216                 Retains, Releases, DeadInsts, M);
2217     }
2218
2219     // Clean up state for next retain.
2220     NewReleases.clear();
2221     NewRetains.clear();
2222     RetainsToMove.clear();
2223     ReleasesToMove.clear();
2224   }
2225
2226   // Now that we're done moving everything, we can delete the newly dead
2227   // instructions, as we no longer need them as insert points.
2228   while (!DeadInsts.empty())
2229     EraseInstruction(DeadInsts.pop_back_val());
2230
2231   return AnyPairsCompletelyEliminated;
2232 }
2233
2234 /// Weak pointer optimizations.
2235 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2236   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2237
2238   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2239   // itself because it uses AliasAnalysis and we need to do provenance
2240   // queries instead.
2241   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2242     Instruction *Inst = &*I++;
2243
2244     DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2245
2246     ARCInstKind Class = GetBasicARCInstKind(Inst);
2247     if (Class != ARCInstKind::LoadWeak &&
2248         Class != ARCInstKind::LoadWeakRetained)
2249       continue;
2250
2251     // Delete objc_loadWeak calls with no users.
2252     if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) {
2253       Inst->eraseFromParent();
2254       continue;
2255     }
2256
2257     // TODO: For now, just look for an earlier available version of this value
2258     // within the same block. Theoretically, we could do memdep-style non-local
2259     // analysis too, but that would want caching. A better approach would be to
2260     // use the technique that EarlyCSE uses.
2261     inst_iterator Current = std::prev(I);
2262     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2263     for (BasicBlock::iterator B = CurrentBB->begin(),
2264                               J = Current.getInstructionIterator();
2265          J != B; --J) {
2266       Instruction *EarlierInst = &*std::prev(J);
2267       ARCInstKind EarlierClass = GetARCInstKind(EarlierInst);
2268       switch (EarlierClass) {
2269       case ARCInstKind::LoadWeak:
2270       case ARCInstKind::LoadWeakRetained: {
2271         // If this is loading from the same pointer, replace this load's value
2272         // with that one.
2273         CallInst *Call = cast<CallInst>(Inst);
2274         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2275         Value *Arg = Call->getArgOperand(0);
2276         Value *EarlierArg = EarlierCall->getArgOperand(0);
2277         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2278         case AliasAnalysis::MustAlias:
2279           Changed = true;
2280           // If the load has a builtin retain, insert a plain retain for it.
2281           if (Class == ARCInstKind::LoadWeakRetained) {
2282             Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2283             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
2284             CI->setTailCall();
2285           }
2286           // Zap the fully redundant load.
2287           Call->replaceAllUsesWith(EarlierCall);
2288           Call->eraseFromParent();
2289           goto clobbered;
2290         case AliasAnalysis::MayAlias:
2291         case AliasAnalysis::PartialAlias:
2292           goto clobbered;
2293         case AliasAnalysis::NoAlias:
2294           break;
2295         }
2296         break;
2297       }
2298       case ARCInstKind::StoreWeak:
2299       case ARCInstKind::InitWeak: {
2300         // If this is storing to the same pointer and has the same size etc.
2301         // replace this load's value with the stored value.
2302         CallInst *Call = cast<CallInst>(Inst);
2303         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2304         Value *Arg = Call->getArgOperand(0);
2305         Value *EarlierArg = EarlierCall->getArgOperand(0);
2306         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2307         case AliasAnalysis::MustAlias:
2308           Changed = true;
2309           // If the load has a builtin retain, insert a plain retain for it.
2310           if (Class == ARCInstKind::LoadWeakRetained) {
2311             Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2312             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
2313             CI->setTailCall();
2314           }
2315           // Zap the fully redundant load.
2316           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2317           Call->eraseFromParent();
2318           goto clobbered;
2319         case AliasAnalysis::MayAlias:
2320         case AliasAnalysis::PartialAlias:
2321           goto clobbered;
2322         case AliasAnalysis::NoAlias:
2323           break;
2324         }
2325         break;
2326       }
2327       case ARCInstKind::MoveWeak:
2328       case ARCInstKind::CopyWeak:
2329         // TOOD: Grab the copied value.
2330         goto clobbered;
2331       case ARCInstKind::AutoreleasepoolPush:
2332       case ARCInstKind::None:
2333       case ARCInstKind::IntrinsicUser:
2334       case ARCInstKind::User:
2335         // Weak pointers are only modified through the weak entry points
2336         // (and arbitrary calls, which could call the weak entry points).
2337         break;
2338       default:
2339         // Anything else could modify the weak pointer.
2340         goto clobbered;
2341       }
2342     }
2343   clobbered:;
2344   }
2345
2346   // Then, for each destroyWeak with an alloca operand, check to see if
2347   // the alloca and all its users can be zapped.
2348   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2349     Instruction *Inst = &*I++;
2350     ARCInstKind Class = GetBasicARCInstKind(Inst);
2351     if (Class != ARCInstKind::DestroyWeak)
2352       continue;
2353
2354     CallInst *Call = cast<CallInst>(Inst);
2355     Value *Arg = Call->getArgOperand(0);
2356     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2357       for (User *U : Alloca->users()) {
2358         const Instruction *UserInst = cast<Instruction>(U);
2359         switch (GetBasicARCInstKind(UserInst)) {
2360         case ARCInstKind::InitWeak:
2361         case ARCInstKind::StoreWeak:
2362         case ARCInstKind::DestroyWeak:
2363           continue;
2364         default:
2365           goto done;
2366         }
2367       }
2368       Changed = true;
2369       for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
2370         CallInst *UserInst = cast<CallInst>(*UI++);
2371         switch (GetBasicARCInstKind(UserInst)) {
2372         case ARCInstKind::InitWeak:
2373         case ARCInstKind::StoreWeak:
2374           // These functions return their second argument.
2375           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2376           break;
2377         case ARCInstKind::DestroyWeak:
2378           // No return value.
2379           break;
2380         default:
2381           llvm_unreachable("alloca really is used!");
2382         }
2383         UserInst->eraseFromParent();
2384       }
2385       Alloca->eraseFromParent();
2386     done:;
2387     }
2388   }
2389 }
2390
2391 /// Identify program paths which execute sequences of retains and releases which
2392 /// can be eliminated.
2393 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2394   // Releases, Retains - These are used to store the results of the main flow
2395   // analysis. These use Value* as the key instead of Instruction* so that the
2396   // map stays valid when we get around to rewriting code and calls get
2397   // replaced by arguments.
2398   DenseMap<Value *, RRInfo> Releases;
2399   BlotMapVector<Value *, RRInfo> Retains;
2400
2401   // This is used during the traversal of the function to track the
2402   // states for each identified object at each block.
2403   DenseMap<const BasicBlock *, BBState> BBStates;
2404
2405   // Analyze the CFG of the function, and all instructions.
2406   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2407
2408   // Transform.
2409   bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2410                                                            Releases,
2411                                                            F.getParent());
2412
2413   // Cleanup.
2414   MultiOwnersSet.clear();
2415
2416   return AnyPairsCompletelyEliminated && NestingDetected;
2417 }
2418
2419 /// Check if there is a dependent call earlier that does not have anything in
2420 /// between the Retain and the call that can affect the reference count of their
2421 /// shared pointer argument. Note that Retain need not be in BB.
2422 static bool
2423 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2424                              SmallPtrSetImpl<Instruction *> &DepInsts,
2425                              SmallPtrSetImpl<const BasicBlock *> &Visited,
2426                              ProvenanceAnalysis &PA) {
2427   FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2428                    DepInsts, Visited, PA);
2429   if (DepInsts.size() != 1)
2430     return false;
2431
2432   auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2433
2434   // Check that the pointer is the return value of the call.
2435   if (!Call || Arg != Call)
2436     return false;
2437
2438   // Check that the call is a regular call.
2439   ARCInstKind Class = GetBasicARCInstKind(Call);
2440   if (Class != ARCInstKind::CallOrUser && Class != ARCInstKind::Call)
2441     return false;
2442
2443   return true;
2444 }
2445
2446 /// Find a dependent retain that precedes the given autorelease for which there
2447 /// is nothing in between the two instructions that can affect the ref count of
2448 /// Arg.
2449 static CallInst *
2450 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2451                                   Instruction *Autorelease,
2452                                   SmallPtrSetImpl<Instruction *> &DepInsts,
2453                                   SmallPtrSetImpl<const BasicBlock *> &Visited,
2454                                   ProvenanceAnalysis &PA) {
2455   FindDependencies(CanChangeRetainCount, Arg,
2456                    BB, Autorelease, DepInsts, Visited, PA);
2457   if (DepInsts.size() != 1)
2458     return nullptr;
2459
2460   auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2461
2462   // Check that we found a retain with the same argument.
2463   if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) ||
2464       GetArgRCIdentityRoot(Retain) != Arg) {
2465     return nullptr;
2466   }
2467
2468   return Retain;
2469 }
2470
2471 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
2472 /// no instructions dependent on Arg that need a positive ref count in between
2473 /// the autorelease and the ret.
2474 static CallInst *
2475 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2476                                        ReturnInst *Ret,
2477                                        SmallPtrSetImpl<Instruction *> &DepInsts,
2478                                        SmallPtrSetImpl<const BasicBlock *> &V,
2479                                        ProvenanceAnalysis &PA) {
2480   FindDependencies(NeedsPositiveRetainCount, Arg,
2481                    BB, Ret, DepInsts, V, PA);
2482   if (DepInsts.size() != 1)
2483     return nullptr;
2484
2485   auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2486   if (!Autorelease)
2487     return nullptr;
2488   ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease);
2489   if (!IsAutorelease(AutoreleaseClass))
2490     return nullptr;
2491   if (GetArgRCIdentityRoot(Autorelease) != Arg)
2492     return nullptr;
2493
2494   return Autorelease;
2495 }
2496
2497 /// Look for this pattern:
2498 /// \code
2499 ///    %call = call i8* @something(...)
2500 ///    %2 = call i8* @objc_retain(i8* %call)
2501 ///    %3 = call i8* @objc_autorelease(i8* %2)
2502 ///    ret i8* %3
2503 /// \endcode
2504 /// And delete the retain and autorelease.
2505 void ObjCARCOpt::OptimizeReturns(Function &F) {
2506   if (!F.getReturnType()->isPointerTy())
2507     return;
2508
2509   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2510
2511   SmallPtrSet<Instruction *, 4> DependingInstructions;
2512   SmallPtrSet<const BasicBlock *, 4> Visited;
2513   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2514     BasicBlock *BB = FI;
2515     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2516
2517     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2518
2519     if (!Ret)
2520       continue;
2521
2522     const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0));
2523
2524     // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2525     // dependent on Arg such that there are no instructions dependent on Arg
2526     // that need a positive ref count in between the autorelease and Ret.
2527     CallInst *Autorelease =
2528       FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2529                                              DependingInstructions, Visited,
2530                                              PA);
2531     DependingInstructions.clear();
2532     Visited.clear();
2533
2534     if (!Autorelease)
2535       continue;
2536
2537     CallInst *Retain =
2538       FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2539                                         DependingInstructions, Visited, PA);
2540     DependingInstructions.clear();
2541     Visited.clear();
2542
2543     if (!Retain)
2544       continue;
2545
2546     // Check that there is nothing that can affect the reference count
2547     // between the retain and the call.  Note that Retain need not be in BB.
2548     bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2549                                                           DependingInstructions,
2550                                                           Visited, PA);
2551     DependingInstructions.clear();
2552     Visited.clear();
2553
2554     if (!HasSafePathToCall)
2555       continue;
2556
2557     // If so, we can zap the retain and autorelease.
2558     Changed = true;
2559     ++NumRets;
2560     DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2561           << *Autorelease << "\n");
2562     EraseInstruction(Retain);
2563     EraseInstruction(Autorelease);
2564   }
2565 }
2566
2567 #ifndef NDEBUG
2568 void
2569 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2570   llvm::Statistic &NumRetains =
2571     AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2572   llvm::Statistic &NumReleases =
2573     AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2574
2575   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2576     Instruction *Inst = &*I++;
2577     switch (GetBasicARCInstKind(Inst)) {
2578     default:
2579       break;
2580     case ARCInstKind::Retain:
2581       ++NumRetains;
2582       break;
2583     case ARCInstKind::Release:
2584       ++NumReleases;
2585       break;
2586     }
2587   }
2588 }
2589 #endif
2590
2591 bool ObjCARCOpt::doInitialization(Module &M) {
2592   if (!EnableARCOpts)
2593     return false;
2594
2595   // If nothing in the Module uses ARC, don't do anything.
2596   Run = ModuleHasARC(M);
2597   if (!Run)
2598     return false;
2599
2600   // Identify the imprecise release metadata kind.
2601   ImpreciseReleaseMDKind =
2602     M.getContext().getMDKindID("clang.imprecise_release");
2603   CopyOnEscapeMDKind =
2604     M.getContext().getMDKindID("clang.arc.copy_on_escape");
2605   NoObjCARCExceptionsMDKind =
2606     M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
2607 #ifdef ARC_ANNOTATIONS
2608   ARCAnnotationBottomUpMDKind =
2609     M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2610   ARCAnnotationTopDownMDKind =
2611     M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2612   ARCAnnotationProvenanceSourceMDKind =
2613     M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2614 #endif // ARC_ANNOTATIONS
2615
2616   // Intuitively, objc_retain and others are nocapture, however in practice
2617   // they are not, because they return their argument value. And objc_release
2618   // calls finalizers which can have arbitrary side effects.
2619
2620   // Initialize our runtime entry point cache.
2621   EP.Initialize(&M);
2622
2623   return false;
2624 }
2625
2626 bool ObjCARCOpt::runOnFunction(Function &F) {
2627   if (!EnableARCOpts)
2628     return false;
2629
2630   // If nothing in the Module uses ARC, don't do anything.
2631   if (!Run)
2632     return false;
2633
2634   Changed = false;
2635
2636   DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2637         "\n");
2638
2639   PA.setAA(&getAnalysis<AliasAnalysis>());
2640
2641 #ifndef NDEBUG
2642   if (AreStatisticsEnabled()) {
2643     GatherStatistics(F, false);
2644   }
2645 #endif
2646
2647   // This pass performs several distinct transformations. As a compile-time aid
2648   // when compiling code that isn't ObjC, skip these if the relevant ObjC
2649   // library functions aren't declared.
2650
2651   // Preliminary optimizations. This also computes UsedInThisFunction.
2652   OptimizeIndividualCalls(F);
2653
2654   // Optimizations for weak pointers.
2655   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) |
2656                             (1 << unsigned(ARCInstKind::LoadWeakRetained)) |
2657                             (1 << unsigned(ARCInstKind::StoreWeak)) |
2658                             (1 << unsigned(ARCInstKind::InitWeak)) |
2659                             (1 << unsigned(ARCInstKind::CopyWeak)) |
2660                             (1 << unsigned(ARCInstKind::MoveWeak)) |
2661                             (1 << unsigned(ARCInstKind::DestroyWeak))))
2662     OptimizeWeakCalls(F);
2663
2664   // Optimizations for retain+release pairs.
2665   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) |
2666                             (1 << unsigned(ARCInstKind::RetainRV)) |
2667                             (1 << unsigned(ARCInstKind::RetainBlock))))
2668     if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release)))
2669       // Run OptimizeSequences until it either stops making changes or
2670       // no retain+release pair nesting is detected.
2671       while (OptimizeSequences(F)) {}
2672
2673   // Optimizations if objc_autorelease is used.
2674   if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) |
2675                             (1 << unsigned(ARCInstKind::AutoreleaseRV))))
2676     OptimizeReturns(F);
2677
2678   // Gather statistics after optimization.
2679 #ifndef NDEBUG
2680   if (AreStatisticsEnabled()) {
2681     GatherStatistics(F, true);
2682   }
2683 #endif
2684
2685   DEBUG(dbgs() << "\n");
2686
2687   return Changed;
2688 }
2689
2690 void ObjCARCOpt::releaseMemory() {
2691   PA.clear();
2692 }
2693
2694 /// @}
2695 ///