1 //===- ObjCARCContract.cpp - ObjC ARC Optimization ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file defines late ObjC ARC optimizations. ARC stands for Automatic
10 /// Reference Counting and is a system for managing reference counts for objects
11 /// in Objective C.
12 ///
13 /// This specific file mainly deals with ``contracting'' multiple lower level
14 /// operations into singular higher level operations through pattern matching.
15 ///
16 /// WARNING: This file knows about certain library functions. It recognizes them
17 /// by name, and hardwires knowledge of their semantics.
18 ///
19 /// WARNING: This file knows about how certain Objective-C library functions are
20 /// used. Naive LLVM IR transformations which would otherwise be
21 /// behavior-preserving may break these assumptions.
22 ///
23 //===----------------------------------------------------------------------===//
24 
25 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
26 // dominated by single calls.
27 
28 #include "ARCRuntimeEntryPoints.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARC.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 using namespace llvm::objcarc;
44 
45 #define DEBUG_TYPE "objc-arc-contract"
46 
47 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
48 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
49 
50 //===----------------------------------------------------------------------===//
51 //                                Declarations
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55   /// Late ARC optimizations
56   ///
57   /// These change the IR in a way that makes it difficult to be analyzed by
58   /// ObjCARCOpt, so it's run late.
59   class ObjCARCContract : public FunctionPass {
60     bool Changed;
61     AliasAnalysis *AA;
62     DominatorTree *DT;
63     ProvenanceAnalysis PA;
64     ARCRuntimeEntryPoints EP;
65 
66     /// A flag indicating whether this optimization pass should run.
67     bool Run;
68 
69     /// The inline asm string to insert between calls and RetainRV calls to make
70     /// the optimization work on targets which need it.
71     const MDString *RVInstMarker;
72 
73     /// The set of inserted objc_storeStrong calls. If at the end of walking the
74     /// function we have found no alloca instructions, these calls can be marked
75     /// "tail".
76     SmallPtrSet<CallInst *, 8> StoreStrongCalls;
77 
78     /// Returns true if we eliminated Inst.
79     bool tryToPeepholeInstruction(
80         Function &F, Instruction *Inst, inst_iterator &Iter,
81         SmallPtrSetImpl<Instruction *> &DepInsts,
82         SmallPtrSetImpl<const BasicBlock *> &Visited,
83         bool &TailOkForStoreStrong,
84         const DenseMap<BasicBlock *, ColorVector> &BlockColors);
85 
86     bool optimizeRetainCall(Function &F, Instruction *Retain);
87 
88     bool
89     contractAutorelease(Function &F, Instruction *Autorelease,
90                         ARCInstKind Class,
91                         SmallPtrSetImpl<Instruction *> &DependingInstructions,
92                         SmallPtrSetImpl<const BasicBlock *> &Visited);
93 
94     void tryToContractReleaseIntoStoreStrong(
95         Instruction *Release, inst_iterator &Iter,
96         const DenseMap<BasicBlock *, ColorVector> &BlockColors);
97 
98     void getAnalysisUsage(AnalysisUsage &AU) const override;
99     bool doInitialization(Module &M) override;
100     bool runOnFunction(Function &F) override;
101 
102   public:
103     static char ID;
104     ObjCARCContract() : FunctionPass(ID) {
105       initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
106     }
107   };
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                               Implementation
112 //===----------------------------------------------------------------------===//
113 
114 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
115 /// return value. We do this late so we do not disrupt the dataflow analysis in
116 /// ObjCARCOpt.
117 bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
118   const auto *Call = dyn_cast<CallBase>(GetArgRCIdentityRoot(Retain));
119   if (!Call)
120     return false;
121   if (Call->getParent() != Retain->getParent())
122     return false;
123 
124   // Check that the call is next to the retain.
125   BasicBlock::const_iterator I = ++Call->getIterator();
126   while (IsNoopInstruction(&*I))
127     ++I;
128   if (&*I != Retain)
129     return false;
130 
131   // Turn it to an objc_retainAutoreleasedReturnValue.
132   Changed = true;
133   ++NumPeeps;
134 
135   LLVM_DEBUG(
136       dbgs() << "Transforming objc_retain => "
137                 "objc_retainAutoreleasedReturnValue since the operand is a "
138                 "return value.\nOld: "
139              << *Retain << "\n");
140 
141   // We do not have to worry about tail calls/does not throw since
142   // retain/retainRV have the same properties.
143   Function *Decl = EP.get(ARCRuntimeEntryPointKind::RetainRV);
144   cast<CallInst>(Retain)->setCalledFunction(Decl);
145 
146   LLVM_DEBUG(dbgs() << "New: " << *Retain << "\n");
147   return true;
148 }
149 
150 /// Merge an autorelease with a retain into a fused call.
151 bool ObjCARCContract::contractAutorelease(
152     Function &F, Instruction *Autorelease, ARCInstKind Class,
153     SmallPtrSetImpl<Instruction *> &DependingInstructions,
154     SmallPtrSetImpl<const BasicBlock *> &Visited) {
155   const Value *Arg = GetArgRCIdentityRoot(Autorelease);
156 
157   // Check that there are no instructions between the retain and the autorelease
158   // (such as an autorelease_pop) which may change the count.
159   CallInst *Retain = nullptr;
160   if (Class == ARCInstKind::AutoreleaseRV)
161     FindDependencies(RetainAutoreleaseRVDep, Arg,
162                      Autorelease->getParent(), Autorelease,
163                      DependingInstructions, Visited, PA);
164   else
165     FindDependencies(RetainAutoreleaseDep, Arg,
166                      Autorelease->getParent(), Autorelease,
167                      DependingInstructions, Visited, PA);
168 
169   Visited.clear();
170   if (DependingInstructions.size() != 1) {
171     DependingInstructions.clear();
172     return false;
173   }
174 
175   Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
176   DependingInstructions.clear();
177 
178   if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
179       GetArgRCIdentityRoot(Retain) != Arg)
180     return false;
181 
182   Changed = true;
183   ++NumPeeps;
184 
185   LLVM_DEBUG(dbgs() << "    Fusing retain/autorelease!\n"
186                        "        Autorelease:"
187                     << *Autorelease
188                     << "\n"
189                        "        Retain: "
190                     << *Retain << "\n");
191 
192   Function *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
193                               ? ARCRuntimeEntryPointKind::RetainAutoreleaseRV
194                               : ARCRuntimeEntryPointKind::RetainAutorelease);
195   Retain->setCalledFunction(Decl);
196 
197   LLVM_DEBUG(dbgs() << "        New RetainAutorelease: " << *Retain << "\n");
198 
199   EraseInstruction(Autorelease);
200   return true;
201 }
202 
203 static StoreInst *findSafeStoreForStoreStrongContraction(LoadInst *Load,
204                                                          Instruction *Release,
205                                                          ProvenanceAnalysis &PA,
206                                                          AliasAnalysis *AA) {
207   StoreInst *Store = nullptr;
208   bool SawRelease = false;
209 
210   // Get the location associated with Load.
211   MemoryLocation Loc = MemoryLocation::get(Load);
212   auto *LocPtr = Loc.Ptr->stripPointerCasts();
213 
214   // Walk down to find the store and the release, which may be in either order.
215   for (auto I = std::next(BasicBlock::iterator(Load)),
216             E = Load->getParent()->end();
217        I != E; ++I) {
218     // If we found the store we were looking for and saw the release,
219     // break. There is no more work to be done.
220     if (Store && SawRelease)
221       break;
222 
223     // Now we know that we have not seen either the store or the release. If I
224     // is the release, mark that we saw the release and continue.
225     Instruction *Inst = &*I;
226     if (Inst == Release) {
227       SawRelease = true;
228       continue;
229     }
230 
231     // Otherwise, we check if Inst is a "good" store. Grab the instruction class
232     // of Inst.
233     ARCInstKind Class = GetBasicARCInstKind(Inst);
234 
235     // If Inst is an unrelated retain, we don't care about it.
236     //
237     // TODO: This is one area where the optimization could be made more
238     // aggressive.
239     if (IsRetain(Class))
240       continue;
241 
242     // If we have seen the store, but not the release...
243     if (Store) {
244       // We need to make sure that it is safe to move the release from its
245       // current position to the store. This implies proving that any
246       // instruction in between Store and the Release conservatively can not use
247       // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
248       // continue...
249       if (!CanUse(Inst, Load, PA, Class)) {
250         continue;
251       }
252 
253       // Otherwise, be conservative and return nullptr.
254       return nullptr;
255     }
256 
257     // Ok, now we know we have not seen a store yet. See if Inst can write to
258     // our load location, if it can not, just ignore the instruction.
259     if (!isModSet(AA->getModRefInfo(Inst, Loc)))
260       continue;
261 
262     Store = dyn_cast<StoreInst>(Inst);
263 
264     // If Inst can, then check if Inst is a simple store. If Inst is not a
265     // store or a store that is not simple, then we have some we do not
266     // understand writing to this memory implying we can not move the load
267     // over the write to any subsequent store that we may find.
268     if (!Store || !Store->isSimple())
269       return nullptr;
270 
271     // Then make sure that the pointer we are storing to is Ptr. If so, we
272     // found our Store!
273     if (Store->getPointerOperand()->stripPointerCasts() == LocPtr)
274       continue;
275 
276     // Otherwise, we have an unknown store to some other ptr that clobbers
277     // Loc.Ptr. Bail!
278     return nullptr;
279   }
280 
281   // If we did not find the store or did not see the release, fail.
282   if (!Store || !SawRelease)
283     return nullptr;
284 
285   // We succeeded!
286   return Store;
287 }
288 
289 static Instruction *
290 findRetainForStoreStrongContraction(Value *New, StoreInst *Store,
291                                     Instruction *Release,
292                                     ProvenanceAnalysis &PA) {
293   // Walk up from the Store to find the retain.
294   BasicBlock::iterator I = Store->getIterator();
295   BasicBlock::iterator Begin = Store->getParent()->begin();
296   while (I != Begin && GetBasicARCInstKind(&*I) != ARCInstKind::Retain) {
297     Instruction *Inst = &*I;
298 
299     // It is only safe to move the retain to the store if we can prove
300     // conservatively that nothing besides the release can decrement reference
301     // counts in between the retain and the store.
302     if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
303       return nullptr;
304     --I;
305   }
306   Instruction *Retain = &*I;
307   if (GetBasicARCInstKind(Retain) != ARCInstKind::Retain)
308     return nullptr;
309   if (GetArgRCIdentityRoot(Retain) != New)
310     return nullptr;
311   return Retain;
312 }
313 
314 /// Create a call instruction with the correct funclet token. Should be used
315 /// instead of calling CallInst::Create directly.
316 static CallInst *
317 createCallInst(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
318                const Twine &NameStr, Instruction *InsertBefore,
319                const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
320   SmallVector<OperandBundleDef, 1> OpBundles;
321   if (!BlockColors.empty()) {
322     const ColorVector &CV = BlockColors.find(InsertBefore->getParent())->second;
323     assert(CV.size() == 1 && "non-unique color for block!");
324     Instruction *EHPad = CV.front()->getFirstNonPHI();
325     if (EHPad->isEHPad())
326       OpBundles.emplace_back("funclet", EHPad);
327   }
328 
329   return CallInst::Create(FTy, Func, Args, OpBundles, NameStr, InsertBefore);
330 }
331 
332 static CallInst *
333 createCallInst(FunctionCallee Func, ArrayRef<Value *> Args, const Twine &NameStr,
334                Instruction *InsertBefore,
335                const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
336   return createCallInst(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
337                         InsertBefore, BlockColors);
338 }
339 
340 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
341 /// an objc_storeStrong. An objc_storeStrong:
342 ///
343 ///   objc_storeStrong(i8** %old_ptr, i8* new_value)
344 ///
345 /// is equivalent to the following IR sequence:
346 ///
347 ///   ; Load old value.
348 ///   %old_value = load i8** %old_ptr               (1)
349 ///
350 ///   ; Increment the new value and then release the old value. This must occur
351 ///   ; in order in case old_value releases new_value in its destructor causing
352 ///   ; us to potentially have a dangling ptr.
353 ///   tail call i8* @objc_retain(i8* %new_value)    (2)
354 ///   tail call void @objc_release(i8* %old_value)  (3)
355 ///
356 ///   ; Store the new_value into old_ptr
357 ///   store i8* %new_value, i8** %old_ptr           (4)
358 ///
359 /// The safety of this optimization is based around the following
360 /// considerations:
361 ///
362 ///  1. We are forming the store strong at the store. Thus to perform this
363 ///     optimization it must be safe to move the retain, load, and release to
364 ///     (4).
365 ///  2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
366 ///     safe.
367 void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
368     Instruction *Release, inst_iterator &Iter,
369     const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
370   // See if we are releasing something that we just loaded.
371   auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
372   if (!Load || !Load->isSimple())
373     return;
374 
375   // For now, require everything to be in one basic block.
376   BasicBlock *BB = Release->getParent();
377   if (Load->getParent() != BB)
378     return;
379 
380   // First scan down the BB from Load, looking for a store of the RCIdentityRoot
381   // of Load's
382   StoreInst *Store =
383       findSafeStoreForStoreStrongContraction(Load, Release, PA, AA);
384   // If we fail, bail.
385   if (!Store)
386     return;
387 
388   // Then find what new_value's RCIdentity Root is.
389   Value *New = GetRCIdentityRoot(Store->getValueOperand());
390 
391   // Then walk up the BB and look for a retain on New without any intervening
392   // instructions which conservatively might decrement ref counts.
393   Instruction *Retain =
394       findRetainForStoreStrongContraction(New, Store, Release, PA);
395 
396   // If we fail, bail.
397   if (!Retain)
398     return;
399 
400   Changed = true;
401   ++NumStoreStrongs;
402 
403   LLVM_DEBUG(
404       llvm::dbgs() << "    Contracting retain, release into objc_storeStrong.\n"
405                    << "        Old:\n"
406                    << "            Store:   " << *Store << "\n"
407                    << "            Release: " << *Release << "\n"
408                    << "            Retain:  " << *Retain << "\n"
409                    << "            Load:    " << *Load << "\n");
410 
411   LLVMContext &C = Release->getContext();
412   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
413   Type *I8XX = PointerType::getUnqual(I8X);
414 
415   Value *Args[] = { Load->getPointerOperand(), New };
416   if (Args[0]->getType() != I8XX)
417     Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
418   if (Args[1]->getType() != I8X)
419     Args[1] = new BitCastInst(Args[1], I8X, "", Store);
420   Function *Decl = EP.get(ARCRuntimeEntryPointKind::StoreStrong);
421   CallInst *StoreStrong = createCallInst(Decl, Args, "", Store, BlockColors);
422   StoreStrong->setDoesNotThrow();
423   StoreStrong->setDebugLoc(Store->getDebugLoc());
424 
425   // We can't set the tail flag yet, because we haven't yet determined
426   // whether there are any escaping allocas. Remember this call, so that
427   // we can set the tail flag once we know it's safe.
428   StoreStrongCalls.insert(StoreStrong);
429 
430   LLVM_DEBUG(llvm::dbgs() << "        New Store Strong: " << *StoreStrong
431                           << "\n");
432 
433   if (&*Iter == Retain) ++Iter;
434   if (&*Iter == Store) ++Iter;
435   Store->eraseFromParent();
436   Release->eraseFromParent();
437   EraseInstruction(Retain);
438   if (Load->use_empty())
439     Load->eraseFromParent();
440 }
441 
442 bool ObjCARCContract::tryToPeepholeInstruction(
443     Function &F, Instruction *Inst, inst_iterator &Iter,
444     SmallPtrSetImpl<Instruction *> &DependingInsts,
445     SmallPtrSetImpl<const BasicBlock *> &Visited, bool &TailOkForStoreStrongs,
446     const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
447   // Only these library routines return their argument. In particular,
448   // objc_retainBlock does not necessarily return its argument.
449   ARCInstKind Class = GetBasicARCInstKind(Inst);
450   switch (Class) {
451   case ARCInstKind::FusedRetainAutorelease:
452   case ARCInstKind::FusedRetainAutoreleaseRV:
453     return false;
454   case ARCInstKind::Autorelease:
455   case ARCInstKind::AutoreleaseRV:
456     return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
457   case ARCInstKind::Retain:
458     // Attempt to convert retains to retainrvs if they are next to function
459     // calls.
460     if (!optimizeRetainCall(F, Inst))
461       return false;
462     // If we succeed in our optimization, fall through.
463     LLVM_FALLTHROUGH;
464   case ARCInstKind::RetainRV:
465   case ARCInstKind::ClaimRV: {
466     // If we're compiling for a target which needs a special inline-asm
467     // marker to do the return value optimization, insert it now.
468     if (!RVInstMarker)
469       return false;
470     BasicBlock::iterator BBI = Inst->getIterator();
471     BasicBlock *InstParent = Inst->getParent();
472 
473     // Step up to see if the call immediately precedes the RV call.
474     // If it's an invoke, we have to cross a block boundary. And we have
475     // to carefully dodge no-op instructions.
476     do {
477       if (BBI == InstParent->begin()) {
478         BasicBlock *Pred = InstParent->getSinglePredecessor();
479         if (!Pred)
480           goto decline_rv_optimization;
481         BBI = Pred->getTerminator()->getIterator();
482         break;
483       }
484       --BBI;
485     } while (IsNoopInstruction(&*BBI));
486 
487     if (&*BBI == GetArgRCIdentityRoot(Inst)) {
488       LLVM_DEBUG(dbgs() << "Adding inline asm marker for the return value "
489                            "optimization.\n");
490       Changed = true;
491       InlineAsm *IA =
492           InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
493                                            /*isVarArg=*/false),
494                          RVInstMarker->getString(),
495                          /*Constraints=*/"", /*hasSideEffects=*/true);
496 
497       createCallInst(IA, None, "", Inst, BlockColors);
498     }
499   decline_rv_optimization:
500     return false;
501   }
502   case ARCInstKind::InitWeak: {
503     // objc_initWeak(p, null) => *p = null
504     CallInst *CI = cast<CallInst>(Inst);
505     if (IsNullOrUndef(CI->getArgOperand(1))) {
506       Value *Null = ConstantPointerNull::get(cast<PointerType>(CI->getType()));
507       Changed = true;
508       new StoreInst(Null, CI->getArgOperand(0), CI);
509 
510       LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
511                         << "                 New = " << *Null << "\n");
512 
513       CI->replaceAllUsesWith(Null);
514       CI->eraseFromParent();
515     }
516     return true;
517   }
518   case ARCInstKind::Release:
519     // Try to form an objc store strong from our release. If we fail, there is
520     // nothing further to do below, so continue.
521     tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
522     return true;
523   case ARCInstKind::User:
524     // Be conservative if the function has any alloca instructions.
525     // Technically we only care about escaping alloca instructions,
526     // but this is sufficient to handle some interesting cases.
527     if (isa<AllocaInst>(Inst))
528       TailOkForStoreStrongs = false;
529     return true;
530   case ARCInstKind::IntrinsicUser:
531     // Remove calls to @llvm.objc.clang.arc.use(...).
532     Changed = true;
533     Inst->eraseFromParent();
534     return true;
535   default:
536     return true;
537   }
538 }
539 
540 //===----------------------------------------------------------------------===//
541 //                              Top Level Driver
542 //===----------------------------------------------------------------------===//
543 
544 bool ObjCARCContract::runOnFunction(Function &F) {
545   if (!EnableARCOpts)
546     return false;
547 
548   // If nothing in the Module uses ARC, don't do anything.
549   if (!Run)
550     return false;
551 
552   Changed = false;
553   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
554   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
555 
556   PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
557 
558   DenseMap<BasicBlock *, ColorVector> BlockColors;
559   if (F.hasPersonalityFn() &&
560       isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
561     BlockColors = colorEHFunclets(F);
562 
563   LLVM_DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
564 
565   // Track whether it's ok to mark objc_storeStrong calls with the "tail"
566   // keyword. Be conservative if the function has variadic arguments.
567   // It seems that functions which "return twice" are also unsafe for the
568   // "tail" argument, because they are setjmp, which could need to
569   // return to an earlier stack state.
570   bool TailOkForStoreStrongs =
571       !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
572 
573   // For ObjC library calls which return their argument, replace uses of the
574   // argument with uses of the call return value, if it dominates the use. This
575   // reduces register pressure.
576   SmallPtrSet<Instruction *, 4> DependingInstructions;
577   SmallPtrSet<const BasicBlock *, 4> Visited;
578 
579   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
580     Instruction *Inst = &*I++;
581 
582     LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
583 
584     // First try to peephole Inst. If there is nothing further we can do in
585     // terms of undoing objc-arc-expand, process the next inst.
586     if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
587                                  TailOkForStoreStrongs, BlockColors))
588       continue;
589 
590     // Otherwise, try to undo objc-arc-expand.
591 
592     // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
593     // and such; to do the replacement, the argument must have type i8*.
594 
595     // Function for replacing uses of Arg dominated by Inst.
596     auto ReplaceArgUses = [Inst, this](Value *Arg) {
597       // If we're compiling bugpointed code, don't get in trouble.
598       if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
599         return;
600 
601       // Look through the uses of the pointer.
602       for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
603            UI != UE; ) {
604         // Increment UI now, because we may unlink its element.
605         Use &U = *UI++;
606         unsigned OperandNo = U.getOperandNo();
607 
608         // If the call's return value dominates a use of the call's argument
609         // value, rewrite the use to use the return value. We check for
610         // reachability here because an unreachable call is considered to
611         // trivially dominate itself, which would lead us to rewriting its
612         // argument in terms of its return value, which would lead to
613         // infinite loops in GetArgRCIdentityRoot.
614         if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
615           continue;
616 
617         Changed = true;
618         Instruction *Replacement = Inst;
619         Type *UseTy = U.get()->getType();
620         if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
621           // For PHI nodes, insert the bitcast in the predecessor block.
622           unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
623           BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
624           if (Replacement->getType() != UseTy) {
625             // A catchswitch is both a pad and a terminator, meaning a basic
626             // block with a catchswitch has no insertion point. Keep going up
627             // the dominator tree until we find a non-catchswitch.
628             BasicBlock *InsertBB = IncomingBB;
629             while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
630               InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
631             }
632 
633             assert(DT->dominates(Inst, &InsertBB->back()) &&
634                    "Invalid insertion point for bitcast");
635             Replacement =
636                 new BitCastInst(Replacement, UseTy, "", &InsertBB->back());
637           }
638 
639           // While we're here, rewrite all edges for this PHI, rather
640           // than just one use at a time, to minimize the number of
641           // bitcasts we emit.
642           for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
643             if (PHI->getIncomingBlock(i) == IncomingBB) {
644               // Keep the UI iterator valid.
645               if (UI != UE &&
646                   &PHI->getOperandUse(
647                       PHINode::getOperandNumForIncomingValue(i)) == &*UI)
648                 ++UI;
649               PHI->setIncomingValue(i, Replacement);
650             }
651         } else {
652           if (Replacement->getType() != UseTy)
653             Replacement = new BitCastInst(Replacement, UseTy, "",
654                                           cast<Instruction>(U.getUser()));
655           U.set(Replacement);
656         }
657       }
658     };
659 
660     Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
661     Value *OrigArg = Arg;
662 
663     // TODO: Change this to a do-while.
664     for (;;) {
665       ReplaceArgUses(Arg);
666 
667       // If Arg is a no-op casted pointer, strip one level of casts and iterate.
668       if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
669         Arg = BI->getOperand(0);
670       else if (isa<GEPOperator>(Arg) &&
671                cast<GEPOperator>(Arg)->hasAllZeroIndices())
672         Arg = cast<GEPOperator>(Arg)->getPointerOperand();
673       else if (isa<GlobalAlias>(Arg) &&
674                !cast<GlobalAlias>(Arg)->isInterposable())
675         Arg = cast<GlobalAlias>(Arg)->getAliasee();
676       else {
677         // If Arg is a PHI node, get PHIs that are equivalent to it and replace
678         // their uses.
679         if (PHINode *PN = dyn_cast<PHINode>(Arg)) {
680           SmallVector<Value *, 1> PHIList;
681           getEquivalentPHIs(*PN, PHIList);
682           for (Value *PHI : PHIList)
683             ReplaceArgUses(PHI);
684         }
685         break;
686       }
687     }
688 
689     // Replace bitcast users of Arg that are dominated by Inst.
690     SmallVector<BitCastInst *, 2> BitCastUsers;
691 
692     // Add all bitcast users of the function argument first.
693     for (User *U : OrigArg->users())
694       if (auto *BC = dyn_cast<BitCastInst>(U))
695         BitCastUsers.push_back(BC);
696 
697     // Replace the bitcasts with the call return. Iterate until list is empty.
698     while (!BitCastUsers.empty()) {
699       auto *BC = BitCastUsers.pop_back_val();
700       for (User *U : BC->users())
701         if (auto *B = dyn_cast<BitCastInst>(U))
702           BitCastUsers.push_back(B);
703 
704       ReplaceArgUses(BC);
705     }
706   }
707 
708   // If this function has no escaping allocas or suspicious vararg usage,
709   // objc_storeStrong calls can be marked with the "tail" keyword.
710   if (TailOkForStoreStrongs)
711     for (CallInst *CI : StoreStrongCalls)
712       CI->setTailCall();
713   StoreStrongCalls.clear();
714 
715   return Changed;
716 }
717 
718 //===----------------------------------------------------------------------===//
719 //                             Misc Pass Manager
720 //===----------------------------------------------------------------------===//
721 
722 char ObjCARCContract::ID = 0;
723 INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
724                       "ObjC ARC contraction", false, false)
725 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
726 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
727 INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
728                     "ObjC ARC contraction", false, false)
729 
730 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
731   AU.addRequired<AAResultsWrapperPass>();
732   AU.addRequired<DominatorTreeWrapperPass>();
733   AU.setPreservesCFG();
734 }
735 
736 Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
737 
738 bool ObjCARCContract::doInitialization(Module &M) {
739   // If nothing in the Module uses ARC, don't do anything.
740   Run = ModuleHasARC(M);
741   if (!Run)
742     return false;
743 
744   EP.init(&M);
745 
746   // Initialize RVInstMarker.
747   const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
748   RVInstMarker = dyn_cast_or_null<MDString>(M.getModuleFlag(MarkerKey));
749 
750   return false;
751 }
752