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,
444  SmallPtrSetImpl<const BasicBlock *> &Visited, bool &TailOkForStoreStrongs,
445  const DenseMap<BasicBlock *, ColorVector> &BlockColors) {
446  // Only these library routines return their argument. In particular,
447  // objc_retainBlock does not necessarily return its argument.
448  ARCInstKind Class = GetBasicARCInstKind(Inst);
449  switch (Class) {
452  return false;
455  return contractAutorelease(F, Inst, Class, DependingInsts, Visited);
456  case ARCInstKind::Retain:
457  // Attempt to convert retains to retainrvs if they are next to function
458  // calls.
459  if (!optimizeRetainCall(F, Inst))
460  return false;
461  // If we succeed in our optimization, fall through.
464  case ARCInstKind::ClaimRV: {
465  // If we're compiling for a target which needs a special inline-asm
466  // marker to do the return value optimization, insert it now.
467  if (!RVInstMarker)
468  return false;
469  BasicBlock::iterator BBI = Inst->getIterator();
470  BasicBlock *InstParent = Inst->getParent();
471 
472  // Step up to see if the call immediately precedes the RV call.
473  // If it's an invoke, we have to cross a block boundary. And we have
474  // to carefully dodge no-op instructions.
475  do {
476  if (BBI == InstParent->begin()) {
477  BasicBlock *Pred = InstParent->getSinglePredecessor();
478  if (!Pred)
479  goto decline_rv_optimization;
480  BBI = Pred->getTerminator()->getIterator();
481  break;
482  }
483  --BBI;
484  } while (IsNoopInstruction(&*BBI));
485 
486  if (&*BBI == GetArgRCIdentityRoot(Inst)) {
487  LLVM_DEBUG(dbgs() << "Adding inline asm marker for the return value "
488  "optimization.\n");
489  Changed = true;
490  InlineAsm *IA =
492  /*isVarArg=*/false),
493  RVInstMarker->getString(),
494  /*Constraints=*/"", /*hasSideEffects=*/true);
495 
496  createCallInst(IA, None, "", Inst, BlockColors);
497  }
498  decline_rv_optimization:
499  return false;
500  }
501  case ARCInstKind::InitWeak: {
502  // objc_initWeak(p, null) => *p = null
503  CallInst *CI = cast<CallInst>(Inst);
504  if (IsNullOrUndef(CI->getArgOperand(1))) {
505  Value *Null = ConstantPointerNull::get(cast<PointerType>(CI->getType()));
506  Changed = true;
507  new StoreInst(Null, CI->getArgOperand(0), CI);
508 
509  LLVM_DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
510  << " New = " << *Null << "\n");
511 
512  CI->replaceAllUsesWith(Null);
513  CI->eraseFromParent();
514  }
515  return true;
516  }
518  // Try to form an objc store strong from our release. If we fail, there is
519  // nothing further to do below, so continue.
520  tryToContractReleaseIntoStoreStrong(Inst, Iter, BlockColors);
521  return true;
522  case ARCInstKind::User:
523  // Be conservative if the function has any alloca instructions.
524  // Technically we only care about escaping alloca instructions,
525  // but this is sufficient to handle some interesting cases.
526  if (isa<AllocaInst>(Inst))
527  TailOkForStoreStrongs = false;
528  return true;
530  // Remove calls to @llvm.objc.clang.arc.use(...).
531  Inst->eraseFromParent();
532  return true;
533  default:
534  return true;
535  }
536 }
537 
538 //===----------------------------------------------------------------------===//
539 // Top Level Driver
540 //===----------------------------------------------------------------------===//
541 
543  if (!EnableARCOpts)
544  return false;
545 
546  // If nothing in the Module uses ARC, don't do anything.
547  if (!Run)
548  return false;
549 
550  Changed = false;
551  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
552  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
553 
554  PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
555 
557  if (F.hasPersonalityFn() &&
559  BlockColors = colorEHFunclets(F);
560 
561  LLVM_DEBUG(llvm::dbgs() << "**** ObjCARC Contract ****\n");
562 
563  // Track whether it's ok to mark objc_storeStrong calls with the "tail"
564  // keyword. Be conservative if the function has variadic arguments.
565  // It seems that functions which "return twice" are also unsafe for the
566  // "tail" argument, because they are setjmp, which could need to
567  // return to an earlier stack state.
568  bool TailOkForStoreStrongs =
570 
571  // For ObjC library calls which return their argument, replace uses of the
572  // argument with uses of the call return value, if it dominates the use. This
573  // reduces register pressure.
574  SmallPtrSet<Instruction *, 4> DependingInstructions;
576  for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E;) {
577  Instruction *Inst = &*I++;
578 
579  LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
580 
581  // First try to peephole Inst. If there is nothing further we can do in
582  // terms of undoing objc-arc-expand, process the next inst.
583  if (tryToPeepholeInstruction(F, Inst, I, DependingInstructions, Visited,
584  TailOkForStoreStrongs, BlockColors))
585  continue;
586 
587  // Otherwise, try to undo objc-arc-expand.
588 
589  // Don't use GetArgRCIdentityRoot because we don't want to look through bitcasts
590  // and such; to do the replacement, the argument must have type i8*.
591 
592  // Function for replacing uses of Arg dominated by Inst.
593  auto ReplaceArgUses = [Inst, this](Value *Arg) {
594  // If we're compiling bugpointed code, don't get in trouble.
595  if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
596  return;
597 
598  // Look through the uses of the pointer.
599  for (Value::use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
600  UI != UE; ) {
601  // Increment UI now, because we may unlink its element.
602  Use &U = *UI++;
603  unsigned OperandNo = U.getOperandNo();
604 
605  // If the call's return value dominates a use of the call's argument
606  // value, rewrite the use to use the return value. We check for
607  // reachability here because an unreachable call is considered to
608  // trivially dominate itself, which would lead us to rewriting its
609  // argument in terms of its return value, which would lead to
610  // infinite loops in GetArgRCIdentityRoot.
611  if (!DT->isReachableFromEntry(U) || !DT->dominates(Inst, U))
612  continue;
613 
614  Changed = true;
615  Instruction *Replacement = Inst;
616  Type *UseTy = U.get()->getType();
617  if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
618  // For PHI nodes, insert the bitcast in the predecessor block.
619  unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
620  BasicBlock *IncomingBB = PHI->getIncomingBlock(ValNo);
621  if (Replacement->getType() != UseTy) {
622  // A catchswitch is both a pad and a terminator, meaning a basic
623  // block with a catchswitch has no insertion point. Keep going up
624  // the dominator tree until we find a non-catchswitch.
625  BasicBlock *InsertBB = IncomingBB;
626  while (isa<CatchSwitchInst>(InsertBB->getFirstNonPHI())) {
627  InsertBB = DT->getNode(InsertBB)->getIDom()->getBlock();
628  }
629 
630  assert(DT->dominates(Inst, &InsertBB->back()) &&
631  "Invalid insertion point for bitcast");
632  Replacement =
633  new BitCastInst(Replacement, UseTy, "", &InsertBB->back());
634  }
635 
636  // While we're here, rewrite all edges for this PHI, rather
637  // than just one use at a time, to minimize the number of
638  // bitcasts we emit.
639  for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
640  if (PHI->getIncomingBlock(i) == IncomingBB) {
641  // Keep the UI iterator valid.
642  if (UI != UE &&
643  &PHI->getOperandUse(
645  ++UI;
646  PHI->setIncomingValue(i, Replacement);
647  }
648  } else {
649  if (Replacement->getType() != UseTy)
650  Replacement = new BitCastInst(Replacement, UseTy, "",
651  cast<Instruction>(U.getUser()));
652  U.set(Replacement);
653  }
654  }
655  };
656 
657 
658  Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
659  Value *OrigArg = Arg;
660 
661  // TODO: Change this to a do-while.
662  for (;;) {
663  ReplaceArgUses(Arg);
664 
665  // If Arg is a no-op casted pointer, strip one level of casts and iterate.
666  if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
667  Arg = BI->getOperand(0);
668  else if (isa<GEPOperator>(Arg) &&
669  cast<GEPOperator>(Arg)->hasAllZeroIndices())
670  Arg = cast<GEPOperator>(Arg)->getPointerOperand();
671  else if (isa<GlobalAlias>(Arg) &&
672  !cast<GlobalAlias>(Arg)->isInterposable())
673  Arg = cast<GlobalAlias>(Arg)->getAliasee();
674  else {
675  // If Arg is a PHI node, get PHIs that are equivalent to it and replace
676  // their uses.
677  if (PHINode *PN = dyn_cast<PHINode>(Arg)) {
678  SmallVector<Value *, 1> PHIList;
679  getEquivalentPHIs(*PN, PHIList);
680  for (Value *PHI : PHIList)
681  ReplaceArgUses(PHI);
682  }
683  break;
684  }
685  }
686 
687  // Replace bitcast users of Arg that are dominated by Inst.
688  SmallVector<BitCastInst *, 2> BitCastUsers;
689 
690  // Add all bitcast users of the function argument first.
691  for (User *U : OrigArg->users())
692  if (auto *BC = dyn_cast<BitCastInst>(U))
693  BitCastUsers.push_back(BC);
694 
695  // Replace the bitcasts with the call return. Iterate until list is empty.
696  while (!BitCastUsers.empty()) {
697  auto *BC = BitCastUsers.pop_back_val();
698  for (User *U : BC->users())
699  if (auto *B = dyn_cast<BitCastInst>(U))
700  BitCastUsers.push_back(B);
701 
702  ReplaceArgUses(BC);
703  }
704  }
705 
706  // If this function has no escaping allocas or suspicious vararg usage,
707  // objc_storeStrong calls can be marked with the "tail" keyword.
708  if (TailOkForStoreStrongs)
709  for (CallInst *CI : StoreStrongCalls)
710  CI->setTailCall();
711  StoreStrongCalls.clear();
712 
713  return Changed;
714 }
715 
716 //===----------------------------------------------------------------------===//
717 // Misc Pass Manager
718 //===----------------------------------------------------------------------===//
719 
720 char ObjCARCContract::ID = 0;
721 INITIALIZE_PASS_BEGIN(ObjCARCContract, "objc-arc-contract",
722  "ObjC ARC contraction", false, false)
725 INITIALIZE_PASS_END(ObjCARCContract, "objc-arc-contract",
726  "ObjC ARC contraction", false, false)
727 
728 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
729  AU.addRequired<AAResultsWrapperPass>();
730  AU.addRequired<DominatorTreeWrapperPass>();
731  AU.setPreservesCFG();
732 }
733 
734 Pass *llvm::createObjCARCContractPass() { return new ObjCARCContract(); }
735 
736 bool ObjCARCContract::doInitialization(Module &M) {
737  // If nothing in the Module uses ARC, don't do anything.
738  Run = ModuleHasARC(M);
739  if (!Run)
740  return false;
741 
742  EP.init(&M);
743 
744  // Initialize RVInstMarker.
745  const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
746  RVInstMarker = dyn_cast_or_null<MDString>(M.getModuleFlag(MarkerKey));
747 
748  return false;
749 }
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
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:645
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:65
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:709
unsigned second
STATISTIC(NumFunctions, "Total number of functions")
F(f)
could call objc_release
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
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.
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:704
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:318
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1410
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:64
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition: Module.cpp:310
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:841
ARCInstKind
Equivalence classes of instructions in the ARC Model.
objc_unsafeClaimAutoreleasedReturnValue
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:374
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:321
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
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:332
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...
#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