blob: 7d93c50373ed8ebb59dd27cdc609873882d55121 [file] [log] [blame]
Chris Lattnere67dbc22004-05-23 21:19:55 +00001//===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner1467f642002-04-28 00:47:11 +00009//
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
Chris Lattner1b09a9a2002-08-30 22:53:30 +000012// using an existing value numbering implementation to identify the common
13// subexpressions, eliminating them when possible.
Chris Lattner1467f642002-04-28 00:47:11 +000014//
Chris Lattner1467f642002-04-28 00:47:11 +000015//===----------------------------------------------------------------------===//
16
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
Chris Lattner69c49002004-04-10 21:11:11 +000018#include "llvm/BasicBlock.h"
19#include "llvm/Constant.h"
20#include "llvm/Instructions.h"
Chris Lattner1b09a9a2002-08-30 22:53:30 +000021#include "llvm/Type.h"
Chris Lattner1467f642002-04-28 00:47:11 +000022#include "llvm/Analysis/Dominators.h"
Chris Lattnerb2a31092002-08-30 20:22:29 +000023#include "llvm/Analysis/ValueNumbering.h"
Chris Lattner69c49002004-04-10 21:11:11 +000024#include "llvm/Transforms/Utils/Local.h"
25#include "Support/DepthFirstIterator.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000026#include "Support/Statistic.h"
Chris Lattner1467f642002-04-28 00:47:11 +000027#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000028using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000029
Chris Lattner1467f642002-04-28 00:47:11 +000030namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000031 Statistic<> NumInstRemoved("gcse", "Number of instructions removed");
32 Statistic<> NumLoadRemoved("gcse", "Number of loads removed");
Chris Lattnercd832822004-03-15 05:46:59 +000033 Statistic<> NumCallRemoved("gcse", "Number of calls removed");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000034 Statistic<> NumNonInsts ("gcse", "Number of instructions removed due "
Chris Lattnerb2a31092002-08-30 20:22:29 +000035 "to non-instruction values");
Chris Lattnere67dbc22004-05-23 21:19:55 +000036 Statistic<> NumArgsRepl ("gcse", "Number of function arguments replaced "
37 "with constant values");
Chris Lattnerb2a31092002-08-30 20:22:29 +000038
Chris Lattner69c49002004-04-10 21:11:11 +000039 struct GCSE : public FunctionPass {
Chris Lattner113f4f42002-06-25 16:13:24 +000040 virtual bool runOnFunction(Function &F);
Chris Lattner1467f642002-04-28 00:47:11 +000041
Chris Lattner1467f642002-04-28 00:47:11 +000042 private:
Chris Lattner69c49002004-04-10 21:11:11 +000043 void ReplaceInstructionWith(Instruction *I, Value *V);
Chris Lattnerd38ddb12002-05-14 05:02:40 +000044
Chris Lattner1467f642002-04-28 00:47:11 +000045 // This transformation requires dominator and immediate dominator info
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000047 AU.setPreservesCFG();
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000048 AU.addRequired<DominatorSet>();
Chris Lattner69c49002004-04-10 21:11:11 +000049 AU.addRequired<DominatorTree>();
Chris Lattnerb2a31092002-08-30 20:22:29 +000050 AU.addRequired<ValueNumbering>();
Chris Lattner1467f642002-04-28 00:47:11 +000051 }
52 };
Chris Lattnerb28b6802002-07-23 18:06:35 +000053
Chris Lattnerc8b70922002-07-26 21:12:46 +000054 RegisterOpt<GCSE> X("gcse", "Global Common Subexpression Elimination");
Chris Lattner1467f642002-04-28 00:47:11 +000055}
56
57// createGCSEPass - The public interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +000058FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
Chris Lattner1467f642002-04-28 00:47:11 +000059
Chris Lattner1467f642002-04-28 00:47:11 +000060// GCSE::runOnFunction - This is the main transformation entry point for a
61// function.
62//
Chris Lattner113f4f42002-06-25 16:13:24 +000063bool GCSE::runOnFunction(Function &F) {
Chris Lattner1467f642002-04-28 00:47:11 +000064 bool Changed = false;
65
Chris Lattner879cb972002-08-22 18:24:48 +000066 // Get pointers to the analysis results that we will be using...
Chris Lattner69c49002004-04-10 21:11:11 +000067 DominatorSet &DS = getAnalysis<DominatorSet>();
68 ValueNumbering &VN = getAnalysis<ValueNumbering>();
69 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner1467f642002-04-28 00:47:11 +000070
Chris Lattner69c49002004-04-10 21:11:11 +000071 std::vector<Value*> EqualValues;
Chris Lattner1467f642002-04-28 00:47:11 +000072
Chris Lattnere67dbc22004-05-23 21:19:55 +000073 // 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]);
84 ++NumArgsRepl;
85 Changed = true;
86 break;
87 }
88 EqualValues.clear();
89 }
90 }
91
Chris Lattner69c49002004-04-10 21:11:11 +000092 // 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();
Chris Lattner1467f642002-04-28 00:47:11 +000097
Chris Lattner69c49002004-04-10 21:11:11 +000098 // Remember which instructions we've seen in this basic block as we scan.
99 std::set<Instruction*> BlockInsts;
Chris Lattnerb2a31092002-08-30 20:22:29 +0000100
Chris Lattner69c49002004-04-10 21:11:11 +0000101 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
102 Instruction *Inst = I++;
103
104 // If this instruction computes a value, try to fold together common
105 // instructions that compute it.
106 //
107 if (Inst->getType() != Type::VoidTy) {
108 VN.getEqualNumberNodes(Inst, EqualValues);
109
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())
114 I = BB->end();
115 else {
116 I = Inst; --I;
117 }
118
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
125
126 // Change all users of Inst to use the replacement and remove it
127 // from the program.
128 ReplaceInstructionWith(Inst, EqualValues[i]);
129 Inst = 0;
130 EqualValues.clear(); // don't enter the next loop
131 break;
132 }
133
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);
142 else
143 Dominates = DS.dominates(OtherI->getParent(), BB);
144
145 if (Dominates) {
146 // Okay, we found an instruction with the same value as this one
147 // and that dominates this one. Replace this instruction with the
148 // specified one.
149 ReplaceInstructionWith(Inst, OtherI);
150 Inst = 0;
151 break;
152 }
153 }
154
155 EqualValues.clear();
156
157 if (Inst) {
158 I = Inst; ++I; // Deleted no instructions
159 } else if (I == BB->end()) { // Deleted first instruction
160 I = BB->begin();
161 } else { // Deleted inst in middle of block.
162 ++I;
163 }
164 }
165
166 if (Inst)
167 BlockInsts.insert(Inst);
168 }
Chris Lattnerb2a31092002-08-30 20:22:29 +0000169 }
Chris Lattner1467f642002-04-28 00:47:11 +0000170 }
Chris Lattnerd38ddb12002-05-14 05:02:40 +0000171
Chris Lattner1467f642002-04-28 00:47:11 +0000172 // When the worklist is empty, return whether or not we changed anything...
173 return Changed;
174}
175
Chris Lattnerb2a31092002-08-30 20:22:29 +0000176
Chris Lattner69c49002004-04-10 21:11:11 +0000177void 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
Chris Lattnerb2a31092002-08-30 20:22:29 +0000183
Chris Lattnerf16fe722004-04-10 22:33:34 +0000184 // Update value numbering
Chris Lattnere67dbc22004-05-23 21:19:55 +0000185 getAnalysis<ValueNumbering>().deleteValue(I);
Chris Lattnerf16fe722004-04-10 22:33:34 +0000186
Chris Lattner69c49002004-04-10 21:11:11 +0000187 // If we are not replacing the instruction with a constant, we cannot do
188 // anything special.
189 if (!isa<Constant>(V)) {
190 I->replaceAllUsesWith(V);
Chris Lattner494a6852004-04-12 05:15:13 +0000191
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());
197 }
Chris Lattnerf16fe722004-04-10 22:33:34 +0000198
Chris Lattner69c49002004-04-10 21:11:11 +0000199 // Erase the instruction from the program.
200 I->getParent()->getInstList().erase(I);
201 return;
202 }
Chris Lattnerb2a31092002-08-30 20:22:29 +0000203
Chris Lattner69c49002004-04-10 21:11:11 +0000204 Constant *C = cast<Constant>(V);
205 std::vector<User*> Users(I->use_begin(), I->use_end());
206
207 // Perform the replacement.
208 I->replaceAllUsesWith(C);
209
Chris Lattner494a6852004-04-12 05:15:13 +0000210 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());
215 }
216
Chris Lattner69c49002004-04-10 21:11:11 +0000217 // Erase the instruction from the program.
218 I->getParent()->getInstList().erase(I);
Chris Lattnerb2a31092002-08-30 20:22:29 +0000219
Chris Lattner69c49002004-04-10 21:11:11 +0000220 // Check each user to see if we can constant fold it.
221 while (!Users.empty()) {
222 Instruction *U = cast<Instruction>(Users.back());
223 Users.pop_back();
Chris Lattnerb2a31092002-08-30 20:22:29 +0000224
Chris Lattner69c49002004-04-10 21:11:11 +0000225 if (Constant *C = ConstantFoldInstruction(U)) {
226 ReplaceInstructionWith(U, C);
227
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()) {
232 Users.erase(It);
233 It = std::find(Users.begin(), Users.end(), U);
Chris Lattnerb2a31092002-08-30 20:22:29 +0000234 }
Chris Lattner1467f642002-04-28 00:47:11 +0000235 }
Chris Lattner1467f642002-04-28 00:47:11 +0000236 }
Chris Lattnerd38ddb12002-05-14 05:02:40 +0000237}