1 //===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass is designed to be a very quick global transformation that
11 // eliminates global common subexpressions from a function. It does this by
12 // using an existing value numbering implementation to identify the common
13 // subexpressions, eliminating them when possible.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constant.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Type.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Analysis/ValueNumbering.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "Support/DepthFirstIterator.h"
26 #include "Support/Statistic.h"
31 Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
32 Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
33 Statistic<> NumCallRemoved("gcse", "Number of calls removed");
34 Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
35 "to non-instruction values");
36 Statistic<> NumArgsRepl ("gcse", "Number of function arguments replaced "
37 "with constant values");
39 struct GCSE : public FunctionPass {
40 virtual bool runOnFunction(Function &F);
43 void ReplaceInstructionWith(Instruction *I, Value *V);
45 // This transformation requires dominator and immediate dominator info
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequired<DominatorSet>();
49 AU.addRequired<DominatorTree>();
50 AU.addRequired<ValueNumbering>();
54 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
57 // createGCSEPass - The public interface to this file...
58 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
60 // GCSE::runOnFunction - This is the main transformation entry point for a
63 bool GCSE::runOnFunction(Function &F) {
66 // Get pointers to the analysis results that we will be using...
67 DominatorSet &DS = getAnalysis<DominatorSet>();
68 ValueNumbering &VN = getAnalysis<ValueNumbering>();
69 DominatorTree &DT = getAnalysis<DominatorTree>();
71 std::vector<Value*> EqualValues;
73 // Check for value numbers of arguments. If the value numbering
74 // implementation can prove that an incoming argument is a constant or global
75 // value address, substitute it, making the argument dead.
76 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
77 if (!AI->use_empty()) {
78 VN.getEqualNumberNodes(AI, EqualValues);
79 if (!EqualValues.empty()) {
80 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
81 if (isa<Constant>(EqualValues[i]) ||
82 isa<GlobalValue>(EqualValues[i])) {
83 AI->replaceAllUsesWith(EqualValues[i]);
92 // Traverse the CFG of the function in dominator order, so that we see each
93 // instruction after we see its operands.
94 for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()),
95 E = df_end(DT.getRootNode()); DI != E; ++DI) {
96 BasicBlock *BB = DI->getBlock();
98 // Remember which instructions we've seen in this basic block as we scan.
99 std::set<Instruction*> BlockInsts;
101 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
102 Instruction *Inst = I++;
104 // If this instruction computes a value, try to fold together common
105 // instructions that compute it.
107 if (Inst->getType() != Type::VoidTy) {
108 VN.getEqualNumberNodes(Inst, EqualValues);
110 // If this instruction computes a value that is already computed
111 // elsewhere, try to recycle the old value.
112 if (!EqualValues.empty()) {
113 if (Inst == &*BB->begin())
119 // First check to see if we were able to value number this instruction
120 // to a non-instruction value. If so, prefer that value over other
121 // instructions which may compute the same thing.
122 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
123 if (!isa<Instruction>(EqualValues[i])) {
124 ++NumNonInsts; // Keep track of # of insts repl with values
126 // Change all users of Inst to use the replacement and remove it
128 ReplaceInstructionWith(Inst, EqualValues[i]);
130 EqualValues.clear(); // don't enter the next loop
134 // If there were no non-instruction values that this instruction
135 // produces, find a dominating instruction that produces the same
136 // value. If we find one, use it's value instead of ours.
137 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
138 Instruction *OtherI = cast<Instruction>(EqualValues[i]);
139 bool Dominates = false;
140 if (OtherI->getParent() == BB)
141 Dominates = BlockInsts.count(OtherI);
143 Dominates = DS.dominates(OtherI->getParent(), BB);
146 // Okay, we found an instruction with the same value as this one
147 // and that dominates this one. Replace this instruction with the
149 ReplaceInstructionWith(Inst, OtherI);
158 I = Inst; ++I; // Deleted no instructions
159 } else if (I == BB->end()) { // Deleted first instruction
161 } else { // Deleted inst in middle of block.
167 BlockInsts.insert(Inst);
172 // When the worklist is empty, return whether or not we changed anything...
177 void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
178 if (isa<LoadInst>(I))
179 ++NumLoadRemoved; // Keep track of loads eliminated
180 if (isa<CallInst>(I))
181 ++NumCallRemoved; // Keep track of calls eliminated
182 ++NumInstRemoved; // Keep track of number of insts eliminated
184 // Update value numbering
185 getAnalysis<ValueNumbering>().deleteValue(I);
187 // If we are not replacing the instruction with a constant, we cannot do
189 if (!isa<Constant>(V)) {
190 I->replaceAllUsesWith(V);
192 if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
193 // Removing an invoke instruction requires adding a branch to the normal
194 // destination and removing PHI node entries in the exception destination.
195 new BranchInst(II->getNormalDest(), II);
196 II->getUnwindDest()->removePredecessor(II->getParent());
199 // Erase the instruction from the program.
200 I->getParent()->getInstList().erase(I);
204 Constant *C = cast<Constant>(V);
205 std::vector<User*> Users(I->use_begin(), I->use_end());
207 // Perform the replacement.
208 I->replaceAllUsesWith(C);
210 if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
211 // Removing an invoke instruction requires adding a branch to the normal
212 // destination and removing PHI node entries in the exception destination.
213 new BranchInst(II->getNormalDest(), II);
214 II->getUnwindDest()->removePredecessor(II->getParent());
217 // Erase the instruction from the program.
218 I->getParent()->getInstList().erase(I);
220 // Check each user to see if we can constant fold it.
221 while (!Users.empty()) {
222 Instruction *U = cast<Instruction>(Users.back());
225 if (Constant *C = ConstantFoldInstruction(U)) {
226 ReplaceInstructionWith(U, C);
228 // If the instruction used I more than once, it could be on the user list
229 // multiple times. Make sure we don't reprocess it.
230 std::vector<User*>::iterator It = std::find(Users.begin(), Users.end(),U);
231 while (It != Users.end()) {
233 It = std::find(Users.begin(), Users.end(), U);