xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/ObjCARC/ObjCARCAPElim.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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/InitializePasses.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 using namespace llvm;
34 using namespace llvm::objcarc;
35 
36 #define DEBUG_TYPE "objc-arc-ap-elim"
37 
38 namespace {
39   /// 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(const CallBase &CB, unsigned Depth = 0);
45     static bool OptimizeBB(BasicBlock *BB);
46 
47   public:
48     static char ID;
49     ObjCARCAPElim() : ModulePass(ID) {
50       initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
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 
61 Pass *llvm::createObjCARCAPElimPass() {
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(const CallBase &CB, unsigned Depth) {
72   if (const Function *Callee = CB.getCalledFunction()) {
73     if (!Callee->hasExactDefinition())
74       return true;
75     for (const BasicBlock &BB : *Callee) {
76       for (const Instruction &I : BB)
77         if (const CallBase *JCB = dyn_cast<CallBase>(&I))
78           // This recursion depth limit is arbitrary. It's just great
79           // enough to cover known interesting testcases.
80           if (Depth < 3 && !JCB->onlyReadsMemory() &&
81               MayAutorelease(*JCB, 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)) {
97     case ARCInstKind::AutoreleasepoolPush:
98       Push = Inst;
99       break;
100     case ARCInstKind::AutoreleasepoolPop:
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;
116     case ARCInstKind::CallOrUser:
117       if (MayAutorelease(cast<CallBase>(*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 
149   assert(GV->hasDefinitiveInitializer() &&
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 }
178