LLVM  6.0.0svn
ObjCARCAPElim.cpp
Go to the documentation of this file.
1 //===- ObjCARCAPElim.cpp - ObjC ARC Optimization --------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
12 /// Reference Counting and is a system for managing reference counts for objects
13 /// in Objective C.
14 ///
15 /// This specific file implements optimizations which remove extraneous
16 /// autorelease pools.
17 ///
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
20 ///
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
24 ///
25 //===----------------------------------------------------------------------===//
26 
27 #include "ObjCARC.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/Support/Debug.h"
32 
33 using namespace llvm;
34 using namespace llvm::objcarc;
35 
36 #define DEBUG_TYPE "objc-arc-ap-elim"
37 
38 namespace {
39  /// \brief Autorelease pool elimination.
40  class ObjCARCAPElim : public ModulePass {
41  void getAnalysisUsage(AnalysisUsage &AU) const override;
42  bool runOnModule(Module &M) override;
43 
44  static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
45  static bool OptimizeBB(BasicBlock *BB);
46 
47  public:
48  static char ID;
49  ObjCARCAPElim() : ModulePass(ID) {
51  }
52  };
53 }
54 
55 char ObjCARCAPElim::ID = 0;
56 INITIALIZE_PASS(ObjCARCAPElim,
57  "objc-arc-apelim",
58  "ObjC ARC autorelease pool elimination",
59  false, false)
60 
62  return new ObjCARCAPElim();
63 }
64 
65 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
66  AU.setPreservesCFG();
67 }
68 
69 /// Interprocedurally determine if calls made by the given call site can
70 /// possibly produce autoreleases.
71 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
72  if (const Function *Callee = CS.getCalledFunction()) {
73  if (!Callee->hasExactDefinition())
74  return true;
75  for (const BasicBlock &BB : *Callee) {
76  for (const Instruction &I : BB)
78  // This recursion depth limit is arbitrary. It's just great
79  // enough to cover known interesting testcases.
80  if (Depth < 3 &&
81  !JCS.onlyReadsMemory() &&
82  MayAutorelease(JCS, Depth + 1))
83  return true;
84  }
85  return false;
86  }
87 
88  return true;
89 }
90 
91 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
92  bool Changed = false;
93 
94  Instruction *Push = nullptr;
95  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
96  Instruction *Inst = &*I++;
97  switch (GetBasicARCInstKind(Inst)) {
99  Push = Inst;
100  break;
102  // If this pop matches a push and nothing in between can autorelease,
103  // zap the pair.
104  if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
105  Changed = true;
106  DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
107  "autorelease pair:\n"
108  " Pop: " << *Inst << "\n"
109  << " Push: " << *Push << "\n");
110  Inst->eraseFromParent();
111  Push->eraseFromParent();
112  }
113  Push = nullptr;
114  break;
116  if (MayAutorelease(ImmutableCallSite(Inst)))
117  Push = nullptr;
118  break;
119  default:
120  break;
121  }
122  }
123 
124  return Changed;
125 }
126 
127 bool ObjCARCAPElim::runOnModule(Module &M) {
128  if (!EnableARCOpts)
129  return false;
130 
131  // If nothing in the Module uses ARC, don't do anything.
132  if (!ModuleHasARC(M))
133  return false;
134 
135  if (skipModule(M))
136  return false;
137 
138  // Find the llvm.global_ctors variable, as the first step in
139  // identifying the global constructors. In theory, unnecessary autorelease
140  // pools could occur anywhere, but in practice it's pretty rare. Global
141  // ctors are a place where autorelease pools get inserted automatically,
142  // so it's pretty common for them to be unnecessary, and it's pretty
143  // profitable to eliminate them.
144  GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
145  if (!GV)
146  return false;
147 
149  "llvm.global_ctors is uncooperative!");
150 
151  bool Changed = false;
152 
153  // Dig the constructor functions out of GV's initializer.
154  ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
155  for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
156  OI != OE; ++OI) {
157  Value *Op = *OI;
158  // llvm.global_ctors is an array of three-field structs where the second
159  // members are constructor functions.
160  Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
161  // If the user used a constructor function with the wrong signature and
162  // it got bitcasted or whatever, look the other way.
163  if (!F)
164  continue;
165  // Only look at function definitions.
166  if (F->isDeclaration())
167  continue;
168  // Only look at functions with one basic block.
169  if (std::next(F->begin()) != F->end())
170  continue;
171  // Ok, a single-block constructor function definition. Try to optimize it.
172  Changed |= OptimizeBB(&F->front());
173  }
174 
175  return Changed;
176 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:69
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.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
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:63
iterator end()
Definition: Function.h:590
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:368
F(f)
op_iterator op_begin()
Definition: User.h:214
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:252
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
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:588
amdgpu Simplify well known AMD library false Value * Callee
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:59
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:216
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:254
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:285
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:405
Establish a view to a call site for examination.
Definition: CallSite.h:713
#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:225
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:323
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:201
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:107
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock & front() const
Definition: Function.h:595
LLVM Value Representation.
Definition: Value.h:73
#define DEBUG(X)
Definition: Debug.h:118