blob: f6be510fb0bb32a8e4c94c596ee870edc56d14cb [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 Lattnerb4394642004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattner57698e22002-03-26 18:01:55 +000028#include "llvm/Function.h"
Chris Lattner49f74522004-01-12 04:29:41 +000029#include "llvm/GlobalVariable.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000030#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000031#include "llvm/Pass.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000032#include "llvm/Type.h"
Chris Lattner6e560792002-04-18 15:13:15 +000033#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000034#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000035#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000036#include "llvm/Support/Debug.h"
37#include "llvm/ADT/hash_map"
38#include "llvm/ADT/Statistic.h"
39#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000040#include <algorithm>
Chris Lattner347389d2001-06-27 23:38:11 +000041#include <set>
Chris Lattner49525f82004-01-09 06:02:20 +000042using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000043
Chris Lattner4f031622004-11-15 05:03:30 +000044// LatticeVal class - This class represents the different lattice values that an
Chris Lattnerc8e66542002-04-27 06:56:12 +000045// instruction may occupy. It is a simple class with value semantics.
Chris Lattner347389d2001-06-27 23:38:11 +000046//
Chris Lattner7d325382002-04-29 21:26:08 +000047namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000048
Chris Lattner4f031622004-11-15 05:03:30 +000049class LatticeVal {
Chris Lattner347389d2001-06-27 23:38:11 +000050 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000051 undefined, // This instruction has no known value
52 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000053 overdefined // This instruction has an unknown value
54 } LatticeValue; // The current lattice position
55 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000056public:
Chris Lattner4f031622004-11-15 05:03:30 +000057 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000058
59 // markOverdefined - Return true if this is a new status to be in...
60 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000061 if (LatticeValue != overdefined) {
62 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000063 return true;
64 }
65 return false;
66 }
67
68 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000069 inline bool markConstant(Constant *V) {
70 if (LatticeValue != constant) {
71 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000072 ConstantVal = V;
73 return true;
74 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000075 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000076 }
77 return false;
78 }
79
Chris Lattner3462ae32001-12-03 22:26:30 +000080 inline bool isUndefined() const { return LatticeValue == undefined; }
81 inline bool isConstant() const { return LatticeValue == constant; }
82 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000083
Chris Lattner05fe6842004-01-12 03:57:30 +000084 inline Constant *getConstant() const {
85 assert(isConstant() && "Cannot get the constant of a non-constant!");
86 return ConstantVal;
87 }
Chris Lattner347389d2001-06-27 23:38:11 +000088};
89
Chris Lattner7d325382002-04-29 21:26:08 +000090} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000091
92
93//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +000094//
Chris Lattner074be1f2004-11-15 04:44:20 +000095/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
96/// Constant Propagation.
97///
98class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +000099 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +0000100 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000101
Chris Lattnerb4394642004-12-10 08:02:06 +0000102 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
103 /// value out of a function, it will have an entry in this map, indicating
104 /// what the known return value for the function is.
105 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
106
Chris Lattnerd79334d2004-07-15 23:36:43 +0000107 // The reason for two worklists is that overdefined is the lowest state
108 // on the lattice, and moving things to overdefined as fast as possible
109 // makes SCCP converge much faster.
110 // By having a separate worklist, we accomplish this because everything
111 // possibly overdefined will become overdefined at the soonest possible
112 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000113 std::vector<Value*> OverdefinedInstWorkList;
114 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000115
116
Chris Lattner7f74a562002-01-20 22:54:45 +0000117 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000118
Chris Lattner05fe6842004-01-12 03:57:30 +0000119 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
120 /// overdefined, despite the fact that the PHI node is overdefined.
121 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
122
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000123 /// KnownFeasibleEdges - Entries in this set are edges which have already had
124 /// PHI nodes retriggered.
125 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
126 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000127public:
128
Chris Lattner074be1f2004-11-15 04:44:20 +0000129 /// MarkBlockExecutable - This method can be used by clients to mark all of
130 /// the blocks that are known to be intrinsically live in the processed unit.
131 void MarkBlockExecutable(BasicBlock *BB) {
132 DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
133 BBExecutable.insert(BB); // Basic block is executable!
134 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000135 }
136
Chris Lattnerb4394642004-12-10 08:02:06 +0000137 /// TrackValueOfGlobalVariableIfPossible - Clients can use this method to
138 /// inform the SCCPSolver that it should track loads and stores to the
139 /// specified global variable if it can. This is only legal to call if
140 /// performing Interprocedural SCCP.
141 void TrackValueOfGlobalVariableIfPossible(GlobalVariable *GV);
142
143 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
144 /// and out of the specified function (which cannot have its address taken),
145 /// this method must be called.
146 void AddTrackedFunction(Function *F) {
147 assert(F->hasInternalLinkage() && "Can only track internal functions!");
148 // Add an entry, F -> undef.
149 TrackedFunctionRetVals[F];
150 }
151
Chris Lattner074be1f2004-11-15 04:44:20 +0000152 /// Solve - Solve for constants and executable blocks.
153 ///
154 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000155
Chris Lattner7285f432004-12-10 20:41:50 +0000156 /// ResolveBranchesIn - While solving the dataflow for a function, we assume
157 /// that branches on undef values cannot reach any of their successors.
158 /// However, this is not a safe assumption. After we solve dataflow, this
159 /// method should be use to handle this. If this returns true, the solver
160 /// should be rerun.
161 bool ResolveBranchesIn(Function &F);
162
Chris Lattner074be1f2004-11-15 04:44:20 +0000163 /// getExecutableBlocks - Once we have solved for constants, return the set of
164 /// blocks that is known to be executable.
165 std::set<BasicBlock*> &getExecutableBlocks() {
166 return BBExecutable;
167 }
168
169 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000170 /// LLVM values to LatticeVals.
171 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000172 return ValueState;
173 }
174
Chris Lattner347389d2001-06-27 23:38:11 +0000175private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000176 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner347389d2001-06-27 23:38:11 +0000177 // is not already a constant, add it to the instruction work list so that
178 // the users of the instruction are updated later.
179 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000180 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000181 if (IV.markConstant(C)) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000182 DEBUG(std::cerr << "markConstant: " << *C << ": " << *V);
183 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000184 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000185 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000186 inline void markConstant(Value *V, Constant *C) {
187 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000188 }
189
Chris Lattnerd79334d2004-07-15 23:36:43 +0000190 // markOverdefined - Make a value be marked as "overdefined". If the
191 // value is not already overdefined, add it to the overdefined instruction
192 // work list so that the users of the instruction are updated later.
193
Chris Lattnerb4394642004-12-10 08:02:06 +0000194 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000195 if (IV.markOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000196 DEBUG(std::cerr << "markOverdefined: " << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000197 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000198 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000199 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000200 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000201 inline void markOverdefined(Value *V) {
202 markOverdefined(ValueState[V], V);
203 }
204
205 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
206 if (IV.isOverdefined() || MergeWithV.isUndefined())
207 return; // Noop.
208 if (MergeWithV.isOverdefined())
209 markOverdefined(IV, V);
210 else if (IV.isUndefined())
211 markConstant(IV, V, MergeWithV.getConstant());
212 else if (IV.getConstant() != MergeWithV.getConstant())
213 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000214 }
215
Chris Lattner4f031622004-11-15 05:03:30 +0000216 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000217 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000218 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000219 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000220 // Instruction object, then use this accessor to get its value from the map.
221 //
Chris Lattner4f031622004-11-15 05:03:30 +0000222 inline LatticeVal &getValueState(Value *V) {
223 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000224 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000225
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000226 if (Constant *CPV = dyn_cast<Constant>(V)) {
227 if (isa<UndefValue>(V)) {
228 // Nothing to do, remain undefined.
229 } else {
230 ValueState[CPV].markConstant(CPV); // Constants are constant
231 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000232 }
Chris Lattner347389d2001-06-27 23:38:11 +0000233 // All others are underdefined by default...
234 return ValueState[V];
235 }
236
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000237 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000238 // work list if it is not already executable...
239 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000240 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
241 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
242 return; // This edge is already known to be executable!
243
244 if (BBExecutable.count(Dest)) {
245 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
246 << " -> " << Dest->getName() << "\n");
247
248 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000249 // feasible that wasn't before. Revisit the PHI nodes in the block
250 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000251 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
252 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000253
254 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000255 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000256 }
Chris Lattner347389d2001-06-27 23:38:11 +0000257 }
258
Chris Lattner074be1f2004-11-15 04:44:20 +0000259 // getFeasibleSuccessors - Return a vector of booleans to indicate which
260 // successors are reachable from a given terminator instruction.
261 //
262 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
263
264 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
265 // block to the 'To' basic block is currently feasible...
266 //
267 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
268
269 // OperandChangedState - This method is invoked on all of the users of an
270 // instruction that was just changed state somehow.... Based on this
271 // information, we need to update the specified user of this instruction.
272 //
273 void OperandChangedState(User *U) {
274 // Only instructions use other variable values!
275 Instruction &I = cast<Instruction>(*U);
276 if (BBExecutable.count(I.getParent())) // Inst is executable?
277 visit(I);
278 }
279
280private:
281 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000282
Chris Lattner6e560792002-04-18 15:13:15 +0000283 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000284 // operand made a transition, or the instruction is newly executable. Change
285 // the value type of I to reflect these changes if appropriate.
286 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000287 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000288
289 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000290 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000291 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000292
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000293 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000294 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000295 void visitBinaryOperator(Instruction &I);
296 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000297
298 // Instructions that cannot be folded away...
Chris Lattner113f4f42002-06-25 16:13:24 +0000299 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattner49f74522004-01-12 04:29:41 +0000300 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000301 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000302 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
303 void visitInvokeInst (InvokeInst &II) {
304 visitCallSite(CallSite::get(&II));
305 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000306 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000307 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000308 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000309 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000310 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000311 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
312 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000313 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000314
Chris Lattner113f4f42002-06-25 16:13:24 +0000315 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000316 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000317 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000318 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000319 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000320};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000321
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000322// getFeasibleSuccessors - Return a vector of booleans to indicate which
323// successors are reachable from a given terminator instruction.
324//
Chris Lattner074be1f2004-11-15 04:44:20 +0000325void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
326 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000327 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000328 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000329 if (BI->isUnconditional()) {
330 Succs[0] = true;
331 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000332 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000333 if (BCValue.isOverdefined() ||
334 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
335 // Overdefined condition variables, and branches on unfoldable constant
336 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000337 Succs[0] = Succs[1] = true;
338 } else if (BCValue.isConstant()) {
339 // Constant condition variables mean the branch can only go a single way
340 Succs[BCValue.getConstant() == ConstantBool::False] = true;
341 }
342 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000343 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000344 // Invoke instructions successors are always executable.
345 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000346 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000347 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000348 if (SCValue.isOverdefined() || // Overdefined condition?
349 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000350 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000351 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000352 } else if (SCValue.isConstant()) {
353 Constant *CPV = SCValue.getConstant();
354 // Make sure to skip the "default value" which isn't a value
355 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
356 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
357 Succs[i] = true;
358 return;
359 }
360 }
361
362 // Constant value not equal to any of the branches... must execute
363 // default branch then...
364 Succs[0] = true;
365 }
366 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000367 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000368 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000369 }
370}
371
372
Chris Lattner13b52e72002-05-02 21:18:01 +0000373// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
374// block to the 'To' basic block is currently feasible...
375//
Chris Lattner074be1f2004-11-15 04:44:20 +0000376bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000377 assert(BBExecutable.count(To) && "Dest should always be alive!");
378
379 // Make sure the source basic block is executable!!
380 if (!BBExecutable.count(From)) return false;
381
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000382 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000383 TerminatorInst *TI = From->getTerminator();
384 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
385 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000386 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000387 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000388 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000389 if (BCValue.isOverdefined()) {
390 // Overdefined condition variables mean the branch could go either way.
391 return true;
392 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000393 // Not branching on an evaluatable constant?
394 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
395
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000396 // Constant condition variables mean the branch can only go a single way
397 return BI->getSuccessor(BCValue.getConstant() ==
398 ConstantBool::False) == To;
399 }
400 return false;
401 }
402 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
403 // Invoke instructions successors are always executable.
404 return true;
405 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000406 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000407 if (SCValue.isOverdefined()) { // Overdefined condition?
408 // All destinations are executable!
409 return true;
410 } else if (SCValue.isConstant()) {
411 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000412 if (!isa<ConstantInt>(CPV))
413 return true; // not a foldable constant?
414
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000415 // Make sure to skip the "default value" which isn't a value
416 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
417 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
418 return SI->getSuccessor(i) == To;
419
420 // Constant value not equal to any of the branches... must execute
421 // default branch then...
422 return SI->getDefaultDest() == To;
423 }
424 return false;
425 } else {
426 std::cerr << "Unknown terminator instruction: " << *TI;
427 abort();
428 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000429}
Chris Lattner347389d2001-06-27 23:38:11 +0000430
Chris Lattner6e560792002-04-18 15:13:15 +0000431// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000432// operand made a transition, or the instruction is newly executable. Change
433// the value type of I to reflect these changes if appropriate. This method
434// makes sure to do the following actions:
435//
436// 1. If a phi node merges two constants in, and has conflicting value coming
437// from different branches, or if the PHI node merges in an overdefined
438// value, then the PHI node becomes overdefined.
439// 2. If a phi node merges only constants in, and they all agree on value, the
440// PHI node becomes a constant value equal to that.
441// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
442// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
443// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
444// 6. If a conditional branch has a value that is constant, make the selected
445// destination executable
446// 7. If a conditional branch has a value that is overdefined, make all
447// successors executable.
448//
Chris Lattner074be1f2004-11-15 04:44:20 +0000449void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000450 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000451 if (PNIV.isOverdefined()) {
452 // There may be instructions using this PHI node that are not overdefined
453 // themselves. If so, make sure that they know that the PHI node operand
454 // changed.
455 std::multimap<PHINode*, Instruction*>::iterator I, E;
456 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
457 if (I != E) {
458 std::vector<Instruction*> Users;
459 Users.reserve(std::distance(I, E));
460 for (; I != E; ++I) Users.push_back(I->second);
461 while (!Users.empty()) {
462 visit(Users.back());
463 Users.pop_back();
464 }
465 }
466 return; // Quick exit
467 }
Chris Lattner347389d2001-06-27 23:38:11 +0000468
Chris Lattner7a7b1142004-03-16 19:49:59 +0000469 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
470 // and slow us down a lot. Just mark them overdefined.
471 if (PN.getNumIncomingValues() > 64) {
472 markOverdefined(PNIV, &PN);
473 return;
474 }
475
Chris Lattner6e560792002-04-18 15:13:15 +0000476 // Look at all of the executable operands of the PHI node. If any of them
477 // are overdefined, the PHI becomes overdefined as well. If they are all
478 // constant, and they agree with each other, the PHI becomes the identical
479 // constant. If they are constant and don't agree, the PHI is overdefined.
480 // If there are no executable operands, the PHI remains undefined.
481 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000482 Constant *OperandVal = 0;
483 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000484 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000485 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000486
Chris Lattner113f4f42002-06-25 16:13:24 +0000487 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000488 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000489 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000490 return;
491 }
492
Chris Lattnercccc5c72003-04-25 02:50:03 +0000493 if (OperandVal == 0) { // Grab the first value...
494 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000495 } else { // Another value is being merged in!
496 // There is already a reachable operand. If we conflict with it,
497 // then the PHI node becomes overdefined. If we agree with it, we
498 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000499
Chris Lattner6e560792002-04-18 15:13:15 +0000500 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000501 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000502 // Yes there is. This means the PHI node is not constant.
503 // You must be overdefined poor PHI.
504 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000505 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000506 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000507 }
Chris Lattner347389d2001-06-27 23:38:11 +0000508 }
509 }
Chris Lattner347389d2001-06-27 23:38:11 +0000510 }
511
Chris Lattner6e560792002-04-18 15:13:15 +0000512 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000513 // arguments that agree with each other(and OperandVal is the constant) or
514 // OperandVal is null because there are no defined incoming arguments. If
515 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000516 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000517 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000518 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000519}
520
Chris Lattnerb4394642004-12-10 08:02:06 +0000521void SCCPSolver::visitReturnInst(ReturnInst &I) {
522 if (I.getNumOperands() == 0) return; // Ret void
523
524 // If we are tracking the return value of this function, merge it in.
525 Function *F = I.getParent()->getParent();
526 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
527 hash_map<Function*, LatticeVal>::iterator TFRVI =
528 TrackedFunctionRetVals.find(F);
529 if (TFRVI != TrackedFunctionRetVals.end() &&
530 !TFRVI->second.isOverdefined()) {
531 LatticeVal &IV = getValueState(I.getOperand(0));
532 mergeInValue(TFRVI->second, F, IV);
533 }
534 }
535}
536
537
Chris Lattner074be1f2004-11-15 04:44:20 +0000538void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000539 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000540 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000541
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000542 BasicBlock *BB = TI.getParent();
543
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000544 // Mark all feasible successors executable...
545 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000546 if (SuccFeasible[i])
547 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000548}
549
Chris Lattner074be1f2004-11-15 04:44:20 +0000550void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000551 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000552 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000553 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000554 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000555 else if (VState.isConstant()) // Propagate constant value
556 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000557}
558
Chris Lattner074be1f2004-11-15 04:44:20 +0000559void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000560 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner59db22d2004-03-12 05:52:44 +0000561 if (CondValue.isOverdefined())
562 markOverdefined(&I);
563 else if (CondValue.isConstant()) {
564 if (CondValue.getConstant() == ConstantBool::True) {
Chris Lattner4f031622004-11-15 05:03:30 +0000565 LatticeVal &Val = getValueState(I.getTrueValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000566 if (Val.isOverdefined())
567 markOverdefined(&I);
568 else if (Val.isConstant())
569 markConstant(&I, Val.getConstant());
570 } else if (CondValue.getConstant() == ConstantBool::False) {
Chris Lattner4f031622004-11-15 05:03:30 +0000571 LatticeVal &Val = getValueState(I.getFalseValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000572 if (Val.isOverdefined())
573 markOverdefined(&I);
574 else if (Val.isConstant())
575 markConstant(&I, Val.getConstant());
576 } else
577 markOverdefined(&I);
578 }
579}
580
Chris Lattner6e560792002-04-18 15:13:15 +0000581// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000582void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000583 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000584 if (IV.isOverdefined()) return;
585
Chris Lattner4f031622004-11-15 05:03:30 +0000586 LatticeVal &V1State = getValueState(I.getOperand(0));
587 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000588
Chris Lattner6e560792002-04-18 15:13:15 +0000589 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000590 // If both operands are PHI nodes, it is possible that this instruction has
591 // a constant value, despite the fact that the PHI node doesn't. Check for
592 // this condition now.
593 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
594 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
595 if (PN1->getParent() == PN2->getParent()) {
596 // Since the two PHI nodes are in the same basic block, they must have
597 // entries for the same predecessors. Walk the predecessor list, and
598 // if all of the incoming values are constants, and the result of
599 // evaluating this expression with all incoming value pairs is the
600 // same, then this expression is a constant even though the PHI node
601 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000602 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000603 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000604 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000605 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000606 LatticeVal &In2 =
607 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000608
609 if (In1.isOverdefined() || In2.isOverdefined()) {
610 Result.markOverdefined();
611 break; // Cannot fold this operation over the PHI nodes!
612 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000613 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
614 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000615 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000616 Result.markConstant(V);
617 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000618 Result.markOverdefined();
619 break;
620 }
621 }
622 }
623
624 // If we found a constant value here, then we know the instruction is
625 // constant despite the fact that the PHI nodes are overdefined.
626 if (Result.isConstant()) {
627 markConstant(IV, &I, Result.getConstant());
628 // Remember that this instruction is virtually using the PHI node
629 // operands.
630 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
631 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
632 return;
633 } else if (Result.isUndefined()) {
634 return;
635 }
636
637 // Okay, this really is overdefined now. Since we might have
638 // speculatively thought that this was not overdefined before, and
639 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
640 // make sure to clean out any entries that we put there, for
641 // efficiency.
642 std::multimap<PHINode*, Instruction*>::iterator It, E;
643 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
644 while (It != E) {
645 if (It->second == &I) {
646 UsersOfOverdefinedPHIs.erase(It++);
647 } else
648 ++It;
649 }
650 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
651 while (It != E) {
652 if (It->second == &I) {
653 UsersOfOverdefinedPHIs.erase(It++);
654 } else
655 ++It;
656 }
657 }
658
659 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000660 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000661 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
662 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000663 }
664}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000665
666// Handle getelementptr instructions... if all operands are constants then we
667// can turn this into a getelementptr ConstantExpr.
668//
Chris Lattner074be1f2004-11-15 04:44:20 +0000669void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000670 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000671 if (IV.isOverdefined()) return;
672
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000673 std::vector<Constant*> Operands;
674 Operands.reserve(I.getNumOperands());
675
676 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000677 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000678 if (State.isUndefined())
679 return; // Operands are not resolved yet...
680 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000681 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000682 return;
683 }
684 assert(State.isConstant() && "Unknown state!");
685 Operands.push_back(State.getConstant());
686 }
687
688 Constant *Ptr = Operands[0];
689 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
690
Chris Lattner49f74522004-01-12 04:29:41 +0000691 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000692}
Brian Gaeke960707c2003-11-11 22:41:34 +0000693
Chris Lattner49f74522004-01-12 04:29:41 +0000694/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
695/// return the constant value being addressed by the constant expression, or
696/// null if something is funny.
697///
698static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +0000699 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner49f74522004-01-12 04:29:41 +0000700 return 0; // Do not allow stepping over the value!
701
702 // Loop over all of the operands, tracking down which value we are
703 // addressing...
704 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
705 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000706 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
707 if (CS == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000708 if (CU->getValue() >= CS->getNumOperands()) return 0;
709 C = CS->getOperand(CU->getValue());
Chris Lattner49f74522004-01-12 04:29:41 +0000710 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000711 ConstantArray *CA = dyn_cast<ConstantArray>(C);
712 if (CA == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000713 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
714 C = CA->getOperand(CS->getValue());
Chris Lattner76b2ff42004-02-15 05:55:15 +0000715 } else
Chris Lattner49f74522004-01-12 04:29:41 +0000716 return 0;
717 return C;
718}
719
720// Handle load instructions. If the operand is a constant pointer to a constant
721// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +0000722void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000723 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000724 if (IV.isOverdefined()) return;
725
Chris Lattner4f031622004-11-15 05:03:30 +0000726 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +0000727 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
728 if (PtrVal.isConstant() && !I.isVolatile()) {
729 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000730 if (isa<ConstantPointerNull>(Ptr)) {
731 // load null -> null
732 markConstant(IV, &I, Constant::getNullValue(I.getType()));
733 return;
734 }
735
Chris Lattner49f74522004-01-12 04:29:41 +0000736 // Transform load (constant global) into the value loaded.
737 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
738 if (GV->isConstant() && !GV->isExternal()) {
739 markConstant(IV, &I, GV->getInitializer());
740 return;
741 }
742
743 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
744 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
745 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencerc5afc952004-07-18 00:31:05 +0000746 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
747 if (GV->isConstant() && !GV->isExternal())
748 if (Constant *V =
749 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
750 markConstant(IV, &I, V);
751 return;
752 }
Chris Lattner49f74522004-01-12 04:29:41 +0000753 }
754
755 // Otherwise we cannot say for certain what value this load will produce.
756 // Bail out.
757 markOverdefined(IV, &I);
758}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000759
Chris Lattnerb4394642004-12-10 08:02:06 +0000760void SCCPSolver::visitCallSite(CallSite CS) {
761 Function *F = CS.getCalledFunction();
762
763 // If we are tracking this function, we must make sure to bind arguments as
764 // appropriate.
765 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
766 if (F && F->hasInternalLinkage())
767 TFRVI = TrackedFunctionRetVals.find(F);
768
769 if (TFRVI != TrackedFunctionRetVals.end()) {
770 // If this is the first call to the function hit, mark its entry block
771 // executable.
772 if (!BBExecutable.count(F->begin()))
773 MarkBlockExecutable(F->begin());
774
775 CallSite::arg_iterator CAI = CS.arg_begin();
776 for (Function::aiterator AI = F->abegin(), E = F->aend();
777 AI != E; ++AI, ++CAI) {
778 LatticeVal &IV = ValueState[AI];
779 if (!IV.isOverdefined())
780 mergeInValue(IV, AI, getValueState(*CAI));
781 }
782 }
783 Instruction *I = CS.getInstruction();
784 if (I->getType() == Type::VoidTy) return;
785
786 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +0000787 if (IV.isOverdefined()) return;
788
Chris Lattnerb4394642004-12-10 08:02:06 +0000789 // Propagate the return value of the function to the value of the instruction.
790 if (TFRVI != TrackedFunctionRetVals.end()) {
791 mergeInValue(IV, I, TFRVI->second);
792 return;
793 }
794
795 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
796 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000797 return;
798 }
799
800 std::vector<Constant*> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +0000801 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000802
Chris Lattnerb4394642004-12-10 08:02:06 +0000803 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
804 AI != E; ++AI) {
805 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000806 if (State.isUndefined())
807 return; // Operands are not resolved yet...
808 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000809 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000810 return;
811 }
812 assert(State.isConstant() && "Unknown state!");
813 Operands.push_back(State.getConstant());
814 }
815
816 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattnerb4394642004-12-10 08:02:06 +0000817 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000818 else
Chris Lattnerb4394642004-12-10 08:02:06 +0000819 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000820}
Chris Lattner074be1f2004-11-15 04:44:20 +0000821
822
823void SCCPSolver::Solve() {
824 // Process the work lists until they are empty!
825 while (!BBWorkList.empty() || !InstWorkList.empty() ||
826 !OverdefinedInstWorkList.empty()) {
827 // Process the instruction work list...
828 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000829 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +0000830 OverdefinedInstWorkList.pop_back();
831
Chris Lattnerb4394642004-12-10 08:02:06 +0000832 DEBUG(std::cerr << "\nPopped off OI-WL: " << *I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000833
834 // "I" got into the work list because it either made the transition from
835 // bottom to constant
836 //
837 // Anything on this worklist that is overdefined need not be visited
838 // since all of its users will have already been marked as overdefined
839 // Update all of the users of this instruction's value...
840 //
841 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
842 UI != E; ++UI)
843 OperandChangedState(*UI);
844 }
845 // Process the instruction work list...
846 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000847 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +0000848 InstWorkList.pop_back();
849
850 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
851
852 // "I" got into the work list because it either made the transition from
853 // bottom to constant
854 //
855 // Anything on this worklist that is overdefined need not be visited
856 // since all of its users will have already been marked as overdefined.
857 // Update all of the users of this instruction's value...
858 //
859 if (!getValueState(I).isOverdefined())
860 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
861 UI != E; ++UI)
862 OperandChangedState(*UI);
863 }
864
865 // Process the basic block work list...
866 while (!BBWorkList.empty()) {
867 BasicBlock *BB = BBWorkList.back();
868 BBWorkList.pop_back();
869
870 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
871
872 // Notify all instructions in this basic block that they are newly
873 // executable.
874 visit(BB);
875 }
876 }
877}
878
Chris Lattner7285f432004-12-10 20:41:50 +0000879/// ResolveBranchesIn - While solving the dataflow for a function, we assume
880/// that branches on undef values cannot reach any of their successors.
881/// However, this is not a safe assumption. After we solve dataflow, this
882/// method should be use to handle this. If this returns true, the solver
883/// should be rerun.
884bool SCCPSolver::ResolveBranchesIn(Function &F) {
885 bool BranchesResolved = false;
886 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
887 TerminatorInst *TI = BB->getTerminator();
888 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
889 if (BI->isConditional()) {
890 LatticeVal &BCValue = getValueState(BI->getCondition());
891 if (BCValue.isUndefined()) {
892 BI->setCondition(ConstantBool::True);
893 BranchesResolved = true;
894 visit(BI);
895 }
896 }
897 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
898 LatticeVal &SCValue = getValueState(SI->getCondition());
899 if (SCValue.isUndefined()) {
900 SI->setCondition(Constant::getNullValue(SI->getCondition()->getType()));
901 BranchesResolved = true;
902 visit(SI);
903 }
904 }
905 }
906 return BranchesResolved;
907}
908
Chris Lattner074be1f2004-11-15 04:44:20 +0000909
910namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +0000911 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
912 Statistic<> NumDeadBlocks ("sccp", "Number of basic blocks unreachable");
913
Chris Lattner1890f942004-11-15 07:15:04 +0000914 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +0000915 //
Chris Lattner1890f942004-11-15 07:15:04 +0000916 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
917 /// Sparse Conditional COnstant Propagator.
918 ///
919 struct SCCP : public FunctionPass {
920 // runOnFunction - Run the Sparse Conditional Constant Propagation
921 // algorithm, and return true if the function was modified.
922 //
923 bool runOnFunction(Function &F);
924
925 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
926 AU.setPreservesCFG();
927 }
928 };
Chris Lattner074be1f2004-11-15 04:44:20 +0000929
930 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
931} // end anonymous namespace
932
933
934// createSCCPPass - This is the public interface to this file...
935FunctionPass *llvm::createSCCPPass() {
936 return new SCCP();
937}
938
939
Chris Lattner074be1f2004-11-15 04:44:20 +0000940// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
941// and return true if the function was modified.
942//
943bool SCCP::runOnFunction(Function &F) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000944 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner074be1f2004-11-15 04:44:20 +0000945 SCCPSolver Solver;
946
947 // Mark the first block of the function as being executable.
948 Solver.MarkBlockExecutable(F.begin());
949
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000950 // Mark all arguments to the function as being overdefined.
951 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
952 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
953 Values[AI].markOverdefined();
954
Chris Lattner074be1f2004-11-15 04:44:20 +0000955 // Solve for constants.
Chris Lattner7285f432004-12-10 20:41:50 +0000956 bool ResolvedBranches = true;
957 while (ResolvedBranches) {
958 Solver.Solve();
959 ResolvedBranches = Solver.ResolveBranchesIn(F);
960 }
Chris Lattner074be1f2004-11-15 04:44:20 +0000961
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000962 bool MadeChanges = false;
963
964 // If we decided that there are basic blocks that are dead in this function,
965 // delete their contents now. Note that we cannot actually delete the blocks,
966 // as we cannot modify the CFG of the function.
967 //
968 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
969 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
970 if (!ExecutableBBs.count(BB)) {
971 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
Chris Lattner9a038a32004-11-15 07:02:42 +0000972 ++NumDeadBlocks;
973
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000974 // Delete the instructions backwards, as it has a reduced likelihood of
975 // having to update as many def-use and use-def chains.
976 std::vector<Instruction*> Insts;
977 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
978 I != E; ++I)
979 Insts.push_back(I);
980 while (!Insts.empty()) {
981 Instruction *I = Insts.back();
982 Insts.pop_back();
983 if (!I->use_empty())
984 I->replaceAllUsesWith(UndefValue::get(I->getType()));
985 BB->getInstList().erase(I);
986 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +0000987 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000988 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000989 } else {
990 // Iterate over all of the instructions in a function, replacing them with
991 // constants if we have found them to be of constant values.
992 //
993 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
994 Instruction *Inst = BI++;
995 if (Inst->getType() != Type::VoidTy) {
996 LatticeVal &IV = Values[Inst];
997 if (IV.isConstant() || IV.isUndefined() &&
998 !isa<TerminatorInst>(Inst)) {
999 Constant *Const = IV.isConstant()
1000 ? IV.getConstant() : UndefValue::get(Inst->getType());
Chris Lattner074be1f2004-11-15 04:44:20 +00001001 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
Chris Lattnerb4394642004-12-10 08:02:06 +00001002
1003 // Replaces all of the uses of a variable with uses of the constant.
1004 Inst->replaceAllUsesWith(Const);
1005
1006 // Delete the instruction.
1007 BB->getInstList().erase(Inst);
1008
1009 // Hey, we just changed something!
1010 MadeChanges = true;
1011 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001012 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001013 }
1014 }
1015 }
1016
1017 return MadeChanges;
1018}
Chris Lattnerb4394642004-12-10 08:02:06 +00001019
1020namespace {
1021 Statistic<> IPNumInstRemoved("ipsccp", "Number of instructions removed");
1022 Statistic<> IPNumDeadBlocks ("ipsccp", "Number of basic blocks unreachable");
1023 Statistic<> IPNumArgsElimed ("ipsccp",
1024 "Number of arguments constant propagated");
1025
1026 //===--------------------------------------------------------------------===//
1027 //
1028 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1029 /// Constant Propagation.
1030 ///
1031 struct IPSCCP : public ModulePass {
1032 bool runOnModule(Module &M);
1033 };
1034
1035 RegisterOpt<IPSCCP>
1036 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1037} // end anonymous namespace
1038
1039// createIPSCCPPass - This is the public interface to this file...
1040ModulePass *llvm::createIPSCCPPass() {
1041 return new IPSCCP();
1042}
1043
1044
1045static bool AddressIsTaken(GlobalValue *GV) {
1046 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1047 UI != E; ++UI)
1048 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1049 if (SI->getOperand(0) == GV) return true; // Storing addr of GV.
1050 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1051 // Make sure we are calling the function, not passing the address.
1052 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1053 for (CallSite::arg_iterator AI = CS.arg_begin(),
1054 E = CS.arg_end(); AI != E; ++AI)
1055 if (*AI == GV)
1056 return true;
1057 } else if (!isa<LoadInst>(*UI)) {
1058 return true;
1059 }
1060 return false;
1061}
1062
1063bool IPSCCP::runOnModule(Module &M) {
1064 SCCPSolver Solver;
1065
1066 // Loop over all functions, marking arguments to those with their addresses
1067 // taken or that are external as overdefined.
1068 //
1069 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1070 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1071 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1072 if (!F->isExternal())
1073 Solver.MarkBlockExecutable(F->begin());
1074 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1075 Values[AI].markOverdefined();
1076 } else {
1077 Solver.AddTrackedFunction(F);
1078 }
1079
1080 // Solve for constants.
Chris Lattner7285f432004-12-10 20:41:50 +00001081 bool ResolvedBranches = true;
1082 while (ResolvedBranches) {
1083 Solver.Solve();
1084
1085 ResolvedBranches = false;
1086 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1087 ResolvedBranches |= Solver.ResolveBranchesIn(*F);
1088 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001089
1090 bool MadeChanges = false;
1091
1092 // Iterate over all of the instructions in the module, replacing them with
1093 // constants if we have found them to be of constant values.
1094 //
1095 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1096 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1097 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1098 if (!AI->use_empty()) {
1099 LatticeVal &IV = Values[AI];
1100 if (IV.isConstant() || IV.isUndefined()) {
1101 Constant *CST = IV.isConstant() ?
1102 IV.getConstant() : UndefValue::get(AI->getType());
1103 DEBUG(std::cerr << "*** Arg " << *AI << " = " << *CST <<"\n");
1104
1105 // Replaces all of the uses of a variable with uses of the
1106 // constant.
1107 AI->replaceAllUsesWith(CST);
1108 ++IPNumArgsElimed;
1109 }
1110 }
1111
Chris Lattnerbae4b642004-12-10 22:29:08 +00001112 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001113 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1114 if (!ExecutableBBs.count(BB)) {
1115 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
1116 ++IPNumDeadBlocks;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001117 BlocksToErase.push_back(BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001118
Chris Lattnerb4394642004-12-10 08:02:06 +00001119 // Delete the instructions backwards, as it has a reduced likelihood of
1120 // having to update as many def-use and use-def chains.
1121 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001122 TerminatorInst *TI = BB->getTerminator();
1123 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001124 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001125
Chris Lattnerb4394642004-12-10 08:02:06 +00001126 while (!Insts.empty()) {
1127 Instruction *I = Insts.back();
1128 Insts.pop_back();
1129 if (!I->use_empty())
1130 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1131 BB->getInstList().erase(I);
1132 MadeChanges = true;
1133 ++IPNumInstRemoved;
1134 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001135
1136 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1137 BasicBlock *Succ = TI->getSuccessor(i);
1138 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1139 TI->getSuccessor(i)->removePredecessor(BB);
1140 }
1141 BB->getInstList().erase(TI);
1142
Chris Lattnerb4394642004-12-10 08:02:06 +00001143 } else {
1144 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1145 Instruction *Inst = BI++;
1146 if (Inst->getType() != Type::VoidTy) {
1147 LatticeVal &IV = Values[Inst];
1148 if (IV.isConstant() || IV.isUndefined() &&
1149 !isa<TerminatorInst>(Inst)) {
1150 Constant *Const = IV.isConstant()
1151 ? IV.getConstant() : UndefValue::get(Inst->getType());
1152 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
1153
1154 // Replaces all of the uses of a variable with uses of the
1155 // constant.
1156 Inst->replaceAllUsesWith(Const);
1157
1158 // Delete the instruction.
1159 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1160 BB->getInstList().erase(Inst);
1161
1162 // Hey, we just changed something!
1163 MadeChanges = true;
1164 ++IPNumInstRemoved;
1165 }
1166 }
1167 }
1168 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001169
1170 // Now that all instructions in the function are constant folded, erase dead
1171 // blocks, because we can now use ConstantFoldTerminator to get rid of
1172 // in-edges.
1173 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1174 // If there are any PHI nodes in this successor, drop entries for BB now.
1175 BasicBlock *DeadBB = BlocksToErase[i];
1176 while (!DeadBB->use_empty()) {
1177 Instruction *I = cast<Instruction>(DeadBB->use_back());
1178 bool Folded = ConstantFoldTerminator(I->getParent());
1179 assert(Folded && "Didn't fold away reference to block!");
1180 }
1181
1182 // Finally, delete the basic block.
1183 F->getBasicBlockList().erase(DeadBB);
1184 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001185 }
1186 return MadeChanges;
1187}