blob: 9a8d26bb7b8c2b50795121dcdea41008b2dce1c2 [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 Lattner91dbae62004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.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 Lattner6e560792002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.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
Chris Lattner4f031622004-11-15 05:03:30 +000047class LatticeVal {
Chris Lattner347389d2001-06-27 23:38:11 +000048 enum {
Chris Lattner3462ae32001-12-03 22:26:30 +000049 undefined, // This instruction has no known value
50 constant, // This instruction has a constant value
Chris Lattner3462ae32001-12-03 22:26:30 +000051 overdefined // This instruction has an unknown value
52 } LatticeValue; // The current lattice position
53 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000054public:
Chris Lattner4f031622004-11-15 05:03:30 +000055 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner347389d2001-06-27 23:38:11 +000056
57 // markOverdefined - Return true if this is a new status to be in...
58 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000059 if (LatticeValue != overdefined) {
60 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000061 return true;
62 }
63 return false;
64 }
65
66 // markConstant - Return true if this is a new status for us...
Chris Lattner3462ae32001-12-03 22:26:30 +000067 inline bool markConstant(Constant *V) {
68 if (LatticeValue != constant) {
69 LatticeValue = constant;
Chris Lattner347389d2001-06-27 23:38:11 +000070 ConstantVal = V;
71 return true;
72 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +000073 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +000074 }
75 return false;
76 }
77
Chris Lattner3462ae32001-12-03 22:26:30 +000078 inline bool isUndefined() const { return LatticeValue == undefined; }
79 inline bool isConstant() const { return LatticeValue == constant; }
80 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +000081
Chris Lattner05fe6842004-01-12 03:57:30 +000082 inline Constant *getConstant() const {
83 assert(isConstant() && "Cannot get the constant of a non-constant!");
84 return ConstantVal;
85 }
Chris Lattner347389d2001-06-27 23:38:11 +000086};
87
Chris Lattner7d325382002-04-29 21:26:08 +000088} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +000089
90
91//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +000092//
Chris Lattner074be1f2004-11-15 04:44:20 +000093/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
94/// Constant Propagation.
95///
96class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +000097 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +000098 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +000099
Chris Lattner91dbae62004-12-11 05:15:59 +0000100 /// GlobalValue - If we are tracking any values for the contents of a global
101 /// variable, we keep a mapping from the constant accessor to the element of
102 /// the global, to the currently known value. If the value becomes
103 /// overdefined, it's entry is simply removed from this map.
104 hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
105
Chris Lattnerb4394642004-12-10 08:02:06 +0000106 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
107 /// value out of a function, it will have an entry in this map, indicating
108 /// what the known return value for the function is.
109 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
110
Chris Lattnerd79334d2004-07-15 23:36:43 +0000111 // The reason for two worklists is that overdefined is the lowest state
112 // on the lattice, and moving things to overdefined as fast as possible
113 // makes SCCP converge much faster.
114 // By having a separate worklist, we accomplish this because everything
115 // possibly overdefined will become overdefined at the soonest possible
116 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000117 std::vector<Value*> OverdefinedInstWorkList;
118 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000119
120
Chris Lattner7f74a562002-01-20 22:54:45 +0000121 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000122
Chris Lattner05fe6842004-01-12 03:57:30 +0000123 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
124 /// overdefined, despite the fact that the PHI node is overdefined.
125 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
126
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000127 /// KnownFeasibleEdges - Entries in this set are edges which have already had
128 /// PHI nodes retriggered.
129 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
130 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000131public:
132
Chris Lattner074be1f2004-11-15 04:44:20 +0000133 /// MarkBlockExecutable - This method can be used by clients to mark all of
134 /// the blocks that are known to be intrinsically live in the processed unit.
135 void MarkBlockExecutable(BasicBlock *BB) {
136 DEBUG(std::cerr << "Marking Block Executable: " << BB->getName() << "\n");
137 BBExecutable.insert(BB); // Basic block is executable!
138 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000139 }
140
Chris Lattner91dbae62004-12-11 05:15:59 +0000141 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000142 /// inform the SCCPSolver that it should track loads and stores to the
143 /// specified global variable if it can. This is only legal to call if
144 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000145 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
146 const Type *ElTy = GV->getType()->getElementType();
147 if (ElTy->isFirstClassType()) {
148 LatticeVal &IV = TrackedGlobals[GV];
149 if (!isa<UndefValue>(GV->getInitializer()))
150 IV.markConstant(GV->getInitializer());
151 }
152 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000153
154 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
155 /// and out of the specified function (which cannot have its address taken),
156 /// this method must be called.
157 void AddTrackedFunction(Function *F) {
158 assert(F->hasInternalLinkage() && "Can only track internal functions!");
159 // Add an entry, F -> undef.
160 TrackedFunctionRetVals[F];
161 }
162
Chris Lattner074be1f2004-11-15 04:44:20 +0000163 /// Solve - Solve for constants and executable blocks.
164 ///
165 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000166
Chris Lattner7285f432004-12-10 20:41:50 +0000167 /// ResolveBranchesIn - While solving the dataflow for a function, we assume
168 /// that branches on undef values cannot reach any of their successors.
169 /// However, this is not a safe assumption. After we solve dataflow, this
170 /// method should be use to handle this. If this returns true, the solver
171 /// should be rerun.
172 bool ResolveBranchesIn(Function &F);
173
Chris Lattner074be1f2004-11-15 04:44:20 +0000174 /// getExecutableBlocks - Once we have solved for constants, return the set of
175 /// blocks that is known to be executable.
176 std::set<BasicBlock*> &getExecutableBlocks() {
177 return BBExecutable;
178 }
179
180 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000181 /// LLVM values to LatticeVals.
182 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000183 return ValueState;
184 }
185
Chris Lattner99e12952004-12-11 02:53:57 +0000186 /// getTrackedFunctionRetVals - Get the inferred return value map.
187 ///
188 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
189 return TrackedFunctionRetVals;
190 }
191
Chris Lattner91dbae62004-12-11 05:15:59 +0000192 /// getTrackedGlobals - Get and return the set of inferred initializers for
193 /// global variables.
194 const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
195 return TrackedGlobals;
196 }
197
Chris Lattner99e12952004-12-11 02:53:57 +0000198
Chris Lattner347389d2001-06-27 23:38:11 +0000199private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000200 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner347389d2001-06-27 23:38:11 +0000201 // is not already a constant, add it to the instruction work list so that
202 // the users of the instruction are updated later.
203 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000204 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000205 if (IV.markConstant(C)) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000206 DEBUG(std::cerr << "markConstant: " << *C << ": " << *V);
207 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000208 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000209 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000210 inline void markConstant(Value *V, Constant *C) {
211 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000212 }
213
Chris Lattnerd79334d2004-07-15 23:36:43 +0000214 // markOverdefined - Make a value be marked as "overdefined". If the
215 // value is not already overdefined, add it to the overdefined instruction
216 // work list so that the users of the instruction are updated later.
217
Chris Lattnerb4394642004-12-10 08:02:06 +0000218 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000219 if (IV.markOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000220 DEBUG(std::cerr << "markOverdefined: " << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000221 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000222 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000223 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000224 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000225 inline void markOverdefined(Value *V) {
226 markOverdefined(ValueState[V], V);
227 }
228
229 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
230 if (IV.isOverdefined() || MergeWithV.isUndefined())
231 return; // Noop.
232 if (MergeWithV.isOverdefined())
233 markOverdefined(IV, V);
234 else if (IV.isUndefined())
235 markConstant(IV, V, MergeWithV.getConstant());
236 else if (IV.getConstant() != MergeWithV.getConstant())
237 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000238 }
239
Chris Lattner4f031622004-11-15 05:03:30 +0000240 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000241 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000242 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000243 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000244 // Instruction object, then use this accessor to get its value from the map.
245 //
Chris Lattner4f031622004-11-15 05:03:30 +0000246 inline LatticeVal &getValueState(Value *V) {
247 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000248 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000249
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000250 if (Constant *CPV = dyn_cast<Constant>(V)) {
251 if (isa<UndefValue>(V)) {
252 // Nothing to do, remain undefined.
253 } else {
254 ValueState[CPV].markConstant(CPV); // Constants are constant
255 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000256 }
Chris Lattner347389d2001-06-27 23:38:11 +0000257 // All others are underdefined by default...
258 return ValueState[V];
259 }
260
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000261 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000262 // work list if it is not already executable...
263 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000264 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
265 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
266 return; // This edge is already known to be executable!
267
268 if (BBExecutable.count(Dest)) {
269 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
270 << " -> " << Dest->getName() << "\n");
271
272 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000273 // feasible that wasn't before. Revisit the PHI nodes in the block
274 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000275 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
276 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000277
278 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000279 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000280 }
Chris Lattner347389d2001-06-27 23:38:11 +0000281 }
282
Chris Lattner074be1f2004-11-15 04:44:20 +0000283 // getFeasibleSuccessors - Return a vector of booleans to indicate which
284 // successors are reachable from a given terminator instruction.
285 //
286 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
287
288 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
289 // block to the 'To' basic block is currently feasible...
290 //
291 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
292
293 // OperandChangedState - This method is invoked on all of the users of an
294 // instruction that was just changed state somehow.... Based on this
295 // information, we need to update the specified user of this instruction.
296 //
297 void OperandChangedState(User *U) {
298 // Only instructions use other variable values!
299 Instruction &I = cast<Instruction>(*U);
300 if (BBExecutable.count(I.getParent())) // Inst is executable?
301 visit(I);
302 }
303
304private:
305 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000306
Chris Lattner6e560792002-04-18 15:13:15 +0000307 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000308 // operand made a transition, or the instruction is newly executable. Change
309 // the value type of I to reflect these changes if appropriate.
310 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000311 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000312
313 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000314 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000315 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000316
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000317 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000318 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000319 void visitBinaryOperator(Instruction &I);
320 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000321
322 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000323 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000324 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000325 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000326 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
327 void visitInvokeInst (InvokeInst &II) {
328 visitCallSite(CallSite::get(&II));
329 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000330 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000331 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000332 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000333 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000334 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000335 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
336 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000337 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000338
Chris Lattner113f4f42002-06-25 16:13:24 +0000339 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000340 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000341 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000342 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000343 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000344};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000345
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000346// getFeasibleSuccessors - Return a vector of booleans to indicate which
347// successors are reachable from a given terminator instruction.
348//
Chris Lattner074be1f2004-11-15 04:44:20 +0000349void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
350 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000351 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000352 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000353 if (BI->isUnconditional()) {
354 Succs[0] = true;
355 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000356 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000357 if (BCValue.isOverdefined() ||
358 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
359 // Overdefined condition variables, and branches on unfoldable constant
360 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000361 Succs[0] = Succs[1] = true;
362 } else if (BCValue.isConstant()) {
363 // Constant condition variables mean the branch can only go a single way
364 Succs[BCValue.getConstant() == ConstantBool::False] = true;
365 }
366 }
Chris Lattner113f4f42002-06-25 16:13:24 +0000367 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000368 // Invoke instructions successors are always executable.
369 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000370 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000371 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000372 if (SCValue.isOverdefined() || // Overdefined condition?
373 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000374 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000375 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000376 } else if (SCValue.isConstant()) {
377 Constant *CPV = SCValue.getConstant();
378 // 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 right branch...
381 Succs[i] = true;
382 return;
383 }
384 }
385
386 // Constant value not equal to any of the branches... must execute
387 // default branch then...
388 Succs[0] = true;
389 }
390 } else {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000391 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000392 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000393 }
394}
395
396
Chris Lattner13b52e72002-05-02 21:18:01 +0000397// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
398// block to the 'To' basic block is currently feasible...
399//
Chris Lattner074be1f2004-11-15 04:44:20 +0000400bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000401 assert(BBExecutable.count(To) && "Dest should always be alive!");
402
403 // Make sure the source basic block is executable!!
404 if (!BBExecutable.count(From)) return false;
405
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000406 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000407 TerminatorInst *TI = From->getTerminator();
408 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
409 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000410 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000411 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000412 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000413 if (BCValue.isOverdefined()) {
414 // Overdefined condition variables mean the branch could go either way.
415 return true;
416 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000417 // Not branching on an evaluatable constant?
418 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
419
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000420 // Constant condition variables mean the branch can only go a single way
421 return BI->getSuccessor(BCValue.getConstant() ==
422 ConstantBool::False) == To;
423 }
424 return false;
425 }
426 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
427 // Invoke instructions successors are always executable.
428 return true;
429 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000430 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000431 if (SCValue.isOverdefined()) { // Overdefined condition?
432 // All destinations are executable!
433 return true;
434 } else if (SCValue.isConstant()) {
435 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000436 if (!isa<ConstantInt>(CPV))
437 return true; // not a foldable constant?
438
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000439 // Make sure to skip the "default value" which isn't a value
440 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
441 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
442 return SI->getSuccessor(i) == To;
443
444 // Constant value not equal to any of the branches... must execute
445 // default branch then...
446 return SI->getDefaultDest() == To;
447 }
448 return false;
449 } else {
450 std::cerr << "Unknown terminator instruction: " << *TI;
451 abort();
452 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000453}
Chris Lattner347389d2001-06-27 23:38:11 +0000454
Chris Lattner6e560792002-04-18 15:13:15 +0000455// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000456// operand made a transition, or the instruction is newly executable. Change
457// the value type of I to reflect these changes if appropriate. This method
458// makes sure to do the following actions:
459//
460// 1. If a phi node merges two constants in, and has conflicting value coming
461// from different branches, or if the PHI node merges in an overdefined
462// value, then the PHI node becomes overdefined.
463// 2. If a phi node merges only constants in, and they all agree on value, the
464// PHI node becomes a constant value equal to that.
465// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
466// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
467// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
468// 6. If a conditional branch has a value that is constant, make the selected
469// destination executable
470// 7. If a conditional branch has a value that is overdefined, make all
471// successors executable.
472//
Chris Lattner074be1f2004-11-15 04:44:20 +0000473void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000474 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000475 if (PNIV.isOverdefined()) {
476 // There may be instructions using this PHI node that are not overdefined
477 // themselves. If so, make sure that they know that the PHI node operand
478 // changed.
479 std::multimap<PHINode*, Instruction*>::iterator I, E;
480 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
481 if (I != E) {
482 std::vector<Instruction*> Users;
483 Users.reserve(std::distance(I, E));
484 for (; I != E; ++I) Users.push_back(I->second);
485 while (!Users.empty()) {
486 visit(Users.back());
487 Users.pop_back();
488 }
489 }
490 return; // Quick exit
491 }
Chris Lattner347389d2001-06-27 23:38:11 +0000492
Chris Lattner7a7b1142004-03-16 19:49:59 +0000493 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
494 // and slow us down a lot. Just mark them overdefined.
495 if (PN.getNumIncomingValues() > 64) {
496 markOverdefined(PNIV, &PN);
497 return;
498 }
499
Chris Lattner6e560792002-04-18 15:13:15 +0000500 // Look at all of the executable operands of the PHI node. If any of them
501 // are overdefined, the PHI becomes overdefined as well. If they are all
502 // constant, and they agree with each other, the PHI becomes the identical
503 // constant. If they are constant and don't agree, the PHI is overdefined.
504 // If there are no executable operands, the PHI remains undefined.
505 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000506 Constant *OperandVal = 0;
507 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000508 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000509 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000510
Chris Lattner113f4f42002-06-25 16:13:24 +0000511 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000512 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000513 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000514 return;
515 }
516
Chris Lattnercccc5c72003-04-25 02:50:03 +0000517 if (OperandVal == 0) { // Grab the first value...
518 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000519 } else { // Another value is being merged in!
520 // There is already a reachable operand. If we conflict with it,
521 // then the PHI node becomes overdefined. If we agree with it, we
522 // can continue on.
Chris Lattnercccc5c72003-04-25 02:50:03 +0000523
Chris Lattner6e560792002-04-18 15:13:15 +0000524 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000525 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000526 // Yes there is. This means the PHI node is not constant.
527 // You must be overdefined poor PHI.
528 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000529 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000530 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000531 }
Chris Lattner347389d2001-06-27 23:38:11 +0000532 }
533 }
Chris Lattner347389d2001-06-27 23:38:11 +0000534 }
535
Chris Lattner6e560792002-04-18 15:13:15 +0000536 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000537 // arguments that agree with each other(and OperandVal is the constant) or
538 // OperandVal is null because there are no defined incoming arguments. If
539 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000540 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000541 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000542 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000543}
544
Chris Lattnerb4394642004-12-10 08:02:06 +0000545void SCCPSolver::visitReturnInst(ReturnInst &I) {
546 if (I.getNumOperands() == 0) return; // Ret void
547
548 // If we are tracking the return value of this function, merge it in.
549 Function *F = I.getParent()->getParent();
550 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
551 hash_map<Function*, LatticeVal>::iterator TFRVI =
552 TrackedFunctionRetVals.find(F);
553 if (TFRVI != TrackedFunctionRetVals.end() &&
554 !TFRVI->second.isOverdefined()) {
555 LatticeVal &IV = getValueState(I.getOperand(0));
556 mergeInValue(TFRVI->second, F, IV);
557 }
558 }
559}
560
561
Chris Lattner074be1f2004-11-15 04:44:20 +0000562void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000563 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000564 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000565
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000566 BasicBlock *BB = TI.getParent();
567
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000568 // Mark all feasible successors executable...
569 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000570 if (SuccFeasible[i])
571 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000572}
573
Chris Lattner074be1f2004-11-15 04:44:20 +0000574void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000575 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000576 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000577 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000578 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000579 else if (VState.isConstant()) // Propagate constant value
580 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000581}
582
Chris Lattner074be1f2004-11-15 04:44:20 +0000583void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000584 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner59db22d2004-03-12 05:52:44 +0000585 if (CondValue.isOverdefined())
586 markOverdefined(&I);
587 else if (CondValue.isConstant()) {
588 if (CondValue.getConstant() == ConstantBool::True) {
Chris Lattner4f031622004-11-15 05:03:30 +0000589 LatticeVal &Val = getValueState(I.getTrueValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000590 if (Val.isOverdefined())
591 markOverdefined(&I);
592 else if (Val.isConstant())
593 markConstant(&I, Val.getConstant());
594 } else if (CondValue.getConstant() == ConstantBool::False) {
Chris Lattner4f031622004-11-15 05:03:30 +0000595 LatticeVal &Val = getValueState(I.getFalseValue());
Chris Lattner59db22d2004-03-12 05:52:44 +0000596 if (Val.isOverdefined())
597 markOverdefined(&I);
598 else if (Val.isConstant())
599 markConstant(&I, Val.getConstant());
600 } else
601 markOverdefined(&I);
602 }
603}
604
Chris Lattner6e560792002-04-18 15:13:15 +0000605// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000606void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000607 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000608 if (IV.isOverdefined()) return;
609
Chris Lattner4f031622004-11-15 05:03:30 +0000610 LatticeVal &V1State = getValueState(I.getOperand(0));
611 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000612
Chris Lattner6e560792002-04-18 15:13:15 +0000613 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000614 // If both operands are PHI nodes, it is possible that this instruction has
615 // a constant value, despite the fact that the PHI node doesn't. Check for
616 // this condition now.
617 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
618 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
619 if (PN1->getParent() == PN2->getParent()) {
620 // Since the two PHI nodes are in the same basic block, they must have
621 // entries for the same predecessors. Walk the predecessor list, and
622 // if all of the incoming values are constants, and the result of
623 // evaluating this expression with all incoming value pairs is the
624 // same, then this expression is a constant even though the PHI node
625 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000626 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000627 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000628 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000629 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000630 LatticeVal &In2 =
631 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000632
633 if (In1.isOverdefined() || In2.isOverdefined()) {
634 Result.markOverdefined();
635 break; // Cannot fold this operation over the PHI nodes!
636 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000637 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
638 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000639 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000640 Result.markConstant(V);
641 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000642 Result.markOverdefined();
643 break;
644 }
645 }
646 }
647
648 // If we found a constant value here, then we know the instruction is
649 // constant despite the fact that the PHI nodes are overdefined.
650 if (Result.isConstant()) {
651 markConstant(IV, &I, Result.getConstant());
652 // Remember that this instruction is virtually using the PHI node
653 // operands.
654 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
655 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
656 return;
657 } else if (Result.isUndefined()) {
658 return;
659 }
660
661 // Okay, this really is overdefined now. Since we might have
662 // speculatively thought that this was not overdefined before, and
663 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
664 // make sure to clean out any entries that we put there, for
665 // efficiency.
666 std::multimap<PHINode*, Instruction*>::iterator It, E;
667 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
668 while (It != E) {
669 if (It->second == &I) {
670 UsersOfOverdefinedPHIs.erase(It++);
671 } else
672 ++It;
673 }
674 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
675 while (It != E) {
676 if (It->second == &I) {
677 UsersOfOverdefinedPHIs.erase(It++);
678 } else
679 ++It;
680 }
681 }
682
683 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000684 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000685 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
686 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000687 }
688}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000689
690// Handle getelementptr instructions... if all operands are constants then we
691// can turn this into a getelementptr ConstantExpr.
692//
Chris Lattner074be1f2004-11-15 04:44:20 +0000693void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000694 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000695 if (IV.isOverdefined()) return;
696
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000697 std::vector<Constant*> Operands;
698 Operands.reserve(I.getNumOperands());
699
700 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000701 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000702 if (State.isUndefined())
703 return; // Operands are not resolved yet...
704 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000705 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000706 return;
707 }
708 assert(State.isConstant() && "Unknown state!");
709 Operands.push_back(State.getConstant());
710 }
711
712 Constant *Ptr = Operands[0];
713 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
714
Chris Lattner49f74522004-01-12 04:29:41 +0000715 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000716}
Brian Gaeke960707c2003-11-11 22:41:34 +0000717
Chris Lattner49f74522004-01-12 04:29:41 +0000718/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
719/// return the constant value being addressed by the constant expression, or
720/// null if something is funny.
721///
722static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +0000723 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner49f74522004-01-12 04:29:41 +0000724 return 0; // Do not allow stepping over the value!
725
726 // Loop over all of the operands, tracking down which value we are
727 // addressing...
728 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
729 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000730 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
731 if (CS == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000732 if (CU->getValue() >= CS->getNumOperands()) return 0;
733 C = CS->getOperand(CU->getValue());
Chris Lattner49f74522004-01-12 04:29:41 +0000734 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattner76b2ff42004-02-15 05:55:15 +0000735 ConstantArray *CA = dyn_cast<ConstantArray>(C);
736 if (CA == 0) return 0;
Alkis Evlogimenos83243722004-08-04 08:44:43 +0000737 if ((uint64_t)CS->getValue() >= CA->getNumOperands()) return 0;
738 C = CA->getOperand(CS->getValue());
Chris Lattner76b2ff42004-02-15 05:55:15 +0000739 } else
Chris Lattner49f74522004-01-12 04:29:41 +0000740 return 0;
741 return C;
742}
743
Chris Lattner91dbae62004-12-11 05:15:59 +0000744void SCCPSolver::visitStoreInst(Instruction &SI) {
745 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
746 return;
747 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
748 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
749 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
750
751 // Get the value we are storing into the global.
752 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
753
754 mergeInValue(I->second, GV, PtrVal);
755 if (I->second.isOverdefined())
756 TrackedGlobals.erase(I); // No need to keep tracking this!
757}
758
759
Chris Lattner49f74522004-01-12 04:29:41 +0000760// Handle load instructions. If the operand is a constant pointer to a constant
761// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +0000762void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000763 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000764 if (IV.isOverdefined()) return;
765
Chris Lattner4f031622004-11-15 05:03:30 +0000766 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +0000767 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
768 if (PtrVal.isConstant() && !I.isVolatile()) {
769 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000770 if (isa<ConstantPointerNull>(Ptr)) {
771 // load null -> null
772 markConstant(IV, &I, Constant::getNullValue(I.getType()));
773 return;
774 }
775
Chris Lattner49f74522004-01-12 04:29:41 +0000776 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +0000777 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
778 if (GV->isConstant()) {
779 if (!GV->isExternal()) {
780 markConstant(IV, &I, GV->getInitializer());
781 return;
782 }
783 } else if (!TrackedGlobals.empty()) {
784 // If we are tracking this global, merge in the known value for it.
785 hash_map<GlobalVariable*, LatticeVal>::iterator It =
786 TrackedGlobals.find(GV);
787 if (It != TrackedGlobals.end()) {
788 mergeInValue(IV, &I, It->second);
789 return;
790 }
Chris Lattner49f74522004-01-12 04:29:41 +0000791 }
Chris Lattner91dbae62004-12-11 05:15:59 +0000792 }
Chris Lattner49f74522004-01-12 04:29:41 +0000793
794 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
795 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
796 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencerc5afc952004-07-18 00:31:05 +0000797 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
798 if (GV->isConstant() && !GV->isExternal())
799 if (Constant *V =
800 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
801 markConstant(IV, &I, V);
802 return;
803 }
Chris Lattner49f74522004-01-12 04:29:41 +0000804 }
805
806 // Otherwise we cannot say for certain what value this load will produce.
807 // Bail out.
808 markOverdefined(IV, &I);
809}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000810
Chris Lattnerb4394642004-12-10 08:02:06 +0000811void SCCPSolver::visitCallSite(CallSite CS) {
812 Function *F = CS.getCalledFunction();
813
814 // If we are tracking this function, we must make sure to bind arguments as
815 // appropriate.
816 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
817 if (F && F->hasInternalLinkage())
818 TFRVI = TrackedFunctionRetVals.find(F);
819
820 if (TFRVI != TrackedFunctionRetVals.end()) {
821 // If this is the first call to the function hit, mark its entry block
822 // executable.
823 if (!BBExecutable.count(F->begin()))
824 MarkBlockExecutable(F->begin());
825
826 CallSite::arg_iterator CAI = CS.arg_begin();
827 for (Function::aiterator AI = F->abegin(), E = F->aend();
828 AI != E; ++AI, ++CAI) {
829 LatticeVal &IV = ValueState[AI];
830 if (!IV.isOverdefined())
831 mergeInValue(IV, AI, getValueState(*CAI));
832 }
833 }
834 Instruction *I = CS.getInstruction();
835 if (I->getType() == Type::VoidTy) return;
836
837 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +0000838 if (IV.isOverdefined()) return;
839
Chris Lattnerb4394642004-12-10 08:02:06 +0000840 // Propagate the return value of the function to the value of the instruction.
841 if (TFRVI != TrackedFunctionRetVals.end()) {
842 mergeInValue(IV, I, TFRVI->second);
843 return;
844 }
845
846 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
847 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000848 return;
849 }
850
851 std::vector<Constant*> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +0000852 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000853
Chris Lattnerb4394642004-12-10 08:02:06 +0000854 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
855 AI != E; ++AI) {
856 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000857 if (State.isUndefined())
858 return; // Operands are not resolved yet...
859 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000860 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000861 return;
862 }
863 assert(State.isConstant() && "Unknown state!");
864 Operands.push_back(State.getConstant());
865 }
866
867 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattnerb4394642004-12-10 08:02:06 +0000868 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000869 else
Chris Lattnerb4394642004-12-10 08:02:06 +0000870 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +0000871}
Chris Lattner074be1f2004-11-15 04:44:20 +0000872
873
874void SCCPSolver::Solve() {
875 // Process the work lists until they are empty!
876 while (!BBWorkList.empty() || !InstWorkList.empty() ||
877 !OverdefinedInstWorkList.empty()) {
878 // Process the instruction work list...
879 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000880 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +0000881 OverdefinedInstWorkList.pop_back();
882
Chris Lattnerb4394642004-12-10 08:02:06 +0000883 DEBUG(std::cerr << "\nPopped off OI-WL: " << *I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000884
885 // "I" got into the work list because it either made the transition from
886 // bottom to constant
887 //
888 // Anything on this worklist that is overdefined need not be visited
889 // since all of its users will have already been marked as overdefined
890 // Update all of the users of this instruction's value...
891 //
892 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
893 UI != E; ++UI)
894 OperandChangedState(*UI);
895 }
896 // Process the instruction work list...
897 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000898 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +0000899 InstWorkList.pop_back();
900
901 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
902
903 // "I" got into the work list because it either made the transition from
904 // bottom to constant
905 //
906 // Anything on this worklist that is overdefined need not be visited
907 // since all of its users will have already been marked as overdefined.
908 // Update all of the users of this instruction's value...
909 //
910 if (!getValueState(I).isOverdefined())
911 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
912 UI != E; ++UI)
913 OperandChangedState(*UI);
914 }
915
916 // Process the basic block work list...
917 while (!BBWorkList.empty()) {
918 BasicBlock *BB = BBWorkList.back();
919 BBWorkList.pop_back();
920
921 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
922
923 // Notify all instructions in this basic block that they are newly
924 // executable.
925 visit(BB);
926 }
927 }
928}
929
Chris Lattner7285f432004-12-10 20:41:50 +0000930/// ResolveBranchesIn - While solving the dataflow for a function, we assume
931/// that branches on undef values cannot reach any of their successors.
932/// However, this is not a safe assumption. After we solve dataflow, this
933/// method should be use to handle this. If this returns true, the solver
934/// should be rerun.
935bool SCCPSolver::ResolveBranchesIn(Function &F) {
936 bool BranchesResolved = false;
937 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
938 TerminatorInst *TI = BB->getTerminator();
939 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
940 if (BI->isConditional()) {
941 LatticeVal &BCValue = getValueState(BI->getCondition());
942 if (BCValue.isUndefined()) {
943 BI->setCondition(ConstantBool::True);
944 BranchesResolved = true;
945 visit(BI);
946 }
947 }
948 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
949 LatticeVal &SCValue = getValueState(SI->getCondition());
950 if (SCValue.isUndefined()) {
951 SI->setCondition(Constant::getNullValue(SI->getCondition()->getType()));
952 BranchesResolved = true;
953 visit(SI);
954 }
955 }
956 }
957 return BranchesResolved;
958}
959
Chris Lattner074be1f2004-11-15 04:44:20 +0000960
961namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +0000962 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
963 Statistic<> NumDeadBlocks ("sccp", "Number of basic blocks unreachable");
964
Chris Lattner1890f942004-11-15 07:15:04 +0000965 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +0000966 //
Chris Lattner1890f942004-11-15 07:15:04 +0000967 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
968 /// Sparse Conditional COnstant Propagator.
969 ///
970 struct SCCP : public FunctionPass {
971 // runOnFunction - Run the Sparse Conditional Constant Propagation
972 // algorithm, and return true if the function was modified.
973 //
974 bool runOnFunction(Function &F);
975
976 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
977 AU.setPreservesCFG();
978 }
979 };
Chris Lattner074be1f2004-11-15 04:44:20 +0000980
981 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
982} // end anonymous namespace
983
984
985// createSCCPPass - This is the public interface to this file...
986FunctionPass *llvm::createSCCPPass() {
987 return new SCCP();
988}
989
990
Chris Lattner074be1f2004-11-15 04:44:20 +0000991// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
992// and return true if the function was modified.
993//
994bool SCCP::runOnFunction(Function &F) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000995 DEBUG(std::cerr << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner074be1f2004-11-15 04:44:20 +0000996 SCCPSolver Solver;
997
998 // Mark the first block of the function as being executable.
999 Solver.MarkBlockExecutable(F.begin());
1000
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001001 // Mark all arguments to the function as being overdefined.
1002 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1003 for (Function::aiterator AI = F.abegin(), E = F.aend(); AI != E; ++AI)
1004 Values[AI].markOverdefined();
1005
Chris Lattner074be1f2004-11-15 04:44:20 +00001006 // Solve for constants.
Chris Lattner7285f432004-12-10 20:41:50 +00001007 bool ResolvedBranches = true;
1008 while (ResolvedBranches) {
1009 Solver.Solve();
1010 ResolvedBranches = Solver.ResolveBranchesIn(F);
1011 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001012
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001013 bool MadeChanges = false;
1014
1015 // If we decided that there are basic blocks that are dead in this function,
1016 // delete their contents now. Note that we cannot actually delete the blocks,
1017 // as we cannot modify the CFG of the function.
1018 //
1019 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1020 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1021 if (!ExecutableBBs.count(BB)) {
1022 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
Chris Lattner9a038a32004-11-15 07:02:42 +00001023 ++NumDeadBlocks;
1024
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001025 // Delete the instructions backwards, as it has a reduced likelihood of
1026 // having to update as many def-use and use-def chains.
1027 std::vector<Instruction*> Insts;
1028 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1029 I != E; ++I)
1030 Insts.push_back(I);
1031 while (!Insts.empty()) {
1032 Instruction *I = Insts.back();
1033 Insts.pop_back();
1034 if (!I->use_empty())
1035 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1036 BB->getInstList().erase(I);
1037 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001038 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001039 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001040 } else {
1041 // Iterate over all of the instructions in a function, replacing them with
1042 // constants if we have found them to be of constant values.
1043 //
1044 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1045 Instruction *Inst = BI++;
1046 if (Inst->getType() != Type::VoidTy) {
1047 LatticeVal &IV = Values[Inst];
1048 if (IV.isConstant() || IV.isUndefined() &&
1049 !isa<TerminatorInst>(Inst)) {
1050 Constant *Const = IV.isConstant()
1051 ? IV.getConstant() : UndefValue::get(Inst->getType());
Chris Lattner074be1f2004-11-15 04:44:20 +00001052 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
Chris Lattnerb4394642004-12-10 08:02:06 +00001053
1054 // Replaces all of the uses of a variable with uses of the constant.
1055 Inst->replaceAllUsesWith(Const);
1056
1057 // Delete the instruction.
1058 BB->getInstList().erase(Inst);
1059
1060 // Hey, we just changed something!
1061 MadeChanges = true;
1062 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001063 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001064 }
1065 }
1066 }
1067
1068 return MadeChanges;
1069}
Chris Lattnerb4394642004-12-10 08:02:06 +00001070
1071namespace {
1072 Statistic<> IPNumInstRemoved("ipsccp", "Number of instructions removed");
1073 Statistic<> IPNumDeadBlocks ("ipsccp", "Number of basic blocks unreachable");
1074 Statistic<> IPNumArgsElimed ("ipsccp",
1075 "Number of arguments constant propagated");
Chris Lattner91dbae62004-12-11 05:15:59 +00001076 Statistic<> IPNumGlobalConst("ipsccp",
1077 "Number of globals found to be constant");
Chris Lattnerb4394642004-12-10 08:02:06 +00001078
1079 //===--------------------------------------------------------------------===//
1080 //
1081 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1082 /// Constant Propagation.
1083 ///
1084 struct IPSCCP : public ModulePass {
1085 bool runOnModule(Module &M);
1086 };
1087
1088 RegisterOpt<IPSCCP>
1089 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1090} // end anonymous namespace
1091
1092// createIPSCCPPass - This is the public interface to this file...
1093ModulePass *llvm::createIPSCCPPass() {
1094 return new IPSCCP();
1095}
1096
1097
1098static bool AddressIsTaken(GlobalValue *GV) {
1099 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1100 UI != E; ++UI)
1101 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001102 if (SI->getOperand(0) == GV || SI->isVolatile())
1103 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001104 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1105 // Make sure we are calling the function, not passing the address.
1106 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1107 for (CallSite::arg_iterator AI = CS.arg_begin(),
1108 E = CS.arg_end(); AI != E; ++AI)
1109 if (*AI == GV)
1110 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001111 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1112 if (LI->isVolatile())
1113 return true;
1114 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001115 return true;
1116 }
1117 return false;
1118}
1119
1120bool IPSCCP::runOnModule(Module &M) {
1121 SCCPSolver Solver;
1122
1123 // Loop over all functions, marking arguments to those with their addresses
1124 // taken or that are external as overdefined.
1125 //
1126 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1127 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1128 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1129 if (!F->isExternal())
1130 Solver.MarkBlockExecutable(F->begin());
1131 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1132 Values[AI].markOverdefined();
1133 } else {
1134 Solver.AddTrackedFunction(F);
1135 }
1136
Chris Lattner91dbae62004-12-11 05:15:59 +00001137 // Loop over global variables. We inform the solver about any internal global
1138 // variables that do not have their 'addresses taken'. If they don't have
1139 // their addresses taken, we can propagate constants through them.
1140 for (Module::giterator G = M.gbegin(), E = M.gend(); G != E; ++G)
1141 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1142 Solver.TrackValueOfGlobalVariable(G);
1143
Chris Lattnerb4394642004-12-10 08:02:06 +00001144 // Solve for constants.
Chris Lattner7285f432004-12-10 20:41:50 +00001145 bool ResolvedBranches = true;
1146 while (ResolvedBranches) {
1147 Solver.Solve();
1148
1149 ResolvedBranches = false;
1150 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1151 ResolvedBranches |= Solver.ResolveBranchesIn(*F);
1152 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001153
1154 bool MadeChanges = false;
1155
1156 // Iterate over all of the instructions in the module, replacing them with
1157 // constants if we have found them to be of constant values.
1158 //
1159 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1160 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1161 for (Function::aiterator AI = F->abegin(), E = F->aend(); AI != E; ++AI)
1162 if (!AI->use_empty()) {
1163 LatticeVal &IV = Values[AI];
1164 if (IV.isConstant() || IV.isUndefined()) {
1165 Constant *CST = IV.isConstant() ?
1166 IV.getConstant() : UndefValue::get(AI->getType());
1167 DEBUG(std::cerr << "*** Arg " << *AI << " = " << *CST <<"\n");
1168
1169 // Replaces all of the uses of a variable with uses of the
1170 // constant.
1171 AI->replaceAllUsesWith(CST);
1172 ++IPNumArgsElimed;
1173 }
1174 }
1175
Chris Lattnerbae4b642004-12-10 22:29:08 +00001176 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001177 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1178 if (!ExecutableBBs.count(BB)) {
1179 DEBUG(std::cerr << " BasicBlock Dead:" << *BB);
1180 ++IPNumDeadBlocks;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001181 BlocksToErase.push_back(BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001182
Chris Lattnerb4394642004-12-10 08:02:06 +00001183 // Delete the instructions backwards, as it has a reduced likelihood of
1184 // having to update as many def-use and use-def chains.
1185 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001186 TerminatorInst *TI = BB->getTerminator();
1187 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001188 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001189
Chris Lattnerb4394642004-12-10 08:02:06 +00001190 while (!Insts.empty()) {
1191 Instruction *I = Insts.back();
1192 Insts.pop_back();
1193 if (!I->use_empty())
1194 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1195 BB->getInstList().erase(I);
1196 MadeChanges = true;
1197 ++IPNumInstRemoved;
1198 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001199
1200 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1201 BasicBlock *Succ = TI->getSuccessor(i);
1202 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1203 TI->getSuccessor(i)->removePredecessor(BB);
1204 }
Chris Lattner99e12952004-12-11 02:53:57 +00001205 if (!TI->use_empty())
1206 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001207 BB->getInstList().erase(TI);
1208
Chris Lattnerb4394642004-12-10 08:02:06 +00001209 } else {
1210 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1211 Instruction *Inst = BI++;
1212 if (Inst->getType() != Type::VoidTy) {
1213 LatticeVal &IV = Values[Inst];
1214 if (IV.isConstant() || IV.isUndefined() &&
1215 !isa<TerminatorInst>(Inst)) {
1216 Constant *Const = IV.isConstant()
1217 ? IV.getConstant() : UndefValue::get(Inst->getType());
1218 DEBUG(std::cerr << " Constant: " << *Const << " = " << *Inst);
1219
1220 // Replaces all of the uses of a variable with uses of the
1221 // constant.
1222 Inst->replaceAllUsesWith(Const);
1223
1224 // Delete the instruction.
1225 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1226 BB->getInstList().erase(Inst);
1227
1228 // Hey, we just changed something!
1229 MadeChanges = true;
1230 ++IPNumInstRemoved;
1231 }
1232 }
1233 }
1234 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001235
1236 // Now that all instructions in the function are constant folded, erase dead
1237 // blocks, because we can now use ConstantFoldTerminator to get rid of
1238 // in-edges.
1239 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1240 // If there are any PHI nodes in this successor, drop entries for BB now.
1241 BasicBlock *DeadBB = BlocksToErase[i];
1242 while (!DeadBB->use_empty()) {
1243 Instruction *I = cast<Instruction>(DeadBB->use_back());
1244 bool Folded = ConstantFoldTerminator(I->getParent());
1245 assert(Folded && "Didn't fold away reference to block!");
1246 }
1247
1248 // Finally, delete the basic block.
1249 F->getBasicBlockList().erase(DeadBB);
1250 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001251 }
Chris Lattner99e12952004-12-11 02:53:57 +00001252
1253 // If we inferred constant or undef return values for a function, we replaced
1254 // all call uses with the inferred value. This means we don't need to bother
1255 // actually returning anything from the function. Replace all return
1256 // instructions with return undef.
1257 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1258 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1259 E = RV.end(); I != E; ++I)
1260 if (!I->second.isOverdefined() &&
1261 I->first->getReturnType() != Type::VoidTy) {
1262 Function *F = I->first;
1263 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1264 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1265 if (!isa<UndefValue>(RI->getOperand(0)))
1266 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1267 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001268
1269 // If we infered constant or undef values for globals variables, we can delete
1270 // the global and any stores that remain to it.
1271 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1272 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1273 E = TG.end(); I != E; ++I) {
1274 GlobalVariable *GV = I->first;
1275 assert(!I->second.isOverdefined() &&
1276 "Overdefined values should have been taken out of the map!");
1277 DEBUG(std::cerr << "Found that GV '" << GV->getName()<< "' is constant!\n");
1278 while (!GV->use_empty()) {
1279 StoreInst *SI = cast<StoreInst>(GV->use_back());
1280 SI->eraseFromParent();
1281 }
1282 M.getGlobalList().erase(GV);
1283 }
Chris Lattner99e12952004-12-11 02:53:57 +00001284
Chris Lattnerb4394642004-12-10 08:02:06 +00001285 return MadeChanges;
1286}