ObjCARCAPElim.cpp 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. //===- ObjCARCAPElim.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. ///
  10. /// This file defines ObjC ARC optimizations. ARC stands for Automatic
  11. /// Reference Counting and is a system for managing reference counts for objects
  12. /// in Objective C.
  13. ///
  14. /// This specific file implements optimizations which remove extraneous
  15. /// autorelease pools.
  16. ///
  17. /// WARNING: This file knows about certain library functions. It recognizes them
  18. /// by name, and hardwires knowledge of their semantics.
  19. ///
  20. /// WARNING: This file knows about how certain Objective-C library functions are
  21. /// used. Naive LLVM IR transformations which would otherwise be
  22. /// behavior-preserving may break these assumptions.
  23. ///
  24. //===----------------------------------------------------------------------===//
  25. #include "ObjCARC.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/PassManager.h"
  29. #include "llvm/InitializePasses.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "llvm/Transforms/ObjCARC.h"
  33. using namespace llvm;
  34. using namespace llvm::objcarc;
  35. #define DEBUG_TYPE "objc-arc-ap-elim"
  36. namespace {
  37. /// Interprocedurally determine if calls made by the given call site can
  38. /// possibly produce autoreleases.
  39. bool MayAutorelease(const CallBase &CB, unsigned Depth = 0) {
  40. if (const Function *Callee = CB.getCalledFunction()) {
  41. if (!Callee->hasExactDefinition())
  42. return true;
  43. for (const BasicBlock &BB : *Callee) {
  44. for (const Instruction &I : BB)
  45. if (const CallBase *JCB = dyn_cast<CallBase>(&I))
  46. // This recursion depth limit is arbitrary. It's just great
  47. // enough to cover known interesting testcases.
  48. if (Depth < 3 && !JCB->onlyReadsMemory() &&
  49. MayAutorelease(*JCB, Depth + 1))
  50. return true;
  51. }
  52. return false;
  53. }
  54. return true;
  55. }
  56. bool OptimizeBB(BasicBlock *BB) {
  57. bool Changed = false;
  58. Instruction *Push = nullptr;
  59. for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
  60. switch (GetBasicARCInstKind(&Inst)) {
  61. case ARCInstKind::AutoreleasepoolPush:
  62. Push = &Inst;
  63. break;
  64. case ARCInstKind::AutoreleasepoolPop:
  65. // If this pop matches a push and nothing in between can autorelease,
  66. // zap the pair.
  67. if (Push && cast<CallInst>(&Inst)->getArgOperand(0) == Push) {
  68. Changed = true;
  69. LLVM_DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
  70. "autorelease pair:\n"
  71. " Pop: "
  72. << Inst << "\n"
  73. << " Push: " << *Push
  74. << "\n");
  75. Inst.eraseFromParent();
  76. Push->eraseFromParent();
  77. }
  78. Push = nullptr;
  79. break;
  80. case ARCInstKind::CallOrUser:
  81. if (MayAutorelease(cast<CallBase>(Inst)))
  82. Push = nullptr;
  83. break;
  84. default:
  85. break;
  86. }
  87. }
  88. return Changed;
  89. }
  90. bool runImpl(Module &M) {
  91. if (!EnableARCOpts)
  92. return false;
  93. // If nothing in the Module uses ARC, don't do anything.
  94. if (!ModuleHasARC(M))
  95. return false;
  96. // Find the llvm.global_ctors variable, as the first step in
  97. // identifying the global constructors. In theory, unnecessary autorelease
  98. // pools could occur anywhere, but in practice it's pretty rare. Global
  99. // ctors are a place where autorelease pools get inserted automatically,
  100. // so it's pretty common for them to be unnecessary, and it's pretty
  101. // profitable to eliminate them.
  102. GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
  103. if (!GV)
  104. return false;
  105. assert(GV->hasDefinitiveInitializer() &&
  106. "llvm.global_ctors is uncooperative!");
  107. bool Changed = false;
  108. // Dig the constructor functions out of GV's initializer.
  109. ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
  110. for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
  111. OI != OE; ++OI) {
  112. Value *Op = *OI;
  113. // llvm.global_ctors is an array of three-field structs where the second
  114. // members are constructor functions.
  115. Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
  116. // If the user used a constructor function with the wrong signature and
  117. // it got bitcasted or whatever, look the other way.
  118. if (!F)
  119. continue;
  120. // Only look at function definitions.
  121. if (F->isDeclaration())
  122. continue;
  123. // Only look at functions with one basic block.
  124. if (std::next(F->begin()) != F->end())
  125. continue;
  126. // Ok, a single-block constructor function definition. Try to optimize it.
  127. Changed |= OptimizeBB(&F->front());
  128. }
  129. return Changed;
  130. }
  131. /// Autorelease pool elimination.
  132. class ObjCARCAPElim : public ModulePass {
  133. void getAnalysisUsage(AnalysisUsage &AU) const override;
  134. bool runOnModule(Module &M) override;
  135. public:
  136. static char ID;
  137. ObjCARCAPElim() : ModulePass(ID) {
  138. initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
  139. }
  140. };
  141. } // namespace
  142. char ObjCARCAPElim::ID = 0;
  143. INITIALIZE_PASS(ObjCARCAPElim, "objc-arc-apelim",
  144. "ObjC ARC autorelease pool elimination", false, false)
  145. Pass *llvm::createObjCARCAPElimPass() { return new ObjCARCAPElim(); }
  146. void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
  147. AU.setPreservesCFG();
  148. }
  149. bool ObjCARCAPElim::runOnModule(Module &M) {
  150. if (skipModule(M))
  151. return false;
  152. return runImpl(M);
  153. }
  154. PreservedAnalyses ObjCARCAPElimPass::run(Module &M, ModuleAnalysisManager &AM) {
  155. if (!runImpl(M))
  156. return PreservedAnalyses::all();
  157. PreservedAnalyses PA;
  158. PA.preserveSet<CFGAnalyses>();
  159. return PA;
  160. }