blob: 11e096cd13a3c4c729511eebc4fcebc521253c4b [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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 Lattner024f4ab2007-01-30 23:46:24 +000031#include "llvm/Analysis/ConstantFolding.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"
Chris Lattner024f4ab2007-01-30 23:46:24 +000035#include "llvm/Support/InstVisitor.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000036#include "llvm/ADT/hash_map"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000037#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000038#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 Lattner79a42ac2006-12-19 21:40:18 +000044STATISTIC(NumInstRemoved, "Number of instructions removed");
45STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
46
47STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
48STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
49STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
51
Chris Lattner7d325382002-04-29 21:26:08 +000052namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000053/// LatticeVal class - This class represents the different lattice values that
54/// an LLVM value may occupy. It is a simple class with value semantics.
55///
Chris Lattner4f031622004-11-15 05:03:30 +000056class LatticeVal {
Misha Brukmanb1c93172005-04-21 23:48:37 +000057 enum {
Chris Lattner1847f6d2006-12-20 06:21:33 +000058 /// undefined - This LLVM Value has no known value yet.
59 undefined,
60
61 /// constant - This LLVM Value has a specific constant value.
62 constant,
63
64 /// forcedconstant - This LLVM Value was thought to be undef until
65 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
66 /// with another (different) constant, it goes to overdefined, instead of
67 /// asserting.
68 forcedconstant,
69
70 /// overdefined - This instruction is not known to be constant, and we know
71 /// it has a value.
72 overdefined
73 } LatticeValue; // The current lattice position
74
Chris Lattner3462ae32001-12-03 22:26:30 +000075 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000076public:
Chris Lattner4f031622004-11-15 05:03:30 +000077 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000078
Chris Lattner347389d2001-06-27 23:38:11 +000079 // markOverdefined - Return true if this is a new status to be in...
80 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000081 if (LatticeValue != overdefined) {
82 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000083 return true;
84 }
85 return false;
86 }
87
Chris Lattner1847f6d2006-12-20 06:21:33 +000088 // markConstant - Return true if this is a new status for us.
Chris Lattner3462ae32001-12-03 22:26:30 +000089 inline bool markConstant(Constant *V) {
90 if (LatticeValue != constant) {
Chris Lattner1847f6d2006-12-20 06:21:33 +000091 if (LatticeValue == undefined) {
92 LatticeValue = constant;
Jim Laskeyc4ba9c12007-01-03 00:11:03 +000093 assert(V && "Marking constant with NULL");
Chris Lattner1847f6d2006-12-20 06:21:33 +000094 ConstantVal = V;
95 } else {
96 assert(LatticeValue == forcedconstant &&
97 "Cannot move from overdefined to constant!");
98 // Stay at forcedconstant if the constant is the same.
99 if (V == ConstantVal) return false;
100
101 // Otherwise, we go to overdefined. Assumptions made based on the
102 // forced value are possibly wrong. Assuming this is another constant
103 // could expose a contradiction.
104 LatticeValue = overdefined;
105 }
Chris Lattner347389d2001-06-27 23:38:11 +0000106 return true;
107 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000108 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000109 }
110 return false;
111 }
112
Chris Lattner1847f6d2006-12-20 06:21:33 +0000113 inline void markForcedConstant(Constant *V) {
114 assert(LatticeValue == undefined && "Can't force a defined value!");
115 LatticeValue = forcedconstant;
116 ConstantVal = V;
117 }
118
119 inline bool isUndefined() const { return LatticeValue == undefined; }
120 inline bool isConstant() const {
121 return LatticeValue == constant || LatticeValue == forcedconstant;
122 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000123 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000124
Chris Lattner05fe6842004-01-12 03:57:30 +0000125 inline Constant *getConstant() const {
126 assert(isConstant() && "Cannot get the constant of a non-constant!");
127 return ConstantVal;
128 }
Chris Lattner347389d2001-06-27 23:38:11 +0000129};
130
Chris Lattner7d325382002-04-29 21:26:08 +0000131} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +0000132
133
134//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000135//
Chris Lattner074be1f2004-11-15 04:44:20 +0000136/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
137/// Constant Propagation.
138///
139class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +0000140 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +0000141 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000142
Chris Lattner91dbae62004-12-11 05:15:59 +0000143 /// GlobalValue - If we are tracking any values for the contents of a global
144 /// variable, we keep a mapping from the constant accessor to the element of
145 /// the global, to the currently known value. If the value becomes
146 /// overdefined, it's entry is simply removed from this map.
147 hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
148
Chris Lattnerb4394642004-12-10 08:02:06 +0000149 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
150 /// value out of a function, it will have an entry in this map, indicating
151 /// what the known return value for the function is.
152 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
153
Chris Lattnerd79334d2004-07-15 23:36:43 +0000154 // The reason for two worklists is that overdefined is the lowest state
155 // on the lattice, and moving things to overdefined as fast as possible
156 // makes SCCP converge much faster.
157 // By having a separate worklist, we accomplish this because everything
158 // possibly overdefined will become overdefined at the soonest possible
159 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000160 std::vector<Value*> OverdefinedInstWorkList;
161 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000162
163
Chris Lattner7f74a562002-01-20 22:54:45 +0000164 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000165
Chris Lattner05fe6842004-01-12 03:57:30 +0000166 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
167 /// overdefined, despite the fact that the PHI node is overdefined.
168 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
169
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000170 /// KnownFeasibleEdges - Entries in this set are edges which have already had
171 /// PHI nodes retriggered.
172 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
173 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000174public:
175
Chris Lattner074be1f2004-11-15 04:44:20 +0000176 /// MarkBlockExecutable - This method can be used by clients to mark all of
177 /// the blocks that are known to be intrinsically live in the processed unit.
178 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000179 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000180 BBExecutable.insert(BB); // Basic block is executable!
181 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000182 }
183
Chris Lattner91dbae62004-12-11 05:15:59 +0000184 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000185 /// inform the SCCPSolver that it should track loads and stores to the
186 /// specified global variable if it can. This is only legal to call if
187 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000188 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
189 const Type *ElTy = GV->getType()->getElementType();
190 if (ElTy->isFirstClassType()) {
191 LatticeVal &IV = TrackedGlobals[GV];
192 if (!isa<UndefValue>(GV->getInitializer()))
193 IV.markConstant(GV->getInitializer());
194 }
195 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000196
197 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
198 /// and out of the specified function (which cannot have its address taken),
199 /// this method must be called.
200 void AddTrackedFunction(Function *F) {
201 assert(F->hasInternalLinkage() && "Can only track internal functions!");
202 // Add an entry, F -> undef.
203 TrackedFunctionRetVals[F];
204 }
205
Chris Lattner074be1f2004-11-15 04:44:20 +0000206 /// Solve - Solve for constants and executable blocks.
207 ///
208 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000209
Chris Lattner1847f6d2006-12-20 06:21:33 +0000210 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000211 /// that branches on undef values cannot reach any of their successors.
212 /// However, this is not a safe assumption. After we solve dataflow, this
213 /// method should be use to handle this. If this returns true, the solver
214 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000215 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000216
Chris Lattner074be1f2004-11-15 04:44:20 +0000217 /// getExecutableBlocks - Once we have solved for constants, return the set of
218 /// blocks that is known to be executable.
219 std::set<BasicBlock*> &getExecutableBlocks() {
220 return BBExecutable;
221 }
222
223 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000224 /// LLVM values to LatticeVals.
225 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000226 return ValueState;
227 }
228
Chris Lattner99e12952004-12-11 02:53:57 +0000229 /// getTrackedFunctionRetVals - Get the inferred return value map.
230 ///
231 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
232 return TrackedFunctionRetVals;
233 }
234
Chris Lattner91dbae62004-12-11 05:15:59 +0000235 /// getTrackedGlobals - Get and return the set of inferred initializers for
236 /// global variables.
237 const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
238 return TrackedGlobals;
239 }
240
Chris Lattner99e12952004-12-11 02:53:57 +0000241
Chris Lattner347389d2001-06-27 23:38:11 +0000242private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000243 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000244 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000245 // the users of the instruction are updated later.
246 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000247 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000248 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000249 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000250 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000251 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000252 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000253
254 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
255 IV.markForcedConstant(C);
256 DOUT << "markForcedConstant: " << *C << ": " << *V;
257 InstWorkList.push_back(V);
258 }
259
Chris Lattnerb4394642004-12-10 08:02:06 +0000260 inline void markConstant(Value *V, Constant *C) {
261 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000262 }
263
Chris Lattnerd79334d2004-07-15 23:36:43 +0000264 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000265 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000266 // work list so that the users of the instruction are updated later.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000267
Chris Lattnerb4394642004-12-10 08:02:06 +0000268 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000269 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000270 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000271 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000272 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000273 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000274 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000275 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000276 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000277 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000278 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000279 inline void markOverdefined(Value *V) {
280 markOverdefined(ValueState[V], V);
281 }
282
283 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
284 if (IV.isOverdefined() || MergeWithV.isUndefined())
285 return; // Noop.
286 if (MergeWithV.isOverdefined())
287 markOverdefined(IV, V);
288 else if (IV.isUndefined())
289 markConstant(IV, V, MergeWithV.getConstant());
290 else if (IV.getConstant() != MergeWithV.getConstant())
291 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000292 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000293
294 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
295 return mergeInValue(ValueState[V], V, MergeWithV);
296 }
297
Chris Lattner347389d2001-06-27 23:38:11 +0000298
Chris Lattner4f031622004-11-15 05:03:30 +0000299 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000300 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000301 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000302 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000303 // Instruction object, then use this accessor to get its value from the map.
304 //
Chris Lattner4f031622004-11-15 05:03:30 +0000305 inline LatticeVal &getValueState(Value *V) {
306 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000307 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000308
Chris Lattner1847f6d2006-12-20 06:21:33 +0000309 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000310 if (isa<UndefValue>(V)) {
311 // Nothing to do, remain undefined.
312 } else {
Chris Lattner1847f6d2006-12-20 06:21:33 +0000313 ValueState[C].markConstant(C); // Constants are constant
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000314 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000315 }
Chris Lattner347389d2001-06-27 23:38:11 +0000316 // All others are underdefined by default...
317 return ValueState[V];
318 }
319
Misha Brukmanb1c93172005-04-21 23:48:37 +0000320 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000321 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000322 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000323 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
324 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
325 return; // This edge is already known to be executable!
326
327 if (BBExecutable.count(Dest)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000328 DOUT << "Marking Edge Executable: " << Source->getName()
329 << " -> " << Dest->getName() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000330
331 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000332 // feasible that wasn't before. Revisit the PHI nodes in the block
333 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000334 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
335 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000336
337 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000338 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000339 }
Chris Lattner347389d2001-06-27 23:38:11 +0000340 }
341
Chris Lattner074be1f2004-11-15 04:44:20 +0000342 // getFeasibleSuccessors - Return a vector of booleans to indicate which
343 // successors are reachable from a given terminator instruction.
344 //
345 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
346
347 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
348 // block to the 'To' basic block is currently feasible...
349 //
350 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
351
352 // OperandChangedState - This method is invoked on all of the users of an
353 // instruction that was just changed state somehow.... Based on this
354 // information, we need to update the specified user of this instruction.
355 //
356 void OperandChangedState(User *U) {
357 // Only instructions use other variable values!
358 Instruction &I = cast<Instruction>(*U);
359 if (BBExecutable.count(I.getParent())) // Inst is executable?
360 visit(I);
361 }
362
363private:
364 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000365
Misha Brukmanb1c93172005-04-21 23:48:37 +0000366 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000367 // operand made a transition, or the instruction is newly executable. Change
368 // the value type of I to reflect these changes if appropriate.
369 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000370 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000371
372 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000373 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000374 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000375
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000376 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000377 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000378 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000379 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000380 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000381 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000382 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000383
384 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000385 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000386 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000387 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000388 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
389 void visitInvokeInst (InvokeInst &II) {
390 visitCallSite(CallSite::get(&II));
391 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000392 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000393 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000394 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000395 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000396 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000397 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
398 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000399 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000400
Chris Lattner113f4f42002-06-25 16:13:24 +0000401 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000402 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000403 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000404 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000405 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000406};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000407
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000408// getFeasibleSuccessors - Return a vector of booleans to indicate which
409// successors are reachable from a given terminator instruction.
410//
Chris Lattner074be1f2004-11-15 04:44:20 +0000411void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
412 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000413 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000414 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000415 if (BI->isUnconditional()) {
416 Succs[0] = true;
417 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000418 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000419 if (BCValue.isOverdefined() ||
Reid Spencercddc9df2007-01-12 04:24:46 +0000420 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000421 // Overdefined condition variables, and branches on unfoldable constant
422 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000423 Succs[0] = Succs[1] = true;
424 } else if (BCValue.isConstant()) {
425 // Constant condition variables mean the branch can only go a single way
Zhou Sheng75b871f2007-01-11 12:24:14 +0000426 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000427 }
428 }
Reid Spencerde46e482006-11-02 20:25:50 +0000429 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000430 // Invoke instructions successors are always executable.
431 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000432 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000433 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000434 if (SCValue.isOverdefined() || // Overdefined condition?
435 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000436 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000437 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000438 } else if (SCValue.isConstant()) {
439 Constant *CPV = SCValue.getConstant();
440 // Make sure to skip the "default value" which isn't a value
441 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
442 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
443 Succs[i] = true;
444 return;
445 }
446 }
447
448 // Constant value not equal to any of the branches... must execute
449 // default branch then...
450 Succs[0] = true;
451 }
452 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000453 cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000454 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000455 }
456}
457
458
Chris Lattner13b52e72002-05-02 21:18:01 +0000459// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
460// block to the 'To' basic block is currently feasible...
461//
Chris Lattner074be1f2004-11-15 04:44:20 +0000462bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000463 assert(BBExecutable.count(To) && "Dest should always be alive!");
464
465 // Make sure the source basic block is executable!!
466 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000467
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000468 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000469 TerminatorInst *TI = From->getTerminator();
470 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
471 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000472 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000473 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000474 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000475 if (BCValue.isOverdefined()) {
476 // Overdefined condition variables mean the branch could go either way.
477 return true;
478 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000479 // Not branching on an evaluatable constant?
Chris Lattnerff7434a2007-01-13 00:42:58 +0000480 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattnerfe992d42004-01-12 17:40:36 +0000481
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000482 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000483 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng75b871f2007-01-11 12:24:14 +0000484 ConstantInt::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000485 }
486 return false;
487 }
Reid Spencerde46e482006-11-02 20:25:50 +0000488 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000489 // Invoke instructions successors are always executable.
490 return true;
491 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000492 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000493 if (SCValue.isOverdefined()) { // Overdefined condition?
494 // All destinations are executable!
495 return true;
496 } else if (SCValue.isConstant()) {
497 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000498 if (!isa<ConstantInt>(CPV))
499 return true; // not a foldable constant?
500
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000501 // Make sure to skip the "default value" which isn't a value
502 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
503 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
504 return SI->getSuccessor(i) == To;
505
506 // Constant value not equal to any of the branches... must execute
507 // default branch then...
508 return SI->getDefaultDest() == To;
509 }
510 return false;
511 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000512 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000513 abort();
514 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000515}
Chris Lattner347389d2001-06-27 23:38:11 +0000516
Chris Lattner6e560792002-04-18 15:13:15 +0000517// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000518// operand made a transition, or the instruction is newly executable. Change
519// the value type of I to reflect these changes if appropriate. This method
520// makes sure to do the following actions:
521//
522// 1. If a phi node merges two constants in, and has conflicting value coming
523// from different branches, or if the PHI node merges in an overdefined
524// value, then the PHI node becomes overdefined.
525// 2. If a phi node merges only constants in, and they all agree on value, the
526// PHI node becomes a constant value equal to that.
527// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
528// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
529// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
530// 6. If a conditional branch has a value that is constant, make the selected
531// destination executable
532// 7. If a conditional branch has a value that is overdefined, make all
533// successors executable.
534//
Chris Lattner074be1f2004-11-15 04:44:20 +0000535void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000536 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000537 if (PNIV.isOverdefined()) {
538 // There may be instructions using this PHI node that are not overdefined
539 // themselves. If so, make sure that they know that the PHI node operand
540 // changed.
541 std::multimap<PHINode*, Instruction*>::iterator I, E;
542 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
543 if (I != E) {
544 std::vector<Instruction*> Users;
545 Users.reserve(std::distance(I, E));
546 for (; I != E; ++I) Users.push_back(I->second);
547 while (!Users.empty()) {
548 visit(Users.back());
549 Users.pop_back();
550 }
551 }
552 return; // Quick exit
553 }
Chris Lattner347389d2001-06-27 23:38:11 +0000554
Chris Lattner7a7b1142004-03-16 19:49:59 +0000555 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
556 // and slow us down a lot. Just mark them overdefined.
557 if (PN.getNumIncomingValues() > 64) {
558 markOverdefined(PNIV, &PN);
559 return;
560 }
561
Chris Lattner6e560792002-04-18 15:13:15 +0000562 // Look at all of the executable operands of the PHI node. If any of them
563 // are overdefined, the PHI becomes overdefined as well. If they are all
564 // constant, and they agree with each other, the PHI becomes the identical
565 // constant. If they are constant and don't agree, the PHI is overdefined.
566 // If there are no executable operands, the PHI remains undefined.
567 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000568 Constant *OperandVal = 0;
569 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000570 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000571 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000572
Chris Lattner113f4f42002-06-25 16:13:24 +0000573 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000574 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000575 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000576 return;
577 }
578
Chris Lattnercccc5c72003-04-25 02:50:03 +0000579 if (OperandVal == 0) { // Grab the first value...
580 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000581 } else { // Another value is being merged in!
582 // There is already a reachable operand. If we conflict with it,
583 // then the PHI node becomes overdefined. If we agree with it, we
584 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000585
Chris Lattner6e560792002-04-18 15:13:15 +0000586 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000587 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000588 // Yes there is. This means the PHI node is not constant.
589 // You must be overdefined poor PHI.
590 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000591 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000592 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000593 }
Chris Lattner347389d2001-06-27 23:38:11 +0000594 }
595 }
Chris Lattner347389d2001-06-27 23:38:11 +0000596 }
597
Chris Lattner6e560792002-04-18 15:13:15 +0000598 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000599 // arguments that agree with each other(and OperandVal is the constant) or
600 // OperandVal is null because there are no defined incoming arguments. If
601 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000602 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000603 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000604 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000605}
606
Chris Lattnerb4394642004-12-10 08:02:06 +0000607void SCCPSolver::visitReturnInst(ReturnInst &I) {
608 if (I.getNumOperands() == 0) return; // Ret void
609
610 // If we are tracking the return value of this function, merge it in.
611 Function *F = I.getParent()->getParent();
612 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
613 hash_map<Function*, LatticeVal>::iterator TFRVI =
614 TrackedFunctionRetVals.find(F);
615 if (TFRVI != TrackedFunctionRetVals.end() &&
616 !TFRVI->second.isOverdefined()) {
617 LatticeVal &IV = getValueState(I.getOperand(0));
618 mergeInValue(TFRVI->second, F, IV);
619 }
620 }
621}
622
623
Chris Lattner074be1f2004-11-15 04:44:20 +0000624void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000625 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000626 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000627
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000628 BasicBlock *BB = TI.getParent();
629
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000630 // Mark all feasible successors executable...
631 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000632 if (SuccFeasible[i])
633 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000634}
635
Chris Lattner074be1f2004-11-15 04:44:20 +0000636void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000637 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000638 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000639 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000640 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000641 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000642 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
643 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000644}
645
Chris Lattner074be1f2004-11-15 04:44:20 +0000646void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000647 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000648 if (CondValue.isUndefined())
649 return;
Reid Spencercddc9df2007-01-12 04:24:46 +0000650 if (CondValue.isConstant()) {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000651 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencercddc9df2007-01-12 04:24:46 +0000652 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng75b871f2007-01-11 12:24:14 +0000653 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000654 return;
655 }
656 }
657
658 // Otherwise, the condition is overdefined or a constant we can't evaluate.
659 // See if we can produce something better than overdefined based on the T/F
660 // value.
661 LatticeVal &TVal = getValueState(I.getTrueValue());
662 LatticeVal &FVal = getValueState(I.getFalseValue());
663
664 // select ?, C, C -> C.
665 if (TVal.isConstant() && FVal.isConstant() &&
666 TVal.getConstant() == FVal.getConstant()) {
667 markConstant(&I, FVal.getConstant());
668 return;
669 }
670
671 if (TVal.isUndefined()) { // select ?, undef, X -> X.
672 mergeInValue(&I, FVal);
673 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
674 mergeInValue(&I, TVal);
675 } else {
676 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000677 }
678}
679
Chris Lattner6e560792002-04-18 15:13:15 +0000680// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000681void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000682 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000683 if (IV.isOverdefined()) return;
684
Chris Lattner4f031622004-11-15 05:03:30 +0000685 LatticeVal &V1State = getValueState(I.getOperand(0));
686 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000687
Chris Lattner6e560792002-04-18 15:13:15 +0000688 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000689 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
690 // operand is overdefined.
691 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
692 LatticeVal *NonOverdefVal = 0;
693 if (!V1State.isOverdefined()) {
694 NonOverdefVal = &V1State;
695 } else if (!V2State.isOverdefined()) {
696 NonOverdefVal = &V2State;
697 }
698
699 if (NonOverdefVal) {
700 if (NonOverdefVal->isUndefined()) {
701 // Could annihilate value.
702 if (I.getOpcode() == Instruction::And)
703 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner806adaf2007-01-04 02:12:40 +0000704 else if (const PackedType *PT = dyn_cast<PackedType>(I.getType()))
705 markConstant(IV, &I, ConstantPacked::getAllOnesValue(PT));
706 else
707 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnercbc01612004-12-11 23:15:19 +0000708 return;
709 } else {
710 if (I.getOpcode() == Instruction::And) {
711 if (NonOverdefVal->getConstant()->isNullValue()) {
712 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskeyc4ba9c12007-01-03 00:11:03 +0000713 return; // X and 0 = 0
Chris Lattnercbc01612004-12-11 23:15:19 +0000714 }
715 } else {
Zhou Sheng75b871f2007-01-11 12:24:14 +0000716 if (ConstantInt *CI =
717 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnercbc01612004-12-11 23:15:19 +0000718 if (CI->isAllOnesValue()) {
719 markConstant(IV, &I, NonOverdefVal->getConstant());
720 return; // X or -1 = -1
721 }
722 }
723 }
724 }
725 }
726
727
Chris Lattner05fe6842004-01-12 03:57:30 +0000728 // If both operands are PHI nodes, it is possible that this instruction has
729 // a constant value, despite the fact that the PHI node doesn't. Check for
730 // this condition now.
731 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
732 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
733 if (PN1->getParent() == PN2->getParent()) {
734 // Since the two PHI nodes are in the same basic block, they must have
735 // entries for the same predecessors. Walk the predecessor list, and
736 // if all of the incoming values are constants, and the result of
737 // evaluating this expression with all incoming value pairs is the
738 // same, then this expression is a constant even though the PHI node
739 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000740 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000741 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000742 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000743 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000744 LatticeVal &In2 =
745 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000746
747 if (In1.isOverdefined() || In2.isOverdefined()) {
748 Result.markOverdefined();
749 break; // Cannot fold this operation over the PHI nodes!
750 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000751 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
752 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000753 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000754 Result.markConstant(V);
755 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000756 Result.markOverdefined();
757 break;
758 }
759 }
760 }
761
762 // If we found a constant value here, then we know the instruction is
763 // constant despite the fact that the PHI nodes are overdefined.
764 if (Result.isConstant()) {
765 markConstant(IV, &I, Result.getConstant());
766 // Remember that this instruction is virtually using the PHI node
767 // operands.
768 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
769 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
770 return;
771 } else if (Result.isUndefined()) {
772 return;
773 }
774
775 // Okay, this really is overdefined now. Since we might have
776 // speculatively thought that this was not overdefined before, and
777 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
778 // make sure to clean out any entries that we put there, for
779 // efficiency.
780 std::multimap<PHINode*, Instruction*>::iterator It, E;
781 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
782 while (It != E) {
783 if (It->second == &I) {
784 UsersOfOverdefinedPHIs.erase(It++);
785 } else
786 ++It;
787 }
788 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
789 while (It != E) {
790 if (It->second == &I) {
791 UsersOfOverdefinedPHIs.erase(It++);
792 } else
793 ++It;
794 }
795 }
796
797 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000798 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000799 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
800 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000801 }
802}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000803
Reid Spencer266e42b2006-12-23 06:05:41 +0000804// Handle ICmpInst instruction...
805void SCCPSolver::visitCmpInst(CmpInst &I) {
806 LatticeVal &IV = ValueState[&I];
807 if (IV.isOverdefined()) return;
808
809 LatticeVal &V1State = getValueState(I.getOperand(0));
810 LatticeVal &V2State = getValueState(I.getOperand(1));
811
812 if (V1State.isOverdefined() || V2State.isOverdefined()) {
813 // If both operands are PHI nodes, it is possible that this instruction has
814 // a constant value, despite the fact that the PHI node doesn't. Check for
815 // this condition now.
816 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
817 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
818 if (PN1->getParent() == PN2->getParent()) {
819 // Since the two PHI nodes are in the same basic block, they must have
820 // entries for the same predecessors. Walk the predecessor list, and
821 // if all of the incoming values are constants, and the result of
822 // evaluating this expression with all incoming value pairs is the
823 // same, then this expression is a constant even though the PHI node
824 // is not a constant!
825 LatticeVal Result;
826 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
827 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
828 BasicBlock *InBlock = PN1->getIncomingBlock(i);
829 LatticeVal &In2 =
830 getValueState(PN2->getIncomingValueForBlock(InBlock));
831
832 if (In1.isOverdefined() || In2.isOverdefined()) {
833 Result.markOverdefined();
834 break; // Cannot fold this operation over the PHI nodes!
835 } else if (In1.isConstant() && In2.isConstant()) {
836 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
837 In1.getConstant(),
838 In2.getConstant());
839 if (Result.isUndefined())
840 Result.markConstant(V);
841 else if (Result.isConstant() && Result.getConstant() != V) {
842 Result.markOverdefined();
843 break;
844 }
845 }
846 }
847
848 // If we found a constant value here, then we know the instruction is
849 // constant despite the fact that the PHI nodes are overdefined.
850 if (Result.isConstant()) {
851 markConstant(IV, &I, Result.getConstant());
852 // Remember that this instruction is virtually using the PHI node
853 // operands.
854 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
855 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
856 return;
857 } else if (Result.isUndefined()) {
858 return;
859 }
860
861 // Okay, this really is overdefined now. Since we might have
862 // speculatively thought that this was not overdefined before, and
863 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
864 // make sure to clean out any entries that we put there, for
865 // efficiency.
866 std::multimap<PHINode*, Instruction*>::iterator It, E;
867 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
868 while (It != E) {
869 if (It->second == &I) {
870 UsersOfOverdefinedPHIs.erase(It++);
871 } else
872 ++It;
873 }
874 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
875 while (It != E) {
876 if (It->second == &I) {
877 UsersOfOverdefinedPHIs.erase(It++);
878 } else
879 ++It;
880 }
881 }
882
883 markOverdefined(IV, &I);
884 } else if (V1State.isConstant() && V2State.isConstant()) {
885 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
886 V1State.getConstant(),
887 V2State.getConstant()));
888 }
889}
890
Robert Bocchinobd518d12006-01-10 19:05:05 +0000891void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000892 // FIXME : SCCP does not handle vectors properly.
893 markOverdefined(&I);
894 return;
895
896#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000897 LatticeVal &ValState = getValueState(I.getOperand(0));
898 LatticeVal &IdxState = getValueState(I.getOperand(1));
899
900 if (ValState.isOverdefined() || IdxState.isOverdefined())
901 markOverdefined(&I);
902 else if(ValState.isConstant() && IdxState.isConstant())
903 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
904 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000905#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000906}
907
Robert Bocchino6dce2502006-01-17 20:06:55 +0000908void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000909 // FIXME : SCCP does not handle vectors properly.
910 markOverdefined(&I);
911 return;
912#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000913 LatticeVal &ValState = getValueState(I.getOperand(0));
914 LatticeVal &EltState = getValueState(I.getOperand(1));
915 LatticeVal &IdxState = getValueState(I.getOperand(2));
916
917 if (ValState.isOverdefined() || EltState.isOverdefined() ||
918 IdxState.isOverdefined())
919 markOverdefined(&I);
920 else if(ValState.isConstant() && EltState.isConstant() &&
921 IdxState.isConstant())
922 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
923 EltState.getConstant(),
924 IdxState.getConstant()));
925 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +0000926 IdxState.isConstant())
Robert Bocchino6dce2502006-01-17 20:06:55 +0000927 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
928 EltState.getConstant(),
929 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000930#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000931}
932
Chris Lattner17bd6052006-04-08 01:19:12 +0000933void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000934 // FIXME : SCCP does not handle vectors properly.
935 markOverdefined(&I);
936 return;
937#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000938 LatticeVal &V1State = getValueState(I.getOperand(0));
939 LatticeVal &V2State = getValueState(I.getOperand(1));
940 LatticeVal &MaskState = getValueState(I.getOperand(2));
941
942 if (MaskState.isUndefined() ||
943 (V1State.isUndefined() && V2State.isUndefined()))
944 return; // Undefined output if mask or both inputs undefined.
945
946 if (V1State.isOverdefined() || V2State.isOverdefined() ||
947 MaskState.isOverdefined()) {
948 markOverdefined(&I);
949 } else {
950 // A mix of constant/undef inputs.
951 Constant *V1 = V1State.isConstant() ?
952 V1State.getConstant() : UndefValue::get(I.getType());
953 Constant *V2 = V2State.isConstant() ?
954 V2State.getConstant() : UndefValue::get(I.getType());
955 Constant *Mask = MaskState.isConstant() ?
956 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
957 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
958 }
Devang Patel21efc732006-12-04 23:54:59 +0000959#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000960}
961
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000962// Handle getelementptr instructions... if all operands are constants then we
963// can turn this into a getelementptr ConstantExpr.
964//
Chris Lattner074be1f2004-11-15 04:44:20 +0000965void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000966 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000967 if (IV.isOverdefined()) return;
968
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000969 std::vector<Constant*> Operands;
970 Operands.reserve(I.getNumOperands());
971
972 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000973 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000974 if (State.isUndefined())
975 return; // Operands are not resolved yet...
976 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000977 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000978 return;
979 }
980 assert(State.isConstant() && "Unknown state!");
981 Operands.push_back(State.getConstant());
982 }
983
984 Constant *Ptr = Operands[0];
985 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
986
Misha Brukmanb1c93172005-04-21 23:48:37 +0000987 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000988}
Brian Gaeke960707c2003-11-11 22:41:34 +0000989
Chris Lattner91dbae62004-12-11 05:15:59 +0000990void SCCPSolver::visitStoreInst(Instruction &SI) {
991 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
992 return;
993 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
994 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
995 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
996
997 // Get the value we are storing into the global.
998 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
999
1000 mergeInValue(I->second, GV, PtrVal);
1001 if (I->second.isOverdefined())
1002 TrackedGlobals.erase(I); // No need to keep tracking this!
1003}
1004
1005
Chris Lattner49f74522004-01-12 04:29:41 +00001006// Handle load instructions. If the operand is a constant pointer to a constant
1007// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001008void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +00001009 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001010 if (IV.isOverdefined()) return;
1011
Chris Lattner4f031622004-11-15 05:03:30 +00001012 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +00001013 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1014 if (PtrVal.isConstant() && !I.isVolatile()) {
1015 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +00001016 if (isa<ConstantPointerNull>(Ptr)) {
1017 // load null -> null
1018 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1019 return;
1020 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001021
Chris Lattner49f74522004-01-12 04:29:41 +00001022 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +00001023 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1024 if (GV->isConstant()) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001025 if (!GV->isDeclaration()) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001026 markConstant(IV, &I, GV->getInitializer());
1027 return;
1028 }
1029 } else if (!TrackedGlobals.empty()) {
1030 // If we are tracking this global, merge in the known value for it.
1031 hash_map<GlobalVariable*, LatticeVal>::iterator It =
1032 TrackedGlobals.find(GV);
1033 if (It != TrackedGlobals.end()) {
1034 mergeInValue(IV, &I, It->second);
1035 return;
1036 }
Chris Lattner49f74522004-01-12 04:29:41 +00001037 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001038 }
Chris Lattner49f74522004-01-12 04:29:41 +00001039
1040 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1041 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1042 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen82639852005-04-23 21:38:35 +00001043 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5301e7c2007-01-30 20:08:39 +00001044 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen82639852005-04-23 21:38:35 +00001045 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +00001046 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +00001047 markConstant(IV, &I, V);
1048 return;
1049 }
Chris Lattner49f74522004-01-12 04:29:41 +00001050 }
1051
1052 // Otherwise we cannot say for certain what value this load will produce.
1053 // Bail out.
1054 markOverdefined(IV, &I);
1055}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001056
Chris Lattnerb4394642004-12-10 08:02:06 +00001057void SCCPSolver::visitCallSite(CallSite CS) {
1058 Function *F = CS.getCalledFunction();
1059
1060 // If we are tracking this function, we must make sure to bind arguments as
1061 // appropriate.
1062 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
1063 if (F && F->hasInternalLinkage())
1064 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001065
Chris Lattnerb4394642004-12-10 08:02:06 +00001066 if (TFRVI != TrackedFunctionRetVals.end()) {
1067 // If this is the first call to the function hit, mark its entry block
1068 // executable.
1069 if (!BBExecutable.count(F->begin()))
1070 MarkBlockExecutable(F->begin());
1071
1072 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +00001073 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerb4394642004-12-10 08:02:06 +00001074 AI != E; ++AI, ++CAI) {
1075 LatticeVal &IV = ValueState[AI];
1076 if (!IV.isOverdefined())
1077 mergeInValue(IV, AI, getValueState(*CAI));
1078 }
1079 }
1080 Instruction *I = CS.getInstruction();
1081 if (I->getType() == Type::VoidTy) return;
1082
1083 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +00001084 if (IV.isOverdefined()) return;
1085
Chris Lattnerb4394642004-12-10 08:02:06 +00001086 // Propagate the return value of the function to the value of the instruction.
1087 if (TFRVI != TrackedFunctionRetVals.end()) {
1088 mergeInValue(IV, I, TFRVI->second);
1089 return;
1090 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001091
Reid Spencer5301e7c2007-01-30 20:08:39 +00001092 if (F == 0 || !F->isDeclaration() || !canConstantFoldCallTo(F)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001093 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001094 return;
1095 }
1096
Chris Lattner0d74d3c2007-01-30 23:15:19 +00001097 SmallVector<Constant*, 8> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +00001098 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001099
Chris Lattnerb4394642004-12-10 08:02:06 +00001100 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1101 AI != E; ++AI) {
1102 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001103 if (State.isUndefined())
1104 return; // Operands are not resolved yet...
1105 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001106 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001107 return;
1108 }
1109 assert(State.isConstant() && "Unknown state!");
1110 Operands.push_back(State.getConstant());
1111 }
1112
Chris Lattner0d74d3c2007-01-30 23:15:19 +00001113 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size()))
Chris Lattnerb4394642004-12-10 08:02:06 +00001114 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001115 else
Chris Lattnerb4394642004-12-10 08:02:06 +00001116 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001117}
Chris Lattner074be1f2004-11-15 04:44:20 +00001118
1119
1120void SCCPSolver::Solve() {
1121 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001122 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001123 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001124 // Process the instruction work list...
1125 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001126 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001127 OverdefinedInstWorkList.pop_back();
1128
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001129 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001130
Chris Lattner074be1f2004-11-15 04:44:20 +00001131 // "I" got into the work list because it either made the transition from
1132 // bottom to constant
1133 //
1134 // Anything on this worklist that is overdefined need not be visited
1135 // since all of its users will have already been marked as overdefined
1136 // Update all of the users of this instruction's value...
1137 //
1138 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1139 UI != E; ++UI)
1140 OperandChangedState(*UI);
1141 }
1142 // Process the instruction work list...
1143 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001144 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001145 InstWorkList.pop_back();
1146
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001147 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001148
Chris Lattner074be1f2004-11-15 04:44:20 +00001149 // "I" got into the work list because it either made the transition from
1150 // bottom to constant
1151 //
1152 // Anything on this worklist that is overdefined need not be visited
1153 // since all of its users will have already been marked as overdefined.
1154 // Update all of the users of this instruction's value...
1155 //
1156 if (!getValueState(I).isOverdefined())
1157 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1158 UI != E; ++UI)
1159 OperandChangedState(*UI);
1160 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001161
Chris Lattner074be1f2004-11-15 04:44:20 +00001162 // Process the basic block work list...
1163 while (!BBWorkList.empty()) {
1164 BasicBlock *BB = BBWorkList.back();
1165 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001166
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001167 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001168
Chris Lattner074be1f2004-11-15 04:44:20 +00001169 // Notify all instructions in this basic block that they are newly
1170 // executable.
1171 visit(BB);
1172 }
1173 }
1174}
1175
Chris Lattner1847f6d2006-12-20 06:21:33 +00001176/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001177/// that branches on undef values cannot reach any of their successors.
1178/// However, this is not a safe assumption. After we solve dataflow, this
1179/// method should be use to handle this. If this returns true, the solver
1180/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001181///
1182/// This method handles this by finding an unresolved branch and marking it one
1183/// of the edges from the block as being feasible, even though the condition
1184/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1185/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001186/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001187/// constraints on the condition of the branch, as that would impact other users
1188/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001189///
1190/// This scan also checks for values that use undefs, whose results are actually
1191/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1192/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1193/// even if X isn't defined.
1194bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001195 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1196 if (!BBExecutable.count(BB))
1197 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001198
1199 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1200 // Look for instructions which produce undef values.
1201 if (I->getType() == Type::VoidTy) continue;
1202
1203 LatticeVal &LV = getValueState(I);
1204 if (!LV.isUndefined()) continue;
1205
1206 // Get the lattice values of the first two operands for use below.
1207 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1208 LatticeVal Op1LV;
1209 if (I->getNumOperands() == 2) {
1210 // If this is a two-operand instruction, and if both operands are
1211 // undefs, the result stays undef.
1212 Op1LV = getValueState(I->getOperand(1));
1213 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1214 continue;
1215 }
1216
1217 // If this is an instructions whose result is defined even if the input is
1218 // not fully defined, propagate the information.
1219 const Type *ITy = I->getType();
1220 switch (I->getOpcode()) {
1221 default: break; // Leave the instruction as an undef.
1222 case Instruction::ZExt:
1223 // After a zero extend, we know the top part is zero. SExt doesn't have
1224 // to be handled here, because we don't know whether the top part is 1's
1225 // or 0's.
1226 assert(Op0LV.isUndefined());
1227 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1228 return true;
1229 case Instruction::Mul:
1230 case Instruction::And:
1231 // undef * X -> 0. X could be zero.
1232 // undef & X -> 0. X could be zero.
1233 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1234 return true;
1235
1236 case Instruction::Or:
1237 // undef | X -> -1. X could be -1.
Chris Lattner806adaf2007-01-04 02:12:40 +00001238 if (const PackedType *PTy = dyn_cast<PackedType>(ITy))
1239 markForcedConstant(LV, I, ConstantPacked::getAllOnesValue(PTy));
1240 else
1241 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1242 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001243
1244 case Instruction::SDiv:
1245 case Instruction::UDiv:
1246 case Instruction::SRem:
1247 case Instruction::URem:
1248 // X / undef -> undef. No change.
1249 // X % undef -> undef. No change.
1250 if (Op1LV.isUndefined()) break;
1251
1252 // undef / X -> 0. X could be maxint.
1253 // undef % X -> 0. X could be 1.
1254 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1255 return true;
1256
1257 case Instruction::AShr:
1258 // undef >>s X -> undef. No change.
1259 if (Op0LV.isUndefined()) break;
1260
1261 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1262 if (Op0LV.isConstant())
1263 markForcedConstant(LV, I, Op0LV.getConstant());
1264 else
1265 markOverdefined(LV, I);
1266 return true;
1267 case Instruction::LShr:
1268 case Instruction::Shl:
1269 // undef >> X -> undef. No change.
1270 // undef << X -> undef. No change.
1271 if (Op0LV.isUndefined()) break;
1272
1273 // X >> undef -> 0. X could be 0.
1274 // X << undef -> 0. X could be 0.
1275 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1276 return true;
1277 case Instruction::Select:
1278 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1279 if (Op0LV.isUndefined()) {
1280 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1281 Op1LV = getValueState(I->getOperand(2));
1282 } else if (Op1LV.isUndefined()) {
1283 // c ? undef : undef -> undef. No change.
1284 Op1LV = getValueState(I->getOperand(2));
1285 if (Op1LV.isUndefined())
1286 break;
1287 // Otherwise, c ? undef : x -> x.
1288 } else {
1289 // Leave Op1LV as Operand(1)'s LatticeValue.
1290 }
1291
1292 if (Op1LV.isConstant())
1293 markForcedConstant(LV, I, Op1LV.getConstant());
1294 else
1295 markOverdefined(LV, I);
1296 return true;
1297 }
1298 }
Chris Lattneraf170962006-10-22 05:59:17 +00001299
1300 TerminatorInst *TI = BB->getTerminator();
1301 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1302 if (!BI->isConditional()) continue;
1303 if (!getValueState(BI->getCondition()).isUndefined())
1304 continue;
1305 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1306 if (!getValueState(SI->getCondition()).isUndefined())
1307 continue;
1308 } else {
1309 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001310 }
Chris Lattneraf170962006-10-22 05:59:17 +00001311
1312 // If the edge to the first successor isn't thought to be feasible yet, mark
1313 // it so now.
1314 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1315 continue;
1316
1317 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1318 // and return. This will make other blocks reachable, which will allow new
1319 // values to be discovered and existing ones to be moved in the lattice.
1320 markEdgeExecutable(BB, TI->getSuccessor(0));
1321 return true;
1322 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001323
Chris Lattneraf170962006-10-22 05:59:17 +00001324 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001325}
1326
Chris Lattner074be1f2004-11-15 04:44:20 +00001327
1328namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001329 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001330 //
Chris Lattner1890f942004-11-15 07:15:04 +00001331 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001332 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001333 ///
1334 struct SCCP : public FunctionPass {
1335 // runOnFunction - Run the Sparse Conditional Constant Propagation
1336 // algorithm, and return true if the function was modified.
1337 //
1338 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339
Chris Lattner1890f942004-11-15 07:15:04 +00001340 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1341 AU.setPreservesCFG();
1342 }
1343 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001344
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001345 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001346} // end anonymous namespace
1347
1348
1349// createSCCPPass - This is the public interface to this file...
1350FunctionPass *llvm::createSCCPPass() {
1351 return new SCCP();
1352}
1353
1354
Chris Lattner074be1f2004-11-15 04:44:20 +00001355// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1356// and return true if the function was modified.
1357//
1358bool SCCP::runOnFunction(Function &F) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001359 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001360 SCCPSolver Solver;
1361
1362 // Mark the first block of the function as being executable.
1363 Solver.MarkBlockExecutable(F.begin());
1364
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001365 // Mark all arguments to the function as being overdefined.
1366 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner531f9e92005-03-15 04:54:21 +00001367 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001368 Values[AI].markOverdefined();
1369
Chris Lattner074be1f2004-11-15 04:44:20 +00001370 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001371 bool ResolvedUndefs = true;
1372 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001373 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001374 DOUT << "RESOLVING UNDEFs\n";
1375 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001376 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001377
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001378 bool MadeChanges = false;
1379
1380 // If we decided that there are basic blocks that are dead in this function,
1381 // delete their contents now. Note that we cannot actually delete the blocks,
1382 // as we cannot modify the CFG of the function.
1383 //
1384 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1385 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1386 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001387 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001388 ++NumDeadBlocks;
1389
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001390 // Delete the instructions backwards, as it has a reduced likelihood of
1391 // having to update as many def-use and use-def chains.
1392 std::vector<Instruction*> Insts;
1393 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1394 I != E; ++I)
1395 Insts.push_back(I);
1396 while (!Insts.empty()) {
1397 Instruction *I = Insts.back();
1398 Insts.pop_back();
1399 if (!I->use_empty())
1400 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1401 BB->getInstList().erase(I);
1402 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001403 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001404 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001405 } else {
1406 // Iterate over all of the instructions in a function, replacing them with
1407 // constants if we have found them to be of constant values.
1408 //
1409 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1410 Instruction *Inst = BI++;
1411 if (Inst->getType() != Type::VoidTy) {
1412 LatticeVal &IV = Values[Inst];
1413 if (IV.isConstant() || IV.isUndefined() &&
1414 !isa<TerminatorInst>(Inst)) {
1415 Constant *Const = IV.isConstant()
1416 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001417 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001418
Chris Lattnerb4394642004-12-10 08:02:06 +00001419 // Replaces all of the uses of a variable with uses of the constant.
1420 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001421
Chris Lattnerb4394642004-12-10 08:02:06 +00001422 // Delete the instruction.
1423 BB->getInstList().erase(Inst);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001424
Chris Lattnerb4394642004-12-10 08:02:06 +00001425 // Hey, we just changed something!
1426 MadeChanges = true;
1427 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001428 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001429 }
1430 }
1431 }
1432
1433 return MadeChanges;
1434}
Chris Lattnerb4394642004-12-10 08:02:06 +00001435
1436namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001437 //===--------------------------------------------------------------------===//
1438 //
1439 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1440 /// Constant Propagation.
1441 ///
1442 struct IPSCCP : public ModulePass {
1443 bool runOnModule(Module &M);
1444 };
1445
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001446 RegisterPass<IPSCCP>
Chris Lattnerb4394642004-12-10 08:02:06 +00001447 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1448} // end anonymous namespace
1449
1450// createIPSCCPPass - This is the public interface to this file...
1451ModulePass *llvm::createIPSCCPPass() {
1452 return new IPSCCP();
1453}
1454
1455
1456static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001457 // Delete any dead constantexpr klingons.
1458 GV->removeDeadConstantUsers();
1459
Chris Lattnerb4394642004-12-10 08:02:06 +00001460 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1461 UI != E; ++UI)
1462 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001463 if (SI->getOperand(0) == GV || SI->isVolatile())
1464 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001465 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1466 // Make sure we are calling the function, not passing the address.
1467 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1468 for (CallSite::arg_iterator AI = CS.arg_begin(),
1469 E = CS.arg_end(); AI != E; ++AI)
1470 if (*AI == GV)
1471 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001472 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1473 if (LI->isVolatile())
1474 return true;
1475 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001476 return true;
1477 }
1478 return false;
1479}
1480
1481bool IPSCCP::runOnModule(Module &M) {
1482 SCCPSolver Solver;
1483
1484 // Loop over all functions, marking arguments to those with their addresses
1485 // taken or that are external as overdefined.
1486 //
1487 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1488 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1489 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5301e7c2007-01-30 20:08:39 +00001490 if (!F->isDeclaration())
Chris Lattnerb4394642004-12-10 08:02:06 +00001491 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001492 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1493 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001494 Values[AI].markOverdefined();
1495 } else {
1496 Solver.AddTrackedFunction(F);
1497 }
1498
Chris Lattner91dbae62004-12-11 05:15:59 +00001499 // Loop over global variables. We inform the solver about any internal global
1500 // variables that do not have their 'addresses taken'. If they don't have
1501 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001502 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1503 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001504 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1505 Solver.TrackValueOfGlobalVariable(G);
1506
Chris Lattnerb4394642004-12-10 08:02:06 +00001507 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001508 bool ResolvedUndefs = true;
1509 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001510 Solver.Solve();
1511
Chris Lattner1847f6d2006-12-20 06:21:33 +00001512 DOUT << "RESOLVING UNDEFS\n";
1513 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001514 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001515 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001516 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001517
1518 bool MadeChanges = false;
1519
1520 // Iterate over all of the instructions in the module, replacing them with
1521 // constants if we have found them to be of constant values.
1522 //
1523 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1524 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001525 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1526 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001527 if (!AI->use_empty()) {
1528 LatticeVal &IV = Values[AI];
1529 if (IV.isConstant() || IV.isUndefined()) {
1530 Constant *CST = IV.isConstant() ?
1531 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001532 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001533
Chris Lattnerb4394642004-12-10 08:02:06 +00001534 // Replaces all of the uses of a variable with uses of the
1535 // constant.
1536 AI->replaceAllUsesWith(CST);
1537 ++IPNumArgsElimed;
1538 }
1539 }
1540
Chris Lattnerbae4b642004-12-10 22:29:08 +00001541 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001542 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1543 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001544 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001545 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001546
Chris Lattnerb4394642004-12-10 08:02:06 +00001547 // Delete the instructions backwards, as it has a reduced likelihood of
1548 // having to update as many def-use and use-def chains.
1549 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001550 TerminatorInst *TI = BB->getTerminator();
1551 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001552 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001553
Chris Lattnerb4394642004-12-10 08:02:06 +00001554 while (!Insts.empty()) {
1555 Instruction *I = Insts.back();
1556 Insts.pop_back();
1557 if (!I->use_empty())
1558 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1559 BB->getInstList().erase(I);
1560 MadeChanges = true;
1561 ++IPNumInstRemoved;
1562 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001563
Chris Lattnerbae4b642004-12-10 22:29:08 +00001564 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1565 BasicBlock *Succ = TI->getSuccessor(i);
1566 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1567 TI->getSuccessor(i)->removePredecessor(BB);
1568 }
Chris Lattner99e12952004-12-11 02:53:57 +00001569 if (!TI->use_empty())
1570 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001571 BB->getInstList().erase(TI);
1572
Chris Lattner8525ebe2004-12-11 05:32:19 +00001573 if (&*BB != &F->front())
1574 BlocksToErase.push_back(BB);
1575 else
1576 new UnreachableInst(BB);
1577
Chris Lattnerb4394642004-12-10 08:02:06 +00001578 } else {
1579 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1580 Instruction *Inst = BI++;
1581 if (Inst->getType() != Type::VoidTy) {
1582 LatticeVal &IV = Values[Inst];
1583 if (IV.isConstant() || IV.isUndefined() &&
1584 !isa<TerminatorInst>(Inst)) {
1585 Constant *Const = IV.isConstant()
1586 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001587 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001588
Chris Lattnerb4394642004-12-10 08:02:06 +00001589 // Replaces all of the uses of a variable with uses of the
1590 // constant.
1591 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001592
Chris Lattnerb4394642004-12-10 08:02:06 +00001593 // Delete the instruction.
1594 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1595 BB->getInstList().erase(Inst);
1596
1597 // Hey, we just changed something!
1598 MadeChanges = true;
1599 ++IPNumInstRemoved;
1600 }
1601 }
1602 }
1603 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001604
1605 // Now that all instructions in the function are constant folded, erase dead
1606 // blocks, because we can now use ConstantFoldTerminator to get rid of
1607 // in-edges.
1608 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1609 // If there are any PHI nodes in this successor, drop entries for BB now.
1610 BasicBlock *DeadBB = BlocksToErase[i];
1611 while (!DeadBB->use_empty()) {
1612 Instruction *I = cast<Instruction>(DeadBB->use_back());
1613 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001614 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001615 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001616 // if this is a branch or switch on undef. Fold it manually as a
1617 // branch to the first successor.
1618 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1619 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1620 "Branch should be foldable!");
1621 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1622 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1623 } else {
1624 assert(0 && "Didn't fold away reference to block!");
1625 }
1626
1627 // Make this an uncond branch to the first successor.
1628 TerminatorInst *TI = I->getParent()->getTerminator();
1629 new BranchInst(TI->getSuccessor(0), TI);
1630
1631 // Remove entries in successor phi nodes to remove edges.
1632 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1633 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1634
1635 // Remove the old terminator.
1636 TI->eraseFromParent();
1637 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001638 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001639
Chris Lattnerbae4b642004-12-10 22:29:08 +00001640 // Finally, delete the basic block.
1641 F->getBasicBlockList().erase(DeadBB);
1642 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001643 }
Chris Lattner99e12952004-12-11 02:53:57 +00001644
1645 // If we inferred constant or undef return values for a function, we replaced
1646 // all call uses with the inferred value. This means we don't need to bother
1647 // actually returning anything from the function. Replace all return
1648 // instructions with return undef.
1649 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1650 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1651 E = RV.end(); I != E; ++I)
1652 if (!I->second.isOverdefined() &&
1653 I->first->getReturnType() != Type::VoidTy) {
1654 Function *F = I->first;
1655 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1656 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1657 if (!isa<UndefValue>(RI->getOperand(0)))
1658 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1659 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001660
1661 // If we infered constant or undef values for globals variables, we can delete
1662 // the global and any stores that remain to it.
1663 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1664 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1665 E = TG.end(); I != E; ++I) {
1666 GlobalVariable *GV = I->first;
1667 assert(!I->second.isOverdefined() &&
1668 "Overdefined values should have been taken out of the map!");
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001669 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001670 while (!GV->use_empty()) {
1671 StoreInst *SI = cast<StoreInst>(GV->use_back());
1672 SI->eraseFromParent();
1673 }
1674 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001675 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001676 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001677
Chris Lattnerb4394642004-12-10 08:02:06 +00001678 return MadeChanges;
1679}