blob: f3025523bcd13136252f4a394fc9d7061538a92c [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
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 Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
Chris Lattner4f031622004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000026#include "llvm/Constants.h"
Chris Lattner57698e22002-03-26 18:01:55 +000027#include "llvm/Function.h"
Chris Lattner49f74522004-01-12 04:29:41 +000028#include "llvm/GlobalVariable.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000031#include "llvm/Type.h"
Chris Lattner6e560792002-04-18 15:13:15 +000032#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000033#include "llvm/Transforms/Utils/Local.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000034#include "llvm/Support/Debug.h"
35#include "llvm/ADT/hash_map"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000038#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000039#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000040using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000041
Chris Lattner4f031622004-11-15 05:03:30 +000042// LatticeVal class - This class represents the different lattice values that an
Chris Lattnerc8e66542002-04-27 06:56:12 +000043// instruction may occupy. It is a simple class with value semantics.
Chris Lattner347389d2001-06-27 23:38:11 +000044//
Chris Lattner7d325382002-04-29 21:26:08 +000045namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000046 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
47
Chris Lattner4f031622004-11-15 05:03:30 +000048class LatticeVal {
Chris Lattner347389d2001-06-27 23:38:11 +000049 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000050 undefined, // This instruction has no known value
51 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000052 overdefined // This instruction has an unknown value
53 } LatticeValue; // The current lattice position
54 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000055public:
Chris Lattner4f031622004-11-15 05:03:30 +000056 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000057
58 // markOverdefined - Return true if this is a new status to be in...
59 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000060 if (LatticeValue != overdefined) {
61 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000062 return true;
63 }
64 return false;
65 }
66
67 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000068 inline bool markConstant(Constant *V) {
69 if (LatticeValue != constant) {
70 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000071 ConstantVal = V;
72 return true;
73 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000074 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000075 }
76 return false;
77 }
78
Chris Lattner3462ae32001-12-03 22:26:30 +000079 inline bool isUndefined() const { return LatticeValue == undefined; }
80 inline bool isConstant() const { return LatticeValue == constant; }
81 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000082
Chris Lattner05fe6842004-01-12 03:57:30 +000083 inline Constant *getConstant() const {
84 assert(isConstant() && "Cannot get the constant of a non-constant!");
85 return ConstantVal;
86 }
Chris Lattner347389d2001-06-27 23:38:11 +000087};
88
Chris Lattner7d325382002-04-29 21:26:08 +000089} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000090
91
92//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +000093//
Chris Lattner074be1f2004-11-15 04:44:20 +000094/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
95/// Constant Propagation.
96///
97class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +000098 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +000099 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000100
Chris Lattnerd79334d2004-07-15 23:36:43 +0000101 // The reason for two worklists is that overdefined is the lowest state
102 // on the lattice, and moving things to overdefined as fast as possible
103 // makes SCCP converge much faster.
104 // By having a separate worklist, we accomplish this because everything
105 // possibly overdefined will become overdefined at the soonest possible
106 // point.
107 std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined
108 // instruction work list
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000109 std::vector<Instruction*> InstWorkList;// The instruction work list
Chris Lattnerd79334d2004-07-15 23:36:43 +0000110
111
Chris Lattner7f74a562002-01-20 22:54:45 +0000112 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000113
Chris Lattner05fe6842004-01-12 03:57:30 +0000114 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
115 /// overdefined, despite the fact that the PHI node is overdefined.
116 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
117
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000118 /// KnownFeasibleEdges - Entries in this set are edges which have already had
119 /// PHI nodes retriggered.
120 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
121 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000122public:
123
Chris Lattner074be1f2004-11-15 04:44:20 +0000124 /// MarkBlockExecutable - This method can be used by clients to mark all of
125 /// the blocks that are known to be intrinsically live in the processed unit.
126 void MarkBlockExecutable(BasicBlock *BB) {
127 DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
128 BBExecutable.insert(BB); // Basic block is executable!
129 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000130 }
131
Chris Lattner074be1f2004-11-15 04:44:20 +0000132 /// Solve - Solve for constants and executable blocks.
133 ///
134 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000135
Chris Lattner074be1f2004-11-15 04:44:20 +0000136 /// getExecutableBlocks - Once we have solved for constants, return the set of
137 /// blocks that is known to be executable.
138 std::set<BasicBlock*> &getExecutableBlocks() {
139 return BBExecutable;
140 }
141
142 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000143 /// LLVM values to LatticeVals.
144 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000145 return ValueState;
146 }
147
Chris Lattner347389d2001-06-27 23:38:11 +0000148private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000149 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner347389d2001-06-27 23:38:11 +0000150 // is not already a constant, add it to the instruction work list so that
151 // the users of the instruction are updated later.
152 //
Chris Lattner4f031622004-11-15 05:03:30 +0000153 inline void markConstant(LatticeVal &IV, Instruction *I, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000154 if (IV.markConstant(C)) {
155 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
Chris Lattnerd66a6e32002-05-07 04:29:32 +0000156 InstWorkList.push_back(I);
Chris Lattner347389d2001-06-27 23:38:11 +0000157 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000158 }
159 inline void markConstant(Instruction *I, Constant *C) {
160 markConstant(ValueState[I], I, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000161 }
162
Chris Lattnerd79334d2004-07-15 23:36:43 +0000163 // markOverdefined - Make a value be marked as "overdefined". If the
164 // value is not already overdefined, add it to the overdefined instruction
165 // work list so that the users of the instruction are updated later.
166
Chris Lattner4f031622004-11-15 05:03:30 +0000167 inline void markOverdefined(LatticeVal &IV, Instruction *I) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000168 if (IV.markOverdefined()) {
169 DEBUG(std::cerr << "markOverdefined: " << *I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000170 // Only instructions go on the work list
171 OverdefinedInstWorkList.push_back(I);
Chris Lattner347389d2001-06-27 23:38:11 +0000172 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000173 }
174 inline void markOverdefined(Instruction *I) {
175 markOverdefined(ValueState[I], I);
Chris Lattner347389d2001-06-27 23:38:11 +0000176 }
177
Chris Lattner4f031622004-11-15 05:03:30 +0000178 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000179 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000180 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000181 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000182 // Instruction object, then use this accessor to get its value from the map.
183 //
Chris Lattner4f031622004-11-15 05:03:30 +0000184 inline LatticeVal &getValueState(Value *V) {
185 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000186 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000187
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000188 if (Constant *CPV = dyn_cast<Constant>(V)) {
189 if (isa<UndefValue>(V)) {
190 // Nothing to do, remain undefined.
191 } else {
192 ValueState[CPV].markConstant(CPV); // Constants are constant
193 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000194 }
Chris Lattner347389d2001-06-27 23:38:11 +0000195 // All others are underdefined by default...
196 return ValueState[V];
197 }
198
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000199 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000200 // work list if it is not already executable...
201 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000202 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
203 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
204 return; // This edge is already known to be executable!
205
206 if (BBExecutable.count(Dest)) {
207 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
208 << " -> " << Dest->getName() << "\n");
209
210 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000211 // feasible that wasn't before. Revisit the PHI nodes in the block
212 // because they have potentially new operands.
Reid Spencer66149462004-09-15 17:06:42 +0000213 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I) {
214 PHINode *PN = cast<PHINode>(I);
Chris Lattner3c982762003-04-25 03:35:10 +0000215 visitPHINode(*PN);
Reid Spencer66149462004-09-15 17:06:42 +0000216 }
Chris Lattnercccc5c72003-04-25 02:50:03 +0000217
218 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000219 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000220 }
Chris Lattner347389d2001-06-27 23:38:11 +0000221 }
222
Chris Lattner074be1f2004-11-15 04:44:20 +0000223 // getFeasibleSuccessors - Return a vector of booleans to indicate which
224 // successors are reachable from a given terminator instruction.
225 //
226 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
227
228 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
229 // block to the 'To' basic block is currently feasible...
230 //
231 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
232
233 // OperandChangedState - This method is invoked on all of the users of an
234 // instruction that was just changed state somehow.... Based on this
235 // information, we need to update the specified user of this instruction.
236 //
237 void OperandChangedState(User *U) {
238 // Only instructions use other variable values!
239 Instruction &I = cast<Instruction>(*U);
240 if (BBExecutable.count(I.getParent())) // Inst is executable?
241 visit(I);
242 }
243
244private:
245 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000246
Chris Lattner6e560792002-04-18 15:13:15 +0000247 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000248 // operand made a transition, or the instruction is newly executable. Change
249 // the value type of I to reflect these changes if appropriate.
250 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000251 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000252
253 // Terminators
Chris Lattner113f4f42002-06-25 16:13:24 +0000254 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
255 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000256
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000257 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000258 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000259 void visitBinaryOperator(Instruction &I);
260 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000261
262 // Instructions that cannot be folded away...
Chris Lattner113f4f42002-06-25 16:13:24 +0000263 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattner49f74522004-01-12 04:29:41 +0000264 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000265 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000266 void visitCallInst (CallInst &I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000267 void visitInvokeInst (TerminatorInst &I) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000268 if (I.getType() != Type::VoidTy) markOverdefined(&I);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000269 visitTerminatorInst(I);
270 }
Chris Lattner9c58cf62003-09-08 18:54:55 +0000271 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000272 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000273 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000274 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
275 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000276 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000277
Chris Lattner113f4f42002-06-25 16:13:24 +0000278 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000279 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000280 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000281 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000282 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000283};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000284
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000285// getFeasibleSuccessors - Return a vector of booleans to indicate which
286// successors are reachable from a given terminator instruction.
287//
Chris Lattner074be1f2004-11-15 04:44:20 +0000288void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
289 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000290 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000291 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000292 if (BI->isUnconditional()) {
293 Succs[0] = true;
294 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000295 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000296 if (BCValue.isOverdefined() ||
297 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
298 // Overdefined condition variables, and branches on unfoldable constant
299 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000300 Succs[0] = Succs[1] = true;
301 } else if (BCValue.isConstant()) {
302 // Constant condition variables mean the branch can only go a single way
303 Succs[BCValue.getConstant() == ConstantBool::False] = true;
304 }
305 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000306 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000307 // Invoke instructions successors are always executable.
308 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000309 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000310 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000311 if (SCValue.isOverdefined() || // Overdefined condition?
312 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000313 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000314 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000315 } else if (SCValue.isConstant()) {
316 Constant *CPV = SCValue.getConstant();
317 // Make sure to skip the "default value" which isn't a value
318 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
319 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
320 Succs[i] = true;
321 return;
322 }
323 }
324
325 // Constant value not equal to any of the branches... must execute
326 // default branch then...
327 Succs[0] = true;
328 }
329 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000330 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000331 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000332 }
333}
334
335
Chris Lattner13b52e72002-05-02 21:18:01 +0000336// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
337// block to the 'To' basic block is currently feasible...
338//
Chris Lattner074be1f2004-11-15 04:44:20 +0000339bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000340 assert(BBExecutable.count(To) && "Dest should always be alive!");
341
342 // Make sure the source basic block is executable!!
343 if (!BBExecutable.count(From)) return false;
344
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000345 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000346 TerminatorInst *TI = From->getTerminator();
347 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
348 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000349 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000350 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000351 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000352 if (BCValue.isOverdefined()) {
353 // Overdefined condition variables mean the branch could go either way.
354 return true;
355 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000356 // Not branching on an evaluatable constant?
357 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
358
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000359 // Constant condition variables mean the branch can only go a single way
360 return BI->getSuccessor(BCValue.getConstant() ==
361 ConstantBool::False) == To;
362 }
363 return false;
364 }
365 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
366 // Invoke instructions successors are always executable.
367 return true;
368 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000369 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000370 if (SCValue.isOverdefined()) { // Overdefined condition?
371 // All destinations are executable!
372 return true;
373 } else if (SCValue.isConstant()) {
374 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000375 if (!isa<ConstantInt>(CPV))
376 return true; // not a foldable constant?
377
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000378 // Make sure to skip the "default value" which isn't a value
379 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
380 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
381 return SI->getSuccessor(i) == To;
382
383 // Constant value not equal to any of the branches... must execute
384 // default branch then...
385 return SI->getDefaultDest() == To;
386 }
387 return false;
388 } else {
389 std::cerr << "Unknown terminator instruction: " << *TI;
390 abort();
391 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000392}
Chris Lattner347389d2001-06-27 23:38:11 +0000393
Chris Lattner6e560792002-04-18 15:13:15 +0000394// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000395// operand made a transition, or the instruction is newly executable. Change
396// the value type of I to reflect these changes if appropriate. This method
397// makes sure to do the following actions:
398//
399// 1. If a phi node merges two constants in, and has conflicting value coming
400// from different branches, or if the PHI node merges in an overdefined
401// value, then the PHI node becomes overdefined.
402// 2. If a phi node merges only constants in, and they all agree on value, the
403// PHI node becomes a constant value equal to that.
404// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
405// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
406// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
407// 6. If a conditional branch has a value that is constant, make the selected
408// destination executable
409// 7. If a conditional branch has a value that is overdefined, make all
410// successors executable.
411//
Chris Lattner074be1f2004-11-15 04:44:20 +0000412void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000413 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000414 if (PNIV.isOverdefined()) {
415 // There may be instructions using this PHI node that are not overdefined
416 // themselves. If so, make sure that they know that the PHI node operand
417 // changed.
418 std::multimap<PHINode*, Instruction*>::iterator I, E;
419 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
420 if (I != E) {
421 std::vector<Instruction*> Users;
422 Users.reserve(std::distance(I, E));
423 for (; I != E; ++I) Users.push_back(I->second);
424 while (!Users.empty()) {
425 visit(Users.back());
426 Users.pop_back();
427 }
428 }
429 return; // Quick exit
430 }
Chris Lattner347389d2001-06-27 23:38:11 +0000431
Chris Lattner7a7b1142004-03-16 19:49:59 +0000432 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
433 // and slow us down a lot. Just mark them overdefined.
434 if (PN.getNumIncomingValues() > 64) {
435 markOverdefined(PNIV, &PN);
436 return;
437 }
438
Chris Lattner6e560792002-04-18 15:13:15 +0000439 // Look at all of the executable operands of the PHI node. If any of them
440 // are overdefined, the PHI becomes overdefined as well. If they are all
441 // constant, and they agree with each other, the PHI becomes the identical
442 // constant. If they are constant and don't agree, the PHI is overdefined.
443 // If there are no executable operands, the PHI remains undefined.
444 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000445 Constant *OperandVal = 0;
446 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000447 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000448 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000449
Chris Lattner113f4f42002-06-25 16:13:24 +0000450 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000451 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000452 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000453 return;
454 }
455
Chris Lattnercccc5c72003-04-25 02:50:03 +0000456 if (OperandVal == 0) { // Grab the first value...
457 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000458 } else { // Another value is being merged in!
459 // There is already a reachable operand. If we conflict with it,
460 // then the PHI node becomes overdefined. If we agree with it, we
461 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000462
Chris Lattner6e560792002-04-18 15:13:15 +0000463 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000464 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000465 // Yes there is. This means the PHI node is not constant.
466 // You must be overdefined poor PHI.
467 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000468 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000469 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000470 }
Chris Lattner347389d2001-06-27 23:38:11 +0000471 }
472 }
Chris Lattner347389d2001-06-27 23:38:11 +0000473 }
474
Chris Lattner6e560792002-04-18 15:13:15 +0000475 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000476 // arguments that agree with each other(and OperandVal is the constant) or
477 // OperandVal is null because there are no defined incoming arguments. If
478 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000479 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000480 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000481 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000482}
483
Chris Lattner074be1f2004-11-15 04:44:20 +0000484void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000485 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000486 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000487
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000488 BasicBlock *BB = TI.getParent();
489
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000490 // Mark all feasible successors executable...
491 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000492 if (SuccFeasible[i])
493 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000494}
495
Chris Lattner074be1f2004-11-15 04:44:20 +0000496void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000497 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000498 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000499 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000500 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000501 else if (VState.isConstant()) // Propagate constant value
502 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000503}
504
Chris Lattner074be1f2004-11-15 04:44:20 +0000505void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000506 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner59db22d2004-03-12 05:52:44 +0000507 if (CondValue.isOverdefined())
508 markOverdefined(&I);
509 else if (CondValue.isConstant()) {
510 if (CondValue.getConstant() == ConstantBool::True) {
Chris Lattner4f031622004-11-15 05:03:30 +0000511 LatticeVal &Val = getValueState(I.getTrueValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000512 if (Val.isOverdefined())
513 markOverdefined(&I);
514 else if (Val.isConstant())
515 markConstant(&I, Val.getConstant());
516 } else if (CondValue.getConstant() == ConstantBool::False) {
Chris Lattner4f031622004-11-15 05:03:30 +0000517 LatticeVal &Val = getValueState(I.getFalseValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000518 if (Val.isOverdefined())
519 markOverdefined(&I);
520 else if (Val.isConstant())
521 markConstant(&I, Val.getConstant());
522 } else
523 markOverdefined(&I);
524 }
525}
526
Chris Lattner6e560792002-04-18 15:13:15 +0000527// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000528void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000529 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000530 if (IV.isOverdefined()) return;
531
Chris Lattner4f031622004-11-15 05:03:30 +0000532 LatticeVal &V1State = getValueState(I.getOperand(0));
533 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000534
Chris Lattner6e560792002-04-18 15:13:15 +0000535 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000536 // If both operands are PHI nodes, it is possible that this instruction has
537 // a constant value, despite the fact that the PHI node doesn't. Check for
538 // this condition now.
539 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
540 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
541 if (PN1->getParent() == PN2->getParent()) {
542 // Since the two PHI nodes are in the same basic block, they must have
543 // entries for the same predecessors. Walk the predecessor list, and
544 // if all of the incoming values are constants, and the result of
545 // evaluating this expression with all incoming value pairs is the
546 // same, then this expression is a constant even though the PHI node
547 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000548 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000549 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000550 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000551 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000552 LatticeVal &In2 =
553 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000554
555 if (In1.isOverdefined() || In2.isOverdefined()) {
556 Result.markOverdefined();
557 break; // Cannot fold this operation over the PHI nodes!
558 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000559 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
560 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000561 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000562 Result.markConstant(V);
563 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000564 Result.markOverdefined();
565 break;
566 }
567 }
568 }
569
570 // If we found a constant value here, then we know the instruction is
571 // constant despite the fact that the PHI nodes are overdefined.
572 if (Result.isConstant()) {
573 markConstant(IV, &I, Result.getConstant());
574 // Remember that this instruction is virtually using the PHI node
575 // operands.
576 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
577 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
578 return;
579 } else if (Result.isUndefined()) {
580 return;
581 }
582
583 // Okay, this really is overdefined now. Since we might have
584 // speculatively thought that this was not overdefined before, and
585 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
586 // make sure to clean out any entries that we put there, for
587 // efficiency.
588 std::multimap<PHINode*, Instruction*>::iterator It, E;
589 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
590 while (It != E) {
591 if (It->second == &I) {
592 UsersOfOverdefinedPHIs.erase(It++);
593 } else
594 ++It;
595 }
596 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
597 while (It != E) {
598 if (It->second == &I) {
599 UsersOfOverdefinedPHIs.erase(It++);
600 } else
601 ++It;
602 }
603 }
604
605 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000606 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000607 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
608 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000609 }
610}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000611
612// Handle getelementptr instructions... if all operands are constants then we
613// can turn this into a getelementptr ConstantExpr.
614//
Chris Lattner074be1f2004-11-15 04:44:20 +0000615void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000616 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000617 if (IV.isOverdefined()) return;
618
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000619 std::vector<Constant*> Operands;
620 Operands.reserve(I.getNumOperands());
621
622 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000623 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000624 if (State.isUndefined())
625 return; // Operands are not resolved yet...
626 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000627 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000628 return;
629 }
630 assert(State.isConstant() && "Unknown state!");
631 Operands.push_back(State.getConstant());
632 }
633
634 Constant *Ptr = Operands[0];
635 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
636
Chris Lattner49f74522004-01-12 04:29:41 +0000637 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000638}
Brian Gaeke960707c2003-11-11 22:41:34 +0000639
Chris Lattner49f74522004-01-12 04:29:41 +0000640/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
641/// return the constant value being addressed by the constant expression, or
642/// null if something is funny.
643///
644static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +0000645 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner49f74522004-01-12 04:29:41 +0000646 return 0; // Do not allow stepping over the value!
647
648 // Loop over all of the operands, tracking down which value we are
649 // addressing...
650 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
651 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000652 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
653 if (CS == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000654 if (CU->getValue() >= CS->getNumOperands()) return 0;
655 C = CS->getOperand(CU->getValue());
Chris Lattner49f74522004-01-12 04:29:41 +0000656 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000657 ConstantArray *CA = dyn_cast<ConstantArray>(C);
658 if (CA == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000659 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
660 C = CA->getOperand(CS->getValue());
Chris Lattner76b2ff42004-02-15 05:55:15 +0000661 } else
Chris Lattner49f74522004-01-12 04:29:41 +0000662 return 0;
663 return C;
664}
665
666// Handle load instructions. If the operand is a constant pointer to a constant
667// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +0000668void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000669 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000670 if (IV.isOverdefined()) return;
671
Chris Lattner4f031622004-11-15 05:03:30 +0000672 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +0000673 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
674 if (PtrVal.isConstant() && !I.isVolatile()) {
675 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000676 if (isa<ConstantPointerNull>(Ptr)) {
677 // load null -> null
678 markConstant(IV, &I, Constant::getNullValue(I.getType()));
679 return;
680 }
681
Chris Lattner49f74522004-01-12 04:29:41 +0000682 // Transform load (constant global) into the value loaded.
683 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
684 if (GV->isConstant() && !GV->isExternal()) {
685 markConstant(IV, &I, GV->getInitializer());
686 return;
687 }
688
689 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
690 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
691 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencerc5afc952004-07-18 00:31:05 +0000692 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
693 if (GV->isConstant() && !GV->isExternal())
694 if (Constant *V =
695 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
696 markConstant(IV, &I, V);
697 return;
698 }
Chris Lattner49f74522004-01-12 04:29:41 +0000699 }
700
701 // Otherwise we cannot say for certain what value this load will produce.
702 // Bail out.
703 markOverdefined(IV, &I);
704}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000705
Chris Lattner074be1f2004-11-15 04:44:20 +0000706void SCCPSolver::visitCallInst(CallInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000707 LatticeVal &IV = ValueState[&I];
Chris Lattnerff9362a2004-04-13 19:43:54 +0000708 if (IV.isOverdefined()) return;
709
710 Function *F = I.getCalledFunction();
711 if (F == 0 || !canConstantFoldCallTo(F)) {
712 markOverdefined(IV, &I);
713 return;
714 }
715
716 std::vector<Constant*> Operands;
717 Operands.reserve(I.getNumOperands()-1);
718
719 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000720 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerff9362a2004-04-13 19:43:54 +0000721 if (State.isUndefined())
722 return; // Operands are not resolved yet...
723 else if (State.isOverdefined()) {
724 markOverdefined(IV, &I);
725 return;
726 }
727 assert(State.isConstant() && "Unknown state!");
728 Operands.push_back(State.getConstant());
729 }
730
731 if (Constant *C = ConstantFoldCall(F, Operands))
732 markConstant(IV, &I, C);
733 else
734 markOverdefined(IV, &I);
735}
Chris Lattner074be1f2004-11-15 04:44:20 +0000736
737
738void SCCPSolver::Solve() {
739 // Process the work lists until they are empty!
740 while (!BBWorkList.empty() || !InstWorkList.empty() ||
741 !OverdefinedInstWorkList.empty()) {
742 // Process the instruction work list...
743 while (!OverdefinedInstWorkList.empty()) {
744 Instruction *I = OverdefinedInstWorkList.back();
745 OverdefinedInstWorkList.pop_back();
746
747 DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
748
749 // "I" got into the work list because it either made the transition from
750 // bottom to constant
751 //
752 // Anything on this worklist that is overdefined need not be visited
753 // since all of its users will have already been marked as overdefined
754 // Update all of the users of this instruction's value...
755 //
756 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
757 UI != E; ++UI)
758 OperandChangedState(*UI);
759 }
760 // Process the instruction work list...
761 while (!InstWorkList.empty()) {
762 Instruction *I = InstWorkList.back();
763 InstWorkList.pop_back();
764
765 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
766
767 // "I" got into the work list because it either made the transition from
768 // bottom to constant
769 //
770 // Anything on this worklist that is overdefined need not be visited
771 // since all of its users will have already been marked as overdefined.
772 // Update all of the users of this instruction's value...
773 //
774 if (!getValueState(I).isOverdefined())
775 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
776 UI != E; ++UI)
777 OperandChangedState(*UI);
778 }
779
780 // Process the basic block work list...
781 while (!BBWorkList.empty()) {
782 BasicBlock *BB = BBWorkList.back();
783 BBWorkList.pop_back();
784
785 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
786
787 // Notify all instructions in this basic block that they are newly
788 // executable.
789 visit(BB);
790 }
791 }
792}
793
794
795namespace {
796//===----------------------------------------------------------------------===//
797//
798/// SCCP Class - This class does all of the work of Sparse Conditional Constant
799/// Propagation.
800///
801class SCCP : public FunctionPass, public InstVisitor<SCCP> {
802public:
803
804 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
805 // and return true if the function was modified.
806 //
807 bool runOnFunction(Function &F);
808
809 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
810 AU.setPreservesCFG();
811 }
812};
813
814 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
815} // end anonymous namespace
816
817
818// createSCCPPass - This is the public interface to this file...
819FunctionPass *llvm::createSCCPPass() {
820 return new SCCP();
821}
822
823
824//===----------------------------------------------------------------------===//
825// SCCP Class Implementation
826
827
828// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
829// and return true if the function was modified.
830//
831bool SCCP::runOnFunction(Function &F) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000832 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner074be1f2004-11-15 04:44:20 +0000833 SCCPSolver Solver;
834
835 // Mark the first block of the function as being executable.
836 Solver.MarkBlockExecutable(F.begin());
837
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000838 // Mark all arguments to the function as being overdefined.
839 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
840 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
841 Values[AI].markOverdefined();
842
Chris Lattner074be1f2004-11-15 04:44:20 +0000843 // Solve for constants.
844 Solver.Solve();
845
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000846 bool MadeChanges = false;
847
848 // If we decided that there are basic blocks that are dead in this function,
849 // delete their contents now. Note that we cannot actually delete the blocks,
850 // as we cannot modify the CFG of the function.
851 //
852 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
853 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
854 if (!ExecutableBBs.count(BB)) {
855 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
856 // Delete the instructions backwards, as it has a reduced likelihood of
857 // having to update as many def-use and use-def chains.
858 std::vector<Instruction*> Insts;
859 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
860 I != E; ++I)
861 Insts.push_back(I);
862 while (!Insts.empty()) {
863 Instruction *I = Insts.back();
864 Insts.pop_back();
865 if (!I->use_empty())
866 I->replaceAllUsesWith(UndefValue::get(I->getType()));
867 BB->getInstList().erase(I);
868 MadeChanges = true;
869 }
870 }
Chris Lattner074be1f2004-11-15 04:44:20 +0000871
872 // Iterate over all of the instructions in a function, replacing them with
873 // constants if we have found them to be of constant values.
874 //
Chris Lattner074be1f2004-11-15 04:44:20 +0000875 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
876 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
877 Instruction *Inst = BI++;
878 if (Inst->getType() != Type::VoidTy) {
Chris Lattner4f031622004-11-15 05:03:30 +0000879 LatticeVal &IV = Values[Inst];
Chris Lattner074be1f2004-11-15 04:44:20 +0000880 if (IV.isConstant() || IV.isUndefined()) {
881 Constant *Const;
882 if (IV.isConstant()) {
883 Const = IV.getConstant();
884 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
885 } else {
886 Const = UndefValue::get(Inst->getType());
887 DEBUG(std::cerr << " Undefined: " << *Inst);
888 }
889
890 // Replaces all of the uses of a variable with uses of the constant.
891 Inst->replaceAllUsesWith(Const);
892
893 // Delete the instruction.
894 BB->getInstList().erase(Inst);
895
896 // Hey, we just changed something!
897 MadeChanges = true;
898 ++NumInstRemoved;
899 }
900 }
901 }
902
903 return MadeChanges;
904}
905
906