LLVM  9.0.0svn
ObjCARCAPElim.cpp
Go to the documentation of this file.
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 
26 #include "ObjCARC.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/Support/Debug.h"
31 
32 using namespace llvm;
33 using namespace llvm::objcarc;
34 
35 #define DEBUG_TYPE "objc-arc-ap-elim"
36 
37 namespace {
38  /// Autorelease pool elimination.
39  class ObjCARCAPElim : public ModulePass {
40  void getAnalysisUsage(AnalysisUsage &AU) const override;
41  bool runOnModule(Module &M) override;
42 
43  static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
44  static bool OptimizeBB(BasicBlock *BB);
45 
46  public:
47  static char ID;
48  ObjCARCAPElim() : ModulePass(ID) {
50  }
51  };
52 }
53 
54 char ObjCARCAPElim::ID = 0;
55 INITIALIZE_PASS(ObjCARCAPElim,
56  "objc-arc-apelim",
57  "ObjC ARC autorelease pool elimination",
58  false, false)
59 
61  return new ObjCARCAPElim();
62 }
63 
64 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
65  AU.setPreservesCFG();
66 }
67 
68 /// Interprocedurally determine if calls made by the given call site can
69 /// possibly produce autoreleases.
70 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
71  if (const Function *Callee = CS.getCalledFunction()) {
72  if (!Callee->hasExactDefinition())
73  return true;
74  for (const BasicBlock &BB : *Callee) {
75  for (const Instruction &I : BB)
77  // This recursion depth limit is arbitrary. It's just great
78  // enough to cover known interesting testcases.
79  if (Depth < 3 &&
80  !JCS.onlyReadsMemory() &&
81  MayAutorelease(JCS, Depth + 1))
82  return true;
83  }
84  return false;
85  }
86 
87  return true;
88 }
89 
90 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
91  bool Changed = false;
92 
93  Instruction *Push = nullptr;
94  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
95  Instruction *Inst = &*I++;
96  switch (GetBasicARCInstKind(Inst)) {
98  Push = Inst;
99  break;
101  // If this pop matches a push and nothing in between can autorelease,
102  // zap the pair.
103  if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
104  Changed = true;
105  LLVM_DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
106  "autorelease pair:\n"
107  " Pop: "
108  << *Inst << "\n"
109  << " Push: " << *Push
110  << "\n");
111  Inst->eraseFromParent();
112  Push->eraseFromParent();
113  }
114  Push = nullptr;
115  break;
117  if (MayAutorelease(ImmutableCallSite(Inst)))
118  Push = nullptr;
119  break;
120  default:
121  break;
122  }
123  }
124 
125  return Changed;
126 }
127 
128 bool ObjCARCAPElim::runOnModule(Module &M) {
129  if (!EnableARCOpts)
130  return false;
131 
132  // If nothing in the Module uses ARC, don't do anything.
133  if (!ModuleHasARC(M))
134  return false;
135 
136  if (skipModule(M))
137  return false;
138 
139  // Find the llvm.global_ctors variable, as the first step in
140  // identifying the global constructors. In theory, unnecessary autorelease
141  // pools could occur anywhere, but in practice it's pretty rare. Global
142  // ctors are a place where autorelease pools get inserted automatically,
143  // so it's pretty common for them to be unnecessary, and it's pretty
144  // profitable to eliminate them.
145  GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
146  if (!GV)
147  return false;
148 
150  "llvm.global_ctors is uncooperative!");
151 
152  bool Changed = false;
153 
154  // Dig the constructor functions out of GV's initializer.
155  ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
156  for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
157  OI != OE; ++OI) {
158  Value *Op = *OI;
159  // llvm.global_ctors is an array of three-field structs where the second
160  // members are constructor functions.
161  Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
162  // If the user used a constructor function with the wrong signature and
163  // it got bitcasted or whatever, look the other way.
164  if (!F)
165  continue;
166  // Only look at function definitions.
167  if (F->isDeclaration())
168  continue;
169  // Only look at functions with one basic block.
170  if (std::next(F->begin()) != F->end())
171  continue;
172  // Ok, a single-block constructor function definition. Try to optimize it.
173  Changed |= OptimizeBB(&F->front());
174  }
175 
176  return Changed;
177 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:80
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
could call objc_release and/or "use" pointers
void initializeObjCARCAPElimPass(PassRegistry &)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
iterator end()
Definition: Function.h:674
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:390
F(f)
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:111
op_iterator op_begin()
Definition: User.h:229
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:268
A Use represents the edge between a Value definition and its users.
Definition: Use.h:55
This file defines common definitions/declarations used by the ObjC ARC Optimizer. ...
Pass * createObjCARCAPElimPass()
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
iterator begin()
Definition: Function.h:672
bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
INITIALIZE_PASS(ObjCARCAPElim, "objc-arc-apelim", "ObjC ARC autorelease pool elimination", false, false) Pass *llvm
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Represent the analysis usage information of a pass.
op_iterator op_end()
Definition: User.h:231
ARCInstKind GetBasicARCInstKind(const Value *V)
Determine which objc runtime call instruction class V belongs to.
Iterator for intrusive lists based on ilist_node.
iterator end()
Definition: BasicBlock.h:270
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:301
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
amdgpu Simplify well known AMD library false FunctionCallee Callee
Establish a view to a call site for examination.
Definition: CallSite.h:897
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
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
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:227
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:679
LLVM Value Representation.
Definition: Value.h:72
#define LLVM_DEBUG(X)
Definition: Debug.h:122