LLVM  9.0.0svn
ObjCARCContract.cpp
Go to the documentation of this file.
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"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/Support/Debug.h"
39 
40 using namespace llvm;
41 using namespace llvm::objcarc;
42 
43 #define DEBUG_TYPE "objc-arc-contract"
44 
45 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
46 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
47 
48 //===----------------------------------------------------------------------===//
49 // Declarations
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53  /// Late ARC optimizations
54  ///
55  /// These change the IR in a way that makes it difficult to be analyzed by
56  /// ObjCARCOpt, so it's run late.
57  class ObjCARCContract : public FunctionPass {
58  bool Changed;
59  AliasAnalysis *AA;
60  DominatorTree *DT;
63 
64  /// A flag indicating whether this optimization pass should run.
65  bool Run;
66 
67  /// The inline asm string to insert between calls and RetainRV calls to make
68  /// the optimization work on targets which need it.
69  const MDString *RVInstMarker;
70 
71  /// The set of inserted objc_storeStrong calls. If at the end of walking the
72  /// function we have found no alloca instructions, these calls can be marked
73  /// "tail".
74  SmallPtrSet<CallInst *, 8> StoreStrongCalls;
75 
76  /// Returns true if we eliminated Inst.
77  bool tryToPeepholeInstruction(
78  Function &F, Instruction *Inst, inst_iterator &Iter,
81  bool &TailOkForStoreStrong,
82  const DenseMap<BasicBlock *, ColorVector> &BlockColors);
83 
84  bool optimizeRetainCall(Function &F, Instruction *Retain);
85 
86  bool
87  contractAutorelease(Function &F, Instruction *Autorelease,
88  ARCInstKind Class,
89  SmallPtrSetImpl<Instruction *> &DependingInstructions,
91 
92  void tryToContractReleaseIntoStoreStrong(
94  const DenseMap<BasicBlock *, ColorVector> &BlockColors);
95 
96  void getAnalysisUsage(AnalysisUsage &AU) const override;
97  bool doInitialization(Module &M) override;
98  bool runOnFunction(Function &F) override;
99 
100  public:
101  static char ID;
102  ObjCARCContract() : FunctionPass(ID) {
104  }
105  };
106 }
107 
108 //===----------------------------------------------------------------------===//
109 // Implementation
110 //===----------------------------------------------------------------------===//
111 
112 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
113 /// return value. We do this late so we do not disrupt the dataflow analysis in
114 /// ObjCARCOpt.
115 bool ObjCARCContract::optimizeRetainCall(Function &F, Instruction *Retain) {
117  const Instruction *Call = CS.getInstruction();
118  if (!Call)
119  return false;
120  if (Call->getParent() != Retain->getParent())
121  return false;
122 
123  // Check that the call is next to the retain.
125  while (IsNoopInstruction(&*I))
126  ++I;
127  if (&*I != Retain)
128  return false;
129 
130  // Turn it to an objc_retainAutoreleasedReturnValue.
131  Changed = true;
132  ++NumPeeps;
133 
134  LLVM_DEBUG(
135  dbgs() << "Transforming objc_retain => "
136  "objc_retainAutoreleasedReturnValue since the operand is a "
137  "return value.\nOld: "
138  << *Retain << "\n");
139 
140  // We do not have to worry about tail calls/does not throw since
141  // retain/retainRV have the same properties.
143  cast<CallInst>(Retain)->setCalledFunction(Decl);
144 
145  LLVM_DEBUG(dbgs() << "New: " << *Retain << "\n");
146  return true;
147 }
148 
149 /// Merge an autorelease with a retain into a fused call.
150 bool ObjCARCContract::contractAutorelease(
152  SmallPtrSetImpl<Instruction *> &DependingInstructions,
154  const Value *Arg = GetArgRCIdentityRoot(Autorelease);
155 
156  // Check that there are no instructions between the retain and the autorelease
157  // (such as an autorelease_pop) which may change the count.
158  CallInst *Retain = nullptr;
159  if (Class == ARCInstKind::AutoreleaseRV)
161  Autorelease->getParent(), Autorelease,
162  DependingInstructions, Visited, PA);
163  else
165  Autorelease->getParent(), Autorelease,
166  DependingInstructions, Visited, PA);
167 
168  Visited.clear();
169  if (DependingInstructions.size() != 1) {
170  DependingInstructions.clear();
171  return false;
172  }
173 
174  Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
175  DependingInstructions.clear();
176 
177  if (!Retain || GetBasicARCInstKind(Retain) != ARCInstKind::Retain ||
178  GetArgRCIdentityRoot(Retain) != Arg)
179  return false;
180 
181  Changed = true;
182  ++NumPeeps;
183 
184  LLVM_DEBUG(dbgs() << " Fusing retain/autorelease!\n"
185  " Autorelease:"
186  << *Autorelease
187  << "\n"
188  " Retain: "
189  << *Retain << "\n");
190 
191  Function *Decl = EP.get(Class == ARCInstKind::AutoreleaseRV
194  Retain->setCalledFunction(Decl);
195 
196  LLVM_DEBUG(dbgs() << " New RetainAutorelease: " << *Retain << "\n");
197 
198  EraseInstruction(Autorelease);
199  return true;
200 }
201 
204  ProvenanceAnalysis &PA,
205  AliasAnalysis *AA) {
206  StoreInst *Store = nullptr;
207  bool SawRelease = false;
208 
209  // Get the location associated with Load.
211  auto *LocPtr = Loc.Ptr->stripPointerCasts();
212 
213  // Walk down to find the store and the release, which may be in either order.
214  for (auto I = std::next(BasicBlock::iterator(Load)),
215  E = Load->getParent()->end();
216  I != E; ++I) {
217  // If we found the store we were looking for and saw the release,
218  // break. There is no more work to be done.
219  if (Store && SawRelease)
220  break;
221 
222  // Now we know that we have not seen either the store or the release. If I
223  // is the release, mark that we saw the release and continue.
224  Instruction *Inst = &*I;
225  if (Inst == Release) {
226  SawRelease = true;
227  continue;
228  }
229 
230  // Otherwise, we check if Inst is a "good" store. Grab the instruction class
231  // of Inst.
232  ARCInstKind Class = GetBasicARCInstKind(Inst);
233 
234  // If Inst is an unrelated retain, we don't care about it.
235  //
236  // TODO: This is one area where the optimization could be made more
237  // aggressive.
238  if (IsRetain(Class))
239  continue;
240 
241  // If we have seen the store, but not the release...
242  if (Store) {
243  // We need to make sure that it is safe to move the release from its
244  // current position to the store. This implies proving that any
245  // instruction in between Store and the Release conservatively can not use
246  // the RCIdentityRoot of Release. If we can prove we can ignore Inst, so
247  // continue...
248  if (!CanUse(Inst, Load, PA, Class)) {
249  continue;
250  }
251 
252  // Otherwise, be conservative and return nullptr.
253  return nullptr;
254  }
255 
256  // Ok, now we know we have not seen a store yet. See if Inst can write to
257  // our load location, if it can not, just ignore the instruction.
258  if (!isModSet(AA->getModRefInfo(Inst, Loc)))
259  continue;
260 
261  Store = dyn_cast<StoreInst>(Inst);
262 
263  // If Inst can, then check if Inst is a simple store. If Inst is not a
264  // store or a store that is not simple, then we have some we do not
265  // understand writing to this memory implying we can not move the load
266  // over the write to any subsequent store that we may find.
267  if (!Store || !Store->isSimple())
268  return nullptr;
269 
270  // Then make sure that the pointer we are storing to is Ptr. If so, we
271  // found our Store!
272  if (Store->getPointerOperand()->stripPointerCasts() == LocPtr)
273  continue;
274 
275  // Otherwise, we have an unknown store to some other ptr that clobbers
276  // Loc.Ptr. Bail!
277  return nullptr;
278  }
279 
280  // If we did not find the store or did not see the release, fail.
281  if (!Store || !SawRelease)
282  return nullptr;
283 
284  // We succeeded!
285  return Store;
286 }
287 
288 static Instruction *
291  ProvenanceAnalysis &PA) {
292  // Walk up from the Store to find the retain.
293  BasicBlock::iterator I = Store->getIterator();
294  BasicBlock::iterator Begin = Store->getParent()->begin();
295  while (I != Begin && GetBasicARCInstKind(&*I) != ARCInstKind::Retain) {
296  Instruction *Inst = &*I;
297 
298  // It is only safe to move the retain to the store if we can prove
299  // conservatively that nothing besides the release can decrement reference
300  // counts in between the retain and the store.
301  if (CanDecrementRefCount(Inst, New, PA) && Inst != Release)
302  return nullptr;
303  --I;
304  }
305  Instruction *Retain = &*I;
307  return nullptr;
308  if (GetArgRCIdentityRoot(Retain) != New)
309  return nullptr;
310  return Retain;
311 }
312 
313 /// Create a call instruction with the correct funclet token. Should be used
314 /// instead of calling CallInst::Create directly.
315 static CallInst *
317  const Twine &NameStr, Instruction *InsertBefore,
318  const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
320  if (!BlockColors.empty()) {
321  const ColorVector &CV = BlockColors.find(InsertBefore->getParent())->second;
322  assert(CV.size() == 1 && "non-unique color for block!");
323  Instruction *EHPad = CV.front()->getFirstNonPHI();
324  if (EHPad->isEHPad())
325  OpBundles.emplace_back("funclet", EHPad);
326  }
327 
328  return CallInst::Create(FTy, Func, Args, OpBundles, NameStr, InsertBefore);
329 }
330 
331 static CallInst *
333  Instruction *InsertBefore,
334  const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
335  return createCallInst(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
336  InsertBefore, BlockColors);
337 }
338 
339 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
340 /// an objc_storeStrong. An objc_storeStrong:
341 ///
342 /// objc_storeStrong(i8** %old_ptr, i8* new_value)
343 ///
344 /// is equivalent to the following IR sequence:
345 ///
346 /// ; Load old value.
347 /// %old_value = load i8** %old_ptr (1)
348 ///
349 /// ; Increment the new value and then release the old value. This must occur
350 /// ; in order in case old_value releases new_value in its destructor causing
351 /// ; us to potentially have a dangling ptr.
352 /// tail call i8* @objc_retain(i8* %new_value) (2)
353 /// tail call void @objc_release(i8* %old_value) (3)
354 ///
355 /// ; Store the new_value into old_ptr
356 /// store i8* %new_value, i8** %old_ptr (4)
357 ///
358 /// The safety of this optimization is based around the following
359 /// considerations:
360 ///
361 /// 1. We are forming the store strong at the store. Thus to perform this
362 /// optimization it must be safe to move the retain, load, and release to
363 /// (4).
364 /// 2. We need to make sure that any re-orderings of (1), (2), (3), (4) are
365 /// safe.
366 void ObjCARCContract::tryToContractReleaseIntoStoreStrong(
368  const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
369  // See if we are releasing something that we just loaded.
370  auto *Load = dyn_cast<LoadInst>(GetArgRCIdentityRoot(Release));
371  if (!Load || !Load->isSimple())
372  return;
373 
374  // For now, require everything to be in one basic block.
375  BasicBlock *BB = Release->getParent();
376  if (Load->getParent() != BB)
377  return;
378 
379  // First scan down the BB from Load, looking for a store of the RCIdentityRoot
380  // of Load's
381  StoreInst *Store =
383  // If we fail, bail.
384  if (!Store)
385  return;
386 
387  // Then find what new_value's RCIdentity Root is.
388  Value *New = GetRCIdentityRoot(Store->getValueOperand());
389 
390  // Then walk up the BB and look for a retain on New without any intervening
391  // instructions which conservatively might decrement ref counts.
392  Instruction *Retain =
393  findRetainForStoreStrongContraction(New, Store, Release, PA);
394 
395  // If we fail, bail.
396  if (!Retain)
397  return;
398 
399  Changed = true;
400  ++NumStoreStrongs;
401 
402  LLVM_DEBUG(
403  llvm::dbgs() << " Contracting retain, release into objc_storeStrong.\n"
404  << " Old:\n"
405  << " Store: " << *Store << "\n"
406  << " Release: " << *Release << "\n"
407  << " Retain: " << *Retain << "\n"
408  << " Load: " << *Load << "\n");
409 
410  LLVMContext &C = Release->getContext();
412  Type *I8XX = PointerType::getUnqual(I8X);
413 
414  Value *Args[] = { Load->getPointerOperand(), New };
415  if (Args[0]->getType() != I8XX)
416  Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
417  if (Args[1]->getType() != I8X)
418  Args[1] = new BitCastInst(Args[1], I8X, "", Store);
420  CallInst *StoreStrong = createCallInst(Decl, Args, "", Store, BlockColors);
421  StoreStrong->setDoesNotThrow();
422  StoreStrong->setDebugLoc(Store->getDebugLoc());
423 
424  // We can't set the tail flag yet, because we haven't yet determined
425  // whether there are any escaping allocas. Remember this call, so that
426  // we can set the tail flag once we know it's safe.
427  StoreStrongCalls.insert(StoreStrong);
428 
429  LLVM_DEBUG(llvm::dbgs() << " New Store Strong: " << *StoreStrong
430  << "\n");
431 
432  if (&*Iter == Retain) ++Iter;
433  if (&*Iter == Store) ++Iter;
434  Store->eraseFromParent();
435  Release->eraseFromParent();
436  EraseInstruction(Retain);
437  if (Load->use_empty())
438  Load->eraseFromParent();
439 }
440 
441 bool ObjCARCContract::tryToPeepholeInstruction(
442  Function &F, Instruction *Inst, inst_iterator &Iter,
443  SmallPtrSetImpl<Instruction *> &DependingInsts,
445  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) {
453  return false;
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.
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;
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 =
507  ConstantPointerNull::get(cast<PointerType>(CI->getType()));
508  Changed = true;
509  new StoreInst(Null, CI->getArgOperand(0), CI);
510 
511  LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
512  << " New = " << *Null << "\n");
513 
514  CI->replaceAllUsesWith(Null);
515  CI->eraseFromParent();
516  }
517  return true;
518  }
520  // Try to form an objc store strong from our release. If we fail, there is
521  // nothing further to do below, so continue.
522  tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
523  return true;
524  case ARCInstKind::User:
525  // Be conservative if the function has any alloca instructions.
526  // Technically we only care about escaping alloca instructions,
527  // but this is sufficient to handle some interesting cases.
528  if (isa<AllocaInst>(Inst))
529  TailOkForStoreStrongs = false;
530  return true;
532  // Remove calls to @llvm.objc.clang.arc.use(...).
533  Inst->eraseFromParent();
534  return true;
535  default:
536  return true;
537  }
538 }
539 
540 //===----------------------------------------------------------------------===//
541 // Top Level Driver
542 //===----------------------------------------------------------------------===//
543 
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 
559  if (F.hasPersonalityFn() &&
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 =
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;
578  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
579  Instruction *Inst = &*I++;
580 
581  LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
582 
583  // First try to peephole Inst. If there is nothing further we can do in
584  // terms of undoing objc-arc-expand, process the next inst.
585  if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
586  TailOkForStoreStrongs, BlockColors))
587  continue;
588 
589  // Otherwise, try to undo objc-arc-expand.
590 
591  // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
592  // and such; to do the replacement, the argument must have type i8*.
593 
594  // Function for replacing uses of Arg dominated by Inst.
595  auto ReplaceArgUses = [Inst, this](Value *Arg) {
596  // If we're compiling bugpointed code, don't get in trouble.
597  if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
598  return;
599 
600  // Look through the uses of the pointer.
601  for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
602  UI != UE; ) {
603  // Increment UI now, because we may unlink its element.
604  Use &U = *UI++;
605  unsigned OperandNo = U.getOperandNo();
606 
607  // If the call's return value dominates a use of the call's argument
608  // value, rewrite the use to use the return value. We check for
609  // reachability here because an unreachable call is considered to
610  // trivially dominate itself, which would lead us to rewriting its
611  // argument in terms of its return value, which would lead to
612  // infinite loops in GetArgRCIdentityRoot.
613  if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
614  continue;
615 
616  Changed = true;
617  Instruction *Replacement = Inst;
618  Type *UseTy = U.get()->getType();
619  if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
620  // For PHI nodes, insert the bitcast in the predecessor block.
621  unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
622  BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
623  if (Replacement->getType() != UseTy) {
624  // A catchswitch is both a pad and a terminator, meaning a basic
625  // block with a catchswitch has no insertion point. Keep going up
626  // the dominator tree until we find a non-catchswitch.
627  BasicBlock *InsertBB = IncomingBB;
628  while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
629  InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
630  }
631 
632  assert(DT->dominates(Inst, &InsertBB->back()) &&
633  "Invalid insertion point for bitcast");
634  Replacement =
635  new BitCastInst(Replacement, UseTy, "", &InsertBB->back());
636  }
637 
638  // While we're here, rewrite all edges for this PHI, rather
639  // than just one use at a time, to minimize the number of
640  // bitcasts we emit.
641  for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
642  if (PHI->getIncomingBlock(i) == IncomingBB) {
643  // Keep the UI iterator valid.
644  if (UI != UE &&
645  &PHI->getOperandUse(
647  ++UI;
648  PHI->setIncomingValue(i, Replacement);
649  }
650  } else {
651  if (Replacement->getType() != UseTy)
652  Replacement = new BitCastInst(Replacement, UseTy, "",
653  cast<Instruction>(U.getUser()));
654  U.set(Replacement);
655  }
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)
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  RVInstMarker = nullptr;
748  if (NamedMDNode *NMD =
749  M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
750  if (NMD->getNumOperands() == 1) {
751  const MDNode *N = NMD->getOperand(0);
752  if (N->getNumOperands() == 1)
753  if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
754  RVInstMarker = S;
755  }
756 
757  return false;
758 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:80
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition: Function.h:176
objc arc contract
uint64_t CallInst * C
Value * getValueOperand()
Definition: Instructions.h:409
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
use_iterator use_end()
Definition: Value.h:346
This file declares special dependency analysis routines used in Objective C ARC Optimizations.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * getPointerOperand(Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
This file contains a class ARCRuntimeEntryPoints for use in creating/managing references to entry poi...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
EltTy front() const
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
bool CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
Test whether the given instruction can "use" the given pointer&#39;s object in a way that requires the re...
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Blocks objc_retainAutorelease.
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:164
This class represents a function call, abstracting a target machine&#39;s calling convention.
static CallInst * createCallInst(FunctionType *FTy, Value *Func, ArrayRef< Value *> Args, const Twine &NameStr, Instruction *InsertBefore, const DenseMap< BasicBlock *, ColorVector > &BlockColors)
Create a call instruction with the correct funclet token.
Value * GetArgRCIdentityRoot(Value *Inst)
Assuming the given instruction is one of the special calls such as objc_retain or objc_release...
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
unsigned second
STATISTIC(NumFunctions, "Total number of functions")
Metadata node.
Definition: Metadata.h:863
F(f)
could call objc_release
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
An instruction for reading from memory.
Definition: Instructions.h:167
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:137
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:30
Value * get() const
Definition: Use.h:107
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1155
static unsigned getOperandNumForIncomingValue(unsigned i)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
A tuple of MDNodes.
Definition: Metadata.h:1325
objc_autoreleaseReturnValue
inst_iterator inst_begin(Function *F)
Definition: InstIterator.h:131
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
void initializeObjCARCContractPass(PassRegistry &)
bool IsNullOrUndef(const Value *V)
This file defines common definitions/declarations used by the ObjC ARC Optimizer. ...
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch, catchpad/ret, and cleanuppad/ret.
objc_retainAutoreleasedReturnValue
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Definition: Use.cpp:40
Class to represent function types.
Definition: DerivedTypes.h:102
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
Definition: InstrTypes.h:1237
Pass * createObjCARCContractPass()
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:250
This class represents a no-op cast from one type to another.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
An instruction for storing to memory.
Definition: Instructions.h:320
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:701
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition: Use.cpp:47
INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract", "ObjC ARC contraction", false, false) INITIALIZE_PASS_END(ObjCARCContract
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
use_iterator_impl< Use > use_iterator
Definition: Value.h:331
static bool runOnFunction(Function &F, bool PostInlining)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:189
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static StoreInst * findSafeStoreForStoreStrongContraction(LoadInst *Load, Instruction *Release, ProvenanceAnalysis &PA, AliasAnalysis *AA)
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:321
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1400
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:233
void set(Value *Val)
Definition: Value.h:670
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
objc_initWeak (derived)
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:160
const Instruction & back() const
Definition: BasicBlock.h:282
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:296
self_iterator getIterator()
Definition: ilist_node.h:81
static Instruction * findRetainForStoreStrongContraction(Value *New, StoreInst *Store, Instruction *Release, ProvenanceAnalysis &PA)
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
Definition: Value.cpp:529
static unsigned getIncomingValueNumForOperand(unsigned i)
static wasm::ValType getType(const TargetRegisterClass *RC)
anything that is inert from an ARC perspective.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
ARCInstKind GetBasicARCInstKind(const Value *V)
Determine which objc runtime call instruction class V belongs to.
bool CanDecrementRefCount(ARCInstKind Kind)
Returns false if conservatively we can prove that any instruction mapped to this kind can not decreme...
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
static void EraseInstruction(Instruction *CI)
Erase the given instruction.
Definition: ObjCARC.h:51
objc arc ObjC ARC contraction
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:417
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:513
iterator end()
Definition: BasicBlock.h:270
This file declares a special form of Alias Analysis called ``Provenance Analysis&#39;&#39;.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
ARCInstKind
Equivalence classes of instructions in the ARC Model.
objc_unsafeClaimAutoreleasedReturnValue
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:373
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void FindDependencies(DependenceKind Flavor, const Value *Arg, BasicBlock *StartBB, Instruction *StartInst, SmallPtrSetImpl< Instruction *> &DependingInstructions, SmallPtrSetImpl< const BasicBlock *> &Visited, ProvenanceAnalysis &PA)
Walk up the CFG from StartPos (which is in StartBB) and find local and non-local dependencies on Arg...
iterator_range< user_iterator > users()
Definition: Value.h:399
objc arc
objc_storeStrong (derived)
could "use" a pointer
bool IsRetain(ARCInstKind Class)
Test if the given class is objc_retain or equivalent.
use_iterator use_begin()
Definition: Value.h:338
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:324
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:644
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Establish a view to a call site for examination.
Definition: CallSite.h:892
Blocks objc_retainAutoreleaseReturnValue.
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
FunctionType * getFunctionType()
Definition: DerivedTypes.h:181
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
Declarations for ObjC runtime functions and constants.
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:42
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
Definition: Function.cpp:1293
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:72
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1302
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:250
This is similar to BasicAliasAnalysis, and it uses many of the same techniques, except it uses specia...
const Value * GetRCIdentityRoot(const Value *V)
The RCIdentity root of a value V is a dominating value U for which retaining or releasing U is equiva...
inst_iterator inst_end(Function *F)
Definition: InstIterator.h:132
A single uniqued string.
Definition: Metadata.h:603
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool isSimple() const
Definition: Instructions.h:401
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
#define LLVM_DEBUG(X)
Definition: Debug.h:122
Value * getPointerOperand()
Definition: Instructions.h:412
void setDoesNotThrow()
Definition: InstrTypes.h:1592
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
unsigned size() const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void getEquivalentPHIs(PHINodeTy &PN, VectorTy &PHIList)
Return the list of PHI nodes that are equivalent to PN.
Definition: ObjCARC.h:86
bool IsNoopInstruction(const Instruction *I)
const BasicBlock * getParent() const
Definition: Instruction.h:66