blob: 7da16157772d3b5c9bd93cf42cc9d77708ae4c26 [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 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 Lattner79a42ac2006-12-19 21:40:18 +000042STATISTIC(NumInstRemoved, "Number of instructions removed");
43STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
44
45STATISTIC(IPNumInstRemoved, "Number ofinstructions removed by IPSCCP");
46STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
47STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
48STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
49
Chris Lattner7d325382002-04-29 21:26:08 +000050namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000051/// LatticeVal class - This class represents the different lattice values that
52/// an LLVM value may occupy. It is a simple class with value semantics.
53///
Chris Lattner4f031622004-11-15 05:03:30 +000054class LatticeVal {
Misha Brukmanb1c93172005-04-21 23:48:37 +000055 enum {
Chris Lattner1847f6d2006-12-20 06:21:33 +000056 /// undefined - This LLVM Value has no known value yet.
57 undefined,
58
59 /// constant - This LLVM Value has a specific constant value.
60 constant,
61
62 /// forcedconstant - This LLVM Value was thought to be undef until
63 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
64 /// with another (different) constant, it goes to overdefined, instead of
65 /// asserting.
66 forcedconstant,
67
68 /// overdefined - This instruction is not known to be constant, and we know
69 /// it has a value.
70 overdefined
71 } LatticeValue; // The current lattice position
72
Chris Lattner3462ae32001-12-03 22:26:30 +000073 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner347389d2001-06-27 23:38:11 +000074public:
Chris Lattner4f031622004-11-15 05:03:30 +000075 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000076
Chris Lattner347389d2001-06-27 23:38:11 +000077 // markOverdefined - Return true if this is a new status to be in...
78 inline bool markOverdefined() {
Chris Lattner3462ae32001-12-03 22:26:30 +000079 if (LatticeValue != overdefined) {
80 LatticeValue = overdefined;
Chris Lattner347389d2001-06-27 23:38:11 +000081 return true;
82 }
83 return false;
84 }
85
Chris Lattner1847f6d2006-12-20 06:21:33 +000086 // markConstant - Return true if this is a new status for us.
Chris Lattner3462ae32001-12-03 22:26:30 +000087 inline bool markConstant(Constant *V) {
88 if (LatticeValue != constant) {
Chris Lattner1847f6d2006-12-20 06:21:33 +000089 if (LatticeValue == undefined) {
90 LatticeValue = constant;
91 ConstantVal = V;
92 } else {
93 assert(LatticeValue == forcedconstant &&
94 "Cannot move from overdefined to constant!");
95 // Stay at forcedconstant if the constant is the same.
96 if (V == ConstantVal) return false;
97
98 // Otherwise, we go to overdefined. Assumptions made based on the
99 // forced value are possibly wrong. Assuming this is another constant
100 // could expose a contradiction.
101 LatticeValue = overdefined;
102 }
Chris Lattner347389d2001-06-27 23:38:11 +0000103 return true;
104 } else {
Chris Lattnerdae05dc2001-09-07 16:43:22 +0000105 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner347389d2001-06-27 23:38:11 +0000106 }
107 return false;
108 }
109
Chris Lattner1847f6d2006-12-20 06:21:33 +0000110 inline void markForcedConstant(Constant *V) {
111 assert(LatticeValue == undefined && "Can't force a defined value!");
112 LatticeValue = forcedconstant;
113 ConstantVal = V;
114 }
115
116 inline bool isUndefined() const { return LatticeValue == undefined; }
117 inline bool isConstant() const {
118 return LatticeValue == constant || LatticeValue == forcedconstant;
119 }
Chris Lattner3462ae32001-12-03 22:26:30 +0000120 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner347389d2001-06-27 23:38:11 +0000121
Chris Lattner05fe6842004-01-12 03:57:30 +0000122 inline Constant *getConstant() const {
123 assert(isConstant() && "Cannot get the constant of a non-constant!");
124 return ConstantVal;
125 }
Chris Lattner347389d2001-06-27 23:38:11 +0000126};
127
Chris Lattner7d325382002-04-29 21:26:08 +0000128} // end anonymous namespace
Chris Lattner347389d2001-06-27 23:38:11 +0000129
130
131//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000132//
Chris Lattner074be1f2004-11-15 04:44:20 +0000133/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
134/// Constant Propagation.
135///
136class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner7f74a562002-01-20 22:54:45 +0000137 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner4f031622004-11-15 05:03:30 +0000138 hash_map<Value*, LatticeVal> ValueState; // The state each value is in...
Chris Lattner347389d2001-06-27 23:38:11 +0000139
Chris Lattner91dbae62004-12-11 05:15:59 +0000140 /// GlobalValue - If we are tracking any values for the contents of a global
141 /// variable, we keep a mapping from the constant accessor to the element of
142 /// the global, to the currently known value. If the value becomes
143 /// overdefined, it's entry is simply removed from this map.
144 hash_map<GlobalVariable*, LatticeVal> TrackedGlobals;
145
Chris Lattnerb4394642004-12-10 08:02:06 +0000146 /// TrackedFunctionRetVals - If we are tracking arguments into and the return
147 /// value out of a function, it will have an entry in this map, indicating
148 /// what the known return value for the function is.
149 hash_map<Function*, LatticeVal> TrackedFunctionRetVals;
150
Chris Lattnerd79334d2004-07-15 23:36:43 +0000151 // The reason for two worklists is that overdefined is the lowest state
152 // on the lattice, and moving things to overdefined as fast as possible
153 // makes SCCP converge much faster.
154 // By having a separate worklist, we accomplish this because everything
155 // possibly overdefined will become overdefined at the soonest possible
156 // point.
Chris Lattnerb4394642004-12-10 08:02:06 +0000157 std::vector<Value*> OverdefinedInstWorkList;
158 std::vector<Value*> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000159
160
Chris Lattner7f74a562002-01-20 22:54:45 +0000161 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000162
Chris Lattner05fe6842004-01-12 03:57:30 +0000163 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
164 /// overdefined, despite the fact that the PHI node is overdefined.
165 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
166
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000167 /// KnownFeasibleEdges - Entries in this set are edges which have already had
168 /// PHI nodes retriggered.
169 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
170 std::set<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000171public:
172
Chris Lattner074be1f2004-11-15 04:44:20 +0000173 /// MarkBlockExecutable - This method can be used by clients to mark all of
174 /// the blocks that are known to be intrinsically live in the processed unit.
175 void MarkBlockExecutable(BasicBlock *BB) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000176 DOUT << "Marking Block Executable: " << BB->getName() << "\n";
Chris Lattner074be1f2004-11-15 04:44:20 +0000177 BBExecutable.insert(BB); // Basic block is executable!
178 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner7d325382002-04-29 21:26:08 +0000179 }
180
Chris Lattner91dbae62004-12-11 05:15:59 +0000181 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000182 /// inform the SCCPSolver that it should track loads and stores to the
183 /// specified global variable if it can. This is only legal to call if
184 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000185 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
186 const Type *ElTy = GV->getType()->getElementType();
187 if (ElTy->isFirstClassType()) {
188 LatticeVal &IV = TrackedGlobals[GV];
189 if (!isa<UndefValue>(GV->getInitializer()))
190 IV.markConstant(GV->getInitializer());
191 }
192 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000193
194 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
195 /// and out of the specified function (which cannot have its address taken),
196 /// this method must be called.
197 void AddTrackedFunction(Function *F) {
198 assert(F->hasInternalLinkage() && "Can only track internal functions!");
199 // Add an entry, F -> undef.
200 TrackedFunctionRetVals[F];
201 }
202
Chris Lattner074be1f2004-11-15 04:44:20 +0000203 /// Solve - Solve for constants and executable blocks.
204 ///
205 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000206
Chris Lattner1847f6d2006-12-20 06:21:33 +0000207 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000208 /// that branches on undef values cannot reach any of their successors.
209 /// However, this is not a safe assumption. After we solve dataflow, this
210 /// method should be use to handle this. If this returns true, the solver
211 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000212 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000213
Chris Lattner074be1f2004-11-15 04:44:20 +0000214 /// getExecutableBlocks - Once we have solved for constants, return the set of
215 /// blocks that is known to be executable.
216 std::set<BasicBlock*> &getExecutableBlocks() {
217 return BBExecutable;
218 }
219
220 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattner4f031622004-11-15 05:03:30 +0000221 /// LLVM values to LatticeVals.
222 hash_map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner074be1f2004-11-15 04:44:20 +0000223 return ValueState;
224 }
225
Chris Lattner99e12952004-12-11 02:53:57 +0000226 /// getTrackedFunctionRetVals - Get the inferred return value map.
227 ///
228 const hash_map<Function*, LatticeVal> &getTrackedFunctionRetVals() {
229 return TrackedFunctionRetVals;
230 }
231
Chris Lattner91dbae62004-12-11 05:15:59 +0000232 /// getTrackedGlobals - Get and return the set of inferred initializers for
233 /// global variables.
234 const hash_map<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
235 return TrackedGlobals;
236 }
237
Chris Lattner99e12952004-12-11 02:53:57 +0000238
Chris Lattner347389d2001-06-27 23:38:11 +0000239private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000240 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000241 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000242 // the users of the instruction are updated later.
243 //
Chris Lattnerb4394642004-12-10 08:02:06 +0000244 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000245 if (IV.markConstant(C)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000246 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattnerb4394642004-12-10 08:02:06 +0000247 InstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000248 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000249 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000250
251 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
252 IV.markForcedConstant(C);
253 DOUT << "markForcedConstant: " << *C << ": " << *V;
254 InstWorkList.push_back(V);
255 }
256
Chris Lattnerb4394642004-12-10 08:02:06 +0000257 inline void markConstant(Value *V, Constant *C) {
258 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000259 }
260
Chris Lattnerd79334d2004-07-15 23:36:43 +0000261 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000262 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000263 // work list so that the users of the instruction are updated later.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000264
Chris Lattnerb4394642004-12-10 08:02:06 +0000265 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner7324f7c2003-10-08 16:21:03 +0000266 if (IV.markOverdefined()) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000267 DEBUG(DOUT << "markOverdefined: ";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000268 if (Function *F = dyn_cast<Function>(V))
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000269 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattner2f687fd2004-12-11 06:05:53 +0000270 else
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000271 DOUT << *V);
Chris Lattner074be1f2004-11-15 04:44:20 +0000272 // Only instructions go on the work list
Chris Lattnerb4394642004-12-10 08:02:06 +0000273 OverdefinedInstWorkList.push_back(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000274 }
Chris Lattner7324f7c2003-10-08 16:21:03 +0000275 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000276 inline void markOverdefined(Value *V) {
277 markOverdefined(ValueState[V], V);
278 }
279
280 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
281 if (IV.isOverdefined() || MergeWithV.isUndefined())
282 return; // Noop.
283 if (MergeWithV.isOverdefined())
284 markOverdefined(IV, V);
285 else if (IV.isUndefined())
286 markConstant(IV, V, MergeWithV.getConstant());
287 else if (IV.getConstant() != MergeWithV.getConstant())
288 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000289 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000290
291 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
292 return mergeInValue(ValueState[V], V, MergeWithV);
293 }
294
Chris Lattner347389d2001-06-27 23:38:11 +0000295
Chris Lattner4f031622004-11-15 05:03:30 +0000296 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman7eb05a12003-08-18 14:43:39 +0000297 // This function is necessary because not all values should start out in the
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000298 // underdefined state... Argument's should be overdefined, and
Chris Lattner57698e22002-03-26 18:01:55 +0000299 // constants should be marked as constants. If a value is not known to be an
Chris Lattner347389d2001-06-27 23:38:11 +0000300 // Instruction object, then use this accessor to get its value from the map.
301 //
Chris Lattner4f031622004-11-15 05:03:30 +0000302 inline LatticeVal &getValueState(Value *V) {
303 hash_map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner347389d2001-06-27 23:38:11 +0000304 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner646354b2004-10-16 18:09:41 +0000305
Chris Lattner1847f6d2006-12-20 06:21:33 +0000306 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000307 if (isa<UndefValue>(V)) {
308 // Nothing to do, remain undefined.
309 } else {
Chris Lattner1847f6d2006-12-20 06:21:33 +0000310 ValueState[C].markConstant(C); // Constants are constant
Chris Lattnerd18c16b2004-11-15 05:45:33 +0000311 }
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000312 }
Chris Lattner347389d2001-06-27 23:38:11 +0000313 // All others are underdefined by default...
314 return ValueState[V];
315 }
316
Misha Brukmanb1c93172005-04-21 23:48:37 +0000317 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner347389d2001-06-27 23:38:11 +0000318 // work list if it is not already executable...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000319 //
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000320 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
321 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
322 return; // This edge is already known to be executable!
323
324 if (BBExecutable.count(Dest)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000325 DOUT << "Marking Edge Executable: " << Source->getName()
326 << " -> " << Dest->getName() << "\n";
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000327
328 // The destination is already executable, but we just made an edge
Chris Lattner35e56e72003-10-08 16:56:11 +0000329 // feasible that wasn't before. Revisit the PHI nodes in the block
330 // because they have potentially new operands.
Chris Lattnerb4394642004-12-10 08:02:06 +0000331 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
332 visitPHINode(*cast<PHINode>(I));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000333
334 } else {
Chris Lattner074be1f2004-11-15 04:44:20 +0000335 MarkBlockExecutable(Dest);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000336 }
Chris Lattner347389d2001-06-27 23:38:11 +0000337 }
338
Chris Lattner074be1f2004-11-15 04:44:20 +0000339 // getFeasibleSuccessors - Return a vector of booleans to indicate which
340 // successors are reachable from a given terminator instruction.
341 //
342 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
343
344 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
345 // block to the 'To' basic block is currently feasible...
346 //
347 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
348
349 // OperandChangedState - This method is invoked on all of the users of an
350 // instruction that was just changed state somehow.... Based on this
351 // information, we need to update the specified user of this instruction.
352 //
353 void OperandChangedState(User *U) {
354 // Only instructions use other variable values!
355 Instruction &I = cast<Instruction>(*U);
356 if (BBExecutable.count(I.getParent())) // Inst is executable?
357 visit(I);
358 }
359
360private:
361 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000362
Misha Brukmanb1c93172005-04-21 23:48:37 +0000363 // visit implementations - Something changed in this instruction... Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000364 // operand made a transition, or the instruction is newly executable. Change
365 // the value type of I to reflect these changes if appropriate.
366 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000367 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000368
369 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000370 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000371 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000372
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000373 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000374 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000375 void visitBinaryOperator(Instruction &I);
376 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Robert Bocchinobd518d12006-01-10 19:05:05 +0000377 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000378 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000379 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000380
381 // Instructions that cannot be folded away...
Chris Lattner91dbae62004-12-11 05:15:59 +0000382 void visitStoreInst (Instruction &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000383 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000384 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattnerb4394642004-12-10 08:02:06 +0000385 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
386 void visitInvokeInst (InvokeInst &II) {
387 visitCallSite(CallSite::get(&II));
388 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000389 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000390 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000391 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000392 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner113f4f42002-06-25 16:13:24 +0000393 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnerf0fc9be2003-10-18 05:56:52 +0000394 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
395 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner113f4f42002-06-25 16:13:24 +0000396 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner6e560792002-04-18 15:13:15 +0000397
Chris Lattner113f4f42002-06-25 16:13:24 +0000398 void visitInstruction(Instruction &I) {
Chris Lattner6e560792002-04-18 15:13:15 +0000399 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlingf3baad32006-12-07 01:30:32 +0000400 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner113f4f42002-06-25 16:13:24 +0000401 markOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000402 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000403};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000404
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000405// getFeasibleSuccessors - Return a vector of booleans to indicate which
406// successors are reachable from a given terminator instruction.
407//
Chris Lattner074be1f2004-11-15 04:44:20 +0000408void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
409 std::vector<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000410 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000411 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000412 if (BI->isUnconditional()) {
413 Succs[0] = true;
414 } else {
Chris Lattner4f031622004-11-15 05:03:30 +0000415 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000416 if (BCValue.isOverdefined() ||
417 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
418 // Overdefined condition variables, and branches on unfoldable constant
419 // conditions, mean the branch could go either way.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000420 Succs[0] = Succs[1] = true;
421 } else if (BCValue.isConstant()) {
422 // Constant condition variables mean the branch can only go a single way
Chris Lattner6ab03f62006-09-28 23:35:22 +0000423 Succs[BCValue.getConstant() == ConstantBool::getFalse()] = true;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000424 }
425 }
Reid Spencerde46e482006-11-02 20:25:50 +0000426 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000427 // Invoke instructions successors are always executable.
428 Succs[0] = Succs[1] = true;
Chris Lattner113f4f42002-06-25 16:13:24 +0000429 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000430 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000431 if (SCValue.isOverdefined() || // Overdefined condition?
432 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000433 // All destinations are executable!
Chris Lattner113f4f42002-06-25 16:13:24 +0000434 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000435 } else if (SCValue.isConstant()) {
436 Constant *CPV = SCValue.getConstant();
437 // Make sure to skip the "default value" which isn't a value
438 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
439 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
440 Succs[i] = true;
441 return;
442 }
443 }
444
445 // Constant value not equal to any of the branches... must execute
446 // default branch then...
447 Succs[0] = true;
448 }
449 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000450 cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner113f4f42002-06-25 16:13:24 +0000451 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000452 }
453}
454
455
Chris Lattner13b52e72002-05-02 21:18:01 +0000456// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
457// block to the 'To' basic block is currently feasible...
458//
Chris Lattner074be1f2004-11-15 04:44:20 +0000459bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000460 assert(BBExecutable.count(To) && "Dest should always be alive!");
461
462 // Make sure the source basic block is executable!!
463 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000465 // Check to make sure this edge itself is actually feasible now...
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000466 TerminatorInst *TI = From->getTerminator();
467 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
468 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000469 return true;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000470 else {
Chris Lattner4f031622004-11-15 05:03:30 +0000471 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000472 if (BCValue.isOverdefined()) {
473 // Overdefined condition variables mean the branch could go either way.
474 return true;
475 } else if (BCValue.isConstant()) {
Chris Lattnerfe992d42004-01-12 17:40:36 +0000476 // Not branching on an evaluatable constant?
477 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
478
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000479 // Constant condition variables mean the branch can only go a single way
Misha Brukmanb1c93172005-04-21 23:48:37 +0000480 return BI->getSuccessor(BCValue.getConstant() ==
Chris Lattner6ab03f62006-09-28 23:35:22 +0000481 ConstantBool::getFalse()) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000482 }
483 return false;
484 }
Reid Spencerde46e482006-11-02 20:25:50 +0000485 } else if (isa<InvokeInst>(TI)) {
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000486 // Invoke instructions successors are always executable.
487 return true;
488 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner4f031622004-11-15 05:03:30 +0000489 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000490 if (SCValue.isOverdefined()) { // Overdefined condition?
491 // All destinations are executable!
492 return true;
493 } else if (SCValue.isConstant()) {
494 Constant *CPV = SCValue.getConstant();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000495 if (!isa<ConstantInt>(CPV))
496 return true; // not a foldable constant?
497
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000498 // Make sure to skip the "default value" which isn't a value
499 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
500 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
501 return SI->getSuccessor(i) == To;
502
503 // Constant value not equal to any of the branches... must execute
504 // default branch then...
505 return SI->getDefaultDest() == To;
506 }
507 return false;
508 } else {
Bill Wendlingf3baad32006-12-07 01:30:32 +0000509 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000510 abort();
511 }
Chris Lattner13b52e72002-05-02 21:18:01 +0000512}
Chris Lattner347389d2001-06-27 23:38:11 +0000513
Chris Lattner6e560792002-04-18 15:13:15 +0000514// visit Implementations - Something changed in this instruction... Either an
Chris Lattner347389d2001-06-27 23:38:11 +0000515// operand made a transition, or the instruction is newly executable. Change
516// the value type of I to reflect these changes if appropriate. This method
517// makes sure to do the following actions:
518//
519// 1. If a phi node merges two constants in, and has conflicting value coming
520// from different branches, or if the PHI node merges in an overdefined
521// value, then the PHI node becomes overdefined.
522// 2. If a phi node merges only constants in, and they all agree on value, the
523// PHI node becomes a constant value equal to that.
524// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
525// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
526// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
527// 6. If a conditional branch has a value that is constant, make the selected
528// destination executable
529// 7. If a conditional branch has a value that is overdefined, make all
530// successors executable.
531//
Chris Lattner074be1f2004-11-15 04:44:20 +0000532void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner4f031622004-11-15 05:03:30 +0000533 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner05fe6842004-01-12 03:57:30 +0000534 if (PNIV.isOverdefined()) {
535 // There may be instructions using this PHI node that are not overdefined
536 // themselves. If so, make sure that they know that the PHI node operand
537 // changed.
538 std::multimap<PHINode*, Instruction*>::iterator I, E;
539 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
540 if (I != E) {
541 std::vector<Instruction*> Users;
542 Users.reserve(std::distance(I, E));
543 for (; I != E; ++I) Users.push_back(I->second);
544 while (!Users.empty()) {
545 visit(Users.back());
546 Users.pop_back();
547 }
548 }
549 return; // Quick exit
550 }
Chris Lattner347389d2001-06-27 23:38:11 +0000551
Chris Lattner7a7b1142004-03-16 19:49:59 +0000552 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
553 // and slow us down a lot. Just mark them overdefined.
554 if (PN.getNumIncomingValues() > 64) {
555 markOverdefined(PNIV, &PN);
556 return;
557 }
558
Chris Lattner6e560792002-04-18 15:13:15 +0000559 // Look at all of the executable operands of the PHI node. If any of them
560 // are overdefined, the PHI becomes overdefined as well. If they are all
561 // constant, and they agree with each other, the PHI becomes the identical
562 // constant. If they are constant and don't agree, the PHI is overdefined.
563 // If there are no executable operands, the PHI remains undefined.
564 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000565 Constant *OperandVal = 0;
566 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000567 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000568 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000569
Chris Lattner113f4f42002-06-25 16:13:24 +0000570 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner7e270582003-06-24 20:29:52 +0000571 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner7324f7c2003-10-08 16:21:03 +0000572 markOverdefined(PNIV, &PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000573 return;
574 }
575
Chris Lattnercccc5c72003-04-25 02:50:03 +0000576 if (OperandVal == 0) { // Grab the first value...
577 OperandVal = IV.getConstant();
Chris Lattner6e560792002-04-18 15:13:15 +0000578 } else { // Another value is being merged in!
579 // There is already a reachable operand. If we conflict with it,
580 // then the PHI node becomes overdefined. If we agree with it, we
581 // can continue on.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000582
Chris Lattner6e560792002-04-18 15:13:15 +0000583 // Check to see if there are two different constants merging...
Chris Lattnercccc5c72003-04-25 02:50:03 +0000584 if (IV.getConstant() != OperandVal) {
Chris Lattner6e560792002-04-18 15:13:15 +0000585 // Yes there is. This means the PHI node is not constant.
586 // You must be overdefined poor PHI.
587 //
Chris Lattner7324f7c2003-10-08 16:21:03 +0000588 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner6e560792002-04-18 15:13:15 +0000589 return; // I'm done analyzing you
Chris Lattnerc4ad64c2001-11-26 18:57:38 +0000590 }
Chris Lattner347389d2001-06-27 23:38:11 +0000591 }
592 }
Chris Lattner347389d2001-06-27 23:38:11 +0000593 }
594
Chris Lattner6e560792002-04-18 15:13:15 +0000595 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000596 // arguments that agree with each other(and OperandVal is the constant) or
597 // OperandVal is null because there are no defined incoming arguments. If
598 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000599 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000600 if (OperandVal)
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000601 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000602}
603
Chris Lattnerb4394642004-12-10 08:02:06 +0000604void SCCPSolver::visitReturnInst(ReturnInst &I) {
605 if (I.getNumOperands() == 0) return; // Ret void
606
607 // If we are tracking the return value of this function, merge it in.
608 Function *F = I.getParent()->getParent();
609 if (F->hasInternalLinkage() && !TrackedFunctionRetVals.empty()) {
610 hash_map<Function*, LatticeVal>::iterator TFRVI =
611 TrackedFunctionRetVals.find(F);
612 if (TFRVI != TrackedFunctionRetVals.end() &&
613 !TFRVI->second.isOverdefined()) {
614 LatticeVal &IV = getValueState(I.getOperand(0));
615 mergeInValue(TFRVI->second, F, IV);
616 }
617 }
618}
619
620
Chris Lattner074be1f2004-11-15 04:44:20 +0000621void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000622 std::vector<bool> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000623 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000624
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000625 BasicBlock *BB = TI.getParent();
626
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000627 // Mark all feasible successors executable...
628 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000629 if (SuccFeasible[i])
630 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000631}
632
Chris Lattner074be1f2004-11-15 04:44:20 +0000633void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000634 Value *V = I.getOperand(0);
Chris Lattner4f031622004-11-15 05:03:30 +0000635 LatticeVal &VState = getValueState(V);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000636 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000637 markOverdefined(&I);
Chris Lattner0fe5b322004-01-12 17:43:40 +0000638 else if (VState.isConstant()) // Propagate constant value
Reid Spencerb341b082006-12-12 05:05:00 +0000639 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
640 VState.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000641}
642
Chris Lattner074be1f2004-11-15 04:44:20 +0000643void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000644 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000645 if (CondValue.isUndefined())
646 return;
647 if (CondValue.isConstant()) {
Chris Lattner6ab03f62006-09-28 23:35:22 +0000648 if (ConstantBool *CondCB = dyn_cast<ConstantBool>(CondValue.getConstant())){
649 mergeInValue(&I, getValueState(CondCB->getValue() ? I.getTrueValue()
650 : I.getFalseValue()));
Chris Lattner06a0ed12006-02-08 02:38:11 +0000651 return;
652 }
653 }
654
655 // Otherwise, the condition is overdefined or a constant we can't evaluate.
656 // See if we can produce something better than overdefined based on the T/F
657 // value.
658 LatticeVal &TVal = getValueState(I.getTrueValue());
659 LatticeVal &FVal = getValueState(I.getFalseValue());
660
661 // select ?, C, C -> C.
662 if (TVal.isConstant() && FVal.isConstant() &&
663 TVal.getConstant() == FVal.getConstant()) {
664 markConstant(&I, FVal.getConstant());
665 return;
666 }
667
668 if (TVal.isUndefined()) { // select ?, undef, X -> X.
669 mergeInValue(&I, FVal);
670 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
671 mergeInValue(&I, TVal);
672 } else {
673 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000674 }
675}
676
Chris Lattner6e560792002-04-18 15:13:15 +0000677// Handle BinaryOperators and Shift Instructions...
Chris Lattner074be1f2004-11-15 04:44:20 +0000678void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000679 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000680 if (IV.isOverdefined()) return;
681
Chris Lattner4f031622004-11-15 05:03:30 +0000682 LatticeVal &V1State = getValueState(I.getOperand(0));
683 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner05fe6842004-01-12 03:57:30 +0000684
Chris Lattner6e560792002-04-18 15:13:15 +0000685 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnercbc01612004-12-11 23:15:19 +0000686 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
687 // operand is overdefined.
688 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
689 LatticeVal *NonOverdefVal = 0;
690 if (!V1State.isOverdefined()) {
691 NonOverdefVal = &V1State;
692 } else if (!V2State.isOverdefined()) {
693 NonOverdefVal = &V2State;
694 }
695
696 if (NonOverdefVal) {
697 if (NonOverdefVal->isUndefined()) {
698 // Could annihilate value.
699 if (I.getOpcode() == Instruction::And)
700 markConstant(IV, &I, Constant::getNullValue(I.getType()));
701 else
702 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
703 return;
704 } else {
705 if (I.getOpcode() == Instruction::And) {
706 if (NonOverdefVal->getConstant()->isNullValue()) {
707 markConstant(IV, &I, NonOverdefVal->getConstant());
708 return; // X or 0 = -1
709 }
710 } else {
711 if (ConstantIntegral *CI =
712 dyn_cast<ConstantIntegral>(NonOverdefVal->getConstant()))
713 if (CI->isAllOnesValue()) {
714 markConstant(IV, &I, NonOverdefVal->getConstant());
715 return; // X or -1 = -1
716 }
717 }
718 }
719 }
720 }
721
722
Chris Lattner05fe6842004-01-12 03:57:30 +0000723 // If both operands are PHI nodes, it is possible that this instruction has
724 // a constant value, despite the fact that the PHI node doesn't. Check for
725 // this condition now.
726 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
727 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
728 if (PN1->getParent() == PN2->getParent()) {
729 // Since the two PHI nodes are in the same basic block, they must have
730 // entries for the same predecessors. Walk the predecessor list, and
731 // if all of the incoming values are constants, and the result of
732 // evaluating this expression with all incoming value pairs is the
733 // same, then this expression is a constant even though the PHI node
734 // is not a constant!
Chris Lattner4f031622004-11-15 05:03:30 +0000735 LatticeVal Result;
Chris Lattner05fe6842004-01-12 03:57:30 +0000736 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000737 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner05fe6842004-01-12 03:57:30 +0000738 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattner4f031622004-11-15 05:03:30 +0000739 LatticeVal &In2 =
740 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000741
742 if (In1.isOverdefined() || In2.isOverdefined()) {
743 Result.markOverdefined();
744 break; // Cannot fold this operation over the PHI nodes!
745 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000746 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
747 In2.getConstant());
Chris Lattner05fe6842004-01-12 03:57:30 +0000748 if (Result.isUndefined())
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000749 Result.markConstant(V);
750 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000751 Result.markOverdefined();
752 break;
753 }
754 }
755 }
756
757 // If we found a constant value here, then we know the instruction is
758 // constant despite the fact that the PHI nodes are overdefined.
759 if (Result.isConstant()) {
760 markConstant(IV, &I, Result.getConstant());
761 // Remember that this instruction is virtually using the PHI node
762 // operands.
763 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
764 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
765 return;
766 } else if (Result.isUndefined()) {
767 return;
768 }
769
770 // Okay, this really is overdefined now. Since we might have
771 // speculatively thought that this was not overdefined before, and
772 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
773 // make sure to clean out any entries that we put there, for
774 // efficiency.
775 std::multimap<PHINode*, Instruction*>::iterator It, E;
776 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
777 while (It != E) {
778 if (It->second == &I) {
779 UsersOfOverdefinedPHIs.erase(It++);
780 } else
781 ++It;
782 }
783 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
784 while (It != E) {
785 if (It->second == &I) {
786 UsersOfOverdefinedPHIs.erase(It++);
787 } else
788 ++It;
789 }
790 }
791
792 markOverdefined(IV, &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000793 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattner1b7d4d72004-01-12 19:08:43 +0000794 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
795 V2State.getConstant()));
Chris Lattner6e560792002-04-18 15:13:15 +0000796 }
797}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000798
Robert Bocchinobd518d12006-01-10 19:05:05 +0000799void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000800 // FIXME : SCCP does not handle vectors properly.
801 markOverdefined(&I);
802 return;
803
804#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000805 LatticeVal &ValState = getValueState(I.getOperand(0));
806 LatticeVal &IdxState = getValueState(I.getOperand(1));
807
808 if (ValState.isOverdefined() || IdxState.isOverdefined())
809 markOverdefined(&I);
810 else if(ValState.isConstant() && IdxState.isConstant())
811 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
812 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000813#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000814}
815
Robert Bocchino6dce2502006-01-17 20:06:55 +0000816void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000817 // FIXME : SCCP does not handle vectors properly.
818 markOverdefined(&I);
819 return;
820#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000821 LatticeVal &ValState = getValueState(I.getOperand(0));
822 LatticeVal &EltState = getValueState(I.getOperand(1));
823 LatticeVal &IdxState = getValueState(I.getOperand(2));
824
825 if (ValState.isOverdefined() || EltState.isOverdefined() ||
826 IdxState.isOverdefined())
827 markOverdefined(&I);
828 else if(ValState.isConstant() && EltState.isConstant() &&
829 IdxState.isConstant())
830 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
831 EltState.getConstant(),
832 IdxState.getConstant()));
833 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +0000834 IdxState.isConstant())
Robert Bocchino6dce2502006-01-17 20:06:55 +0000835 markConstant(&I, ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
836 EltState.getConstant(),
837 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000838#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000839}
840
Chris Lattner17bd6052006-04-08 01:19:12 +0000841void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel21efc732006-12-04 23:54:59 +0000842 // FIXME : SCCP does not handle vectors properly.
843 markOverdefined(&I);
844 return;
845#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000846 LatticeVal &V1State = getValueState(I.getOperand(0));
847 LatticeVal &V2State = getValueState(I.getOperand(1));
848 LatticeVal &MaskState = getValueState(I.getOperand(2));
849
850 if (MaskState.isUndefined() ||
851 (V1State.isUndefined() && V2State.isUndefined()))
852 return; // Undefined output if mask or both inputs undefined.
853
854 if (V1State.isOverdefined() || V2State.isOverdefined() ||
855 MaskState.isOverdefined()) {
856 markOverdefined(&I);
857 } else {
858 // A mix of constant/undef inputs.
859 Constant *V1 = V1State.isConstant() ?
860 V1State.getConstant() : UndefValue::get(I.getType());
861 Constant *V2 = V2State.isConstant() ?
862 V2State.getConstant() : UndefValue::get(I.getType());
863 Constant *Mask = MaskState.isConstant() ?
864 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
865 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
866 }
Devang Patel21efc732006-12-04 23:54:59 +0000867#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000868}
869
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000870// Handle getelementptr instructions... if all operands are constants then we
871// can turn this into a getelementptr ConstantExpr.
872//
Chris Lattner074be1f2004-11-15 04:44:20 +0000873void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000874 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000875 if (IV.isOverdefined()) return;
876
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000877 std::vector<Constant*> Operands;
878 Operands.reserve(I.getNumOperands());
879
880 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner4f031622004-11-15 05:03:30 +0000881 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000882 if (State.isUndefined())
883 return; // Operands are not resolved yet...
884 else if (State.isOverdefined()) {
Chris Lattner49f74522004-01-12 04:29:41 +0000885 markOverdefined(IV, &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000886 return;
887 }
888 assert(State.isConstant() && "Unknown state!");
889 Operands.push_back(State.getConstant());
890 }
891
892 Constant *Ptr = Operands[0];
893 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
894
Misha Brukmanb1c93172005-04-21 23:48:37 +0000895 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000896}
Brian Gaeke960707c2003-11-11 22:41:34 +0000897
Chris Lattner91dbae62004-12-11 05:15:59 +0000898void SCCPSolver::visitStoreInst(Instruction &SI) {
899 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
900 return;
901 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
902 hash_map<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
903 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
904
905 // Get the value we are storing into the global.
906 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
907
908 mergeInValue(I->second, GV, PtrVal);
909 if (I->second.isOverdefined())
910 TrackedGlobals.erase(I); // No need to keep tracking this!
911}
912
913
Chris Lattner49f74522004-01-12 04:29:41 +0000914// Handle load instructions. If the operand is a constant pointer to a constant
915// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +0000916void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner4f031622004-11-15 05:03:30 +0000917 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +0000918 if (IV.isOverdefined()) return;
919
Chris Lattner4f031622004-11-15 05:03:30 +0000920 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattner49f74522004-01-12 04:29:41 +0000921 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
922 if (PtrVal.isConstant() && !I.isVolatile()) {
923 Value *Ptr = PtrVal.getConstant();
Chris Lattner538fee72004-03-07 22:16:24 +0000924 if (isa<ConstantPointerNull>(Ptr)) {
925 // load null -> null
926 markConstant(IV, &I, Constant::getNullValue(I.getType()));
927 return;
928 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000929
Chris Lattner49f74522004-01-12 04:29:41 +0000930 // Transform load (constant global) into the value loaded.
Chris Lattner91dbae62004-12-11 05:15:59 +0000931 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
932 if (GV->isConstant()) {
933 if (!GV->isExternal()) {
934 markConstant(IV, &I, GV->getInitializer());
935 return;
936 }
937 } else if (!TrackedGlobals.empty()) {
938 // If we are tracking this global, merge in the known value for it.
939 hash_map<GlobalVariable*, LatticeVal>::iterator It =
940 TrackedGlobals.find(GV);
941 if (It != TrackedGlobals.end()) {
942 mergeInValue(IV, &I, It->second);
943 return;
944 }
Chris Lattner49f74522004-01-12 04:29:41 +0000945 }
Chris Lattner91dbae62004-12-11 05:15:59 +0000946 }
Chris Lattner49f74522004-01-12 04:29:41 +0000947
948 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
949 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
950 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen82639852005-04-23 21:38:35 +0000951 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
952 if (GV->isConstant() && !GV->isExternal())
953 if (Constant *V =
Chris Lattner02ae21e2005-09-26 05:28:52 +0000954 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen82639852005-04-23 21:38:35 +0000955 markConstant(IV, &I, V);
956 return;
957 }
Chris Lattner49f74522004-01-12 04:29:41 +0000958 }
959
960 // Otherwise we cannot say for certain what value this load will produce.
961 // Bail out.
962 markOverdefined(IV, &I);
963}
Chris Lattnerff9362a2004-04-13 19:43:54 +0000964
Chris Lattnerb4394642004-12-10 08:02:06 +0000965void SCCPSolver::visitCallSite(CallSite CS) {
966 Function *F = CS.getCalledFunction();
967
968 // If we are tracking this function, we must make sure to bind arguments as
969 // appropriate.
970 hash_map<Function*, LatticeVal>::iterator TFRVI =TrackedFunctionRetVals.end();
971 if (F && F->hasInternalLinkage())
972 TFRVI = TrackedFunctionRetVals.find(F);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000973
Chris Lattnerb4394642004-12-10 08:02:06 +0000974 if (TFRVI != TrackedFunctionRetVals.end()) {
975 // If this is the first call to the function hit, mark its entry block
976 // executable.
977 if (!BBExecutable.count(F->begin()))
978 MarkBlockExecutable(F->begin());
979
980 CallSite::arg_iterator CAI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000981 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerb4394642004-12-10 08:02:06 +0000982 AI != E; ++AI, ++CAI) {
983 LatticeVal &IV = ValueState[AI];
984 if (!IV.isOverdefined())
985 mergeInValue(IV, AI, getValueState(*CAI));
986 }
987 }
988 Instruction *I = CS.getInstruction();
989 if (I->getType() == Type::VoidTy) return;
990
991 LatticeVal &IV = ValueState[I];
Chris Lattnerff9362a2004-04-13 19:43:54 +0000992 if (IV.isOverdefined()) return;
993
Chris Lattnerb4394642004-12-10 08:02:06 +0000994 // Propagate the return value of the function to the value of the instruction.
995 if (TFRVI != TrackedFunctionRetVals.end()) {
996 mergeInValue(IV, I, TFRVI->second);
997 return;
998 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000999
Chris Lattnerb4394642004-12-10 08:02:06 +00001000 if (F == 0 || !F->isExternal() || !canConstantFoldCallTo(F)) {
1001 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001002 return;
1003 }
1004
1005 std::vector<Constant*> Operands;
Chris Lattnerb4394642004-12-10 08:02:06 +00001006 Operands.reserve(I->getNumOperands()-1);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001007
Chris Lattnerb4394642004-12-10 08:02:06 +00001008 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1009 AI != E; ++AI) {
1010 LatticeVal &State = getValueState(*AI);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001011 if (State.isUndefined())
1012 return; // Operands are not resolved yet...
1013 else if (State.isOverdefined()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001014 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001015 return;
1016 }
1017 assert(State.isConstant() && "Unknown state!");
1018 Operands.push_back(State.getConstant());
1019 }
1020
1021 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattnerb4394642004-12-10 08:02:06 +00001022 markConstant(IV, I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001023 else
Chris Lattnerb4394642004-12-10 08:02:06 +00001024 markOverdefined(IV, I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001025}
Chris Lattner074be1f2004-11-15 04:44:20 +00001026
1027
1028void SCCPSolver::Solve() {
1029 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001030 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001031 !OverdefinedInstWorkList.empty()) {
Chris Lattner074be1f2004-11-15 04:44:20 +00001032 // Process the instruction work list...
1033 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001034 Value *I = OverdefinedInstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001035 OverdefinedInstWorkList.pop_back();
1036
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001037 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001038
Chris Lattner074be1f2004-11-15 04:44:20 +00001039 // "I" got into the work list because it either made the transition from
1040 // bottom to constant
1041 //
1042 // Anything on this worklist that is overdefined need not be visited
1043 // since all of its users will have already been marked as overdefined
1044 // Update all of the users of this instruction's value...
1045 //
1046 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1047 UI != E; ++UI)
1048 OperandChangedState(*UI);
1049 }
1050 // Process the instruction work list...
1051 while (!InstWorkList.empty()) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001052 Value *I = InstWorkList.back();
Chris Lattner074be1f2004-11-15 04:44:20 +00001053 InstWorkList.pop_back();
1054
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001055 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001056
Chris Lattner074be1f2004-11-15 04:44:20 +00001057 // "I" got into the work list because it either made the transition from
1058 // bottom to constant
1059 //
1060 // Anything on this worklist that is overdefined need not be visited
1061 // since all of its users will have already been marked as overdefined.
1062 // Update all of the users of this instruction's value...
1063 //
1064 if (!getValueState(I).isOverdefined())
1065 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1066 UI != E; ++UI)
1067 OperandChangedState(*UI);
1068 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001069
Chris Lattner074be1f2004-11-15 04:44:20 +00001070 // Process the basic block work list...
1071 while (!BBWorkList.empty()) {
1072 BasicBlock *BB = BBWorkList.back();
1073 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001074
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001075 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001076
Chris Lattner074be1f2004-11-15 04:44:20 +00001077 // Notify all instructions in this basic block that they are newly
1078 // executable.
1079 visit(BB);
1080 }
1081 }
1082}
1083
Chris Lattner1847f6d2006-12-20 06:21:33 +00001084/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001085/// that branches on undef values cannot reach any of their successors.
1086/// However, this is not a safe assumption. After we solve dataflow, this
1087/// method should be use to handle this. If this returns true, the solver
1088/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001089///
1090/// This method handles this by finding an unresolved branch and marking it one
1091/// of the edges from the block as being feasible, even though the condition
1092/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1093/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001094/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001095/// constraints on the condition of the branch, as that would impact other users
1096/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001097///
1098/// This scan also checks for values that use undefs, whose results are actually
1099/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1100/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1101/// even if X isn't defined.
1102bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001103 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1104 if (!BBExecutable.count(BB))
1105 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001106
1107 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1108 // Look for instructions which produce undef values.
1109 if (I->getType() == Type::VoidTy) continue;
1110
1111 LatticeVal &LV = getValueState(I);
1112 if (!LV.isUndefined()) continue;
1113
1114 // Get the lattice values of the first two operands for use below.
1115 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1116 LatticeVal Op1LV;
1117 if (I->getNumOperands() == 2) {
1118 // If this is a two-operand instruction, and if both operands are
1119 // undefs, the result stays undef.
1120 Op1LV = getValueState(I->getOperand(1));
1121 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1122 continue;
1123 }
1124
1125 // If this is an instructions whose result is defined even if the input is
1126 // not fully defined, propagate the information.
1127 const Type *ITy = I->getType();
1128 switch (I->getOpcode()) {
1129 default: break; // Leave the instruction as an undef.
1130 case Instruction::ZExt:
1131 // After a zero extend, we know the top part is zero. SExt doesn't have
1132 // to be handled here, because we don't know whether the top part is 1's
1133 // or 0's.
1134 assert(Op0LV.isUndefined());
1135 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1136 return true;
1137 case Instruction::Mul:
1138 case Instruction::And:
1139 // undef * X -> 0. X could be zero.
1140 // undef & X -> 0. X could be zero.
1141 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1142 return true;
1143
1144 case Instruction::Or:
1145 // undef | X -> -1. X could be -1.
1146 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1147 return true;
1148
1149 case Instruction::SDiv:
1150 case Instruction::UDiv:
1151 case Instruction::SRem:
1152 case Instruction::URem:
1153 // X / undef -> undef. No change.
1154 // X % undef -> undef. No change.
1155 if (Op1LV.isUndefined()) break;
1156
1157 // undef / X -> 0. X could be maxint.
1158 // undef % X -> 0. X could be 1.
1159 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1160 return true;
1161
1162 case Instruction::AShr:
1163 // undef >>s X -> undef. No change.
1164 if (Op0LV.isUndefined()) break;
1165
1166 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1167 if (Op0LV.isConstant())
1168 markForcedConstant(LV, I, Op0LV.getConstant());
1169 else
1170 markOverdefined(LV, I);
1171 return true;
1172 case Instruction::LShr:
1173 case Instruction::Shl:
1174 // undef >> X -> undef. No change.
1175 // undef << X -> undef. No change.
1176 if (Op0LV.isUndefined()) break;
1177
1178 // X >> undef -> 0. X could be 0.
1179 // X << undef -> 0. X could be 0.
1180 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1181 return true;
1182 case Instruction::Select:
1183 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1184 if (Op0LV.isUndefined()) {
1185 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1186 Op1LV = getValueState(I->getOperand(2));
1187 } else if (Op1LV.isUndefined()) {
1188 // c ? undef : undef -> undef. No change.
1189 Op1LV = getValueState(I->getOperand(2));
1190 if (Op1LV.isUndefined())
1191 break;
1192 // Otherwise, c ? undef : x -> x.
1193 } else {
1194 // Leave Op1LV as Operand(1)'s LatticeValue.
1195 }
1196
1197 if (Op1LV.isConstant())
1198 markForcedConstant(LV, I, Op1LV.getConstant());
1199 else
1200 markOverdefined(LV, I);
1201 return true;
1202 }
1203 }
Chris Lattneraf170962006-10-22 05:59:17 +00001204
1205 TerminatorInst *TI = BB->getTerminator();
1206 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1207 if (!BI->isConditional()) continue;
1208 if (!getValueState(BI->getCondition()).isUndefined())
1209 continue;
1210 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1211 if (!getValueState(SI->getCondition()).isUndefined())
1212 continue;
1213 } else {
1214 continue;
Chris Lattner7285f432004-12-10 20:41:50 +00001215 }
Chris Lattneraf170962006-10-22 05:59:17 +00001216
1217 // If the edge to the first successor isn't thought to be feasible yet, mark
1218 // it so now.
1219 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(0))))
1220 continue;
1221
1222 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1223 // and return. This will make other blocks reachable, which will allow new
1224 // values to be discovered and existing ones to be moved in the lattice.
1225 markEdgeExecutable(BB, TI->getSuccessor(0));
1226 return true;
1227 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001228
Chris Lattneraf170962006-10-22 05:59:17 +00001229 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001230}
1231
Chris Lattner074be1f2004-11-15 04:44:20 +00001232
1233namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001234 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001235 //
Chris Lattner1890f942004-11-15 07:15:04 +00001236 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1237 /// Sparse Conditional COnstant Propagator.
1238 ///
1239 struct SCCP : public FunctionPass {
1240 // runOnFunction - Run the Sparse Conditional Constant Propagation
1241 // algorithm, and return true if the function was modified.
1242 //
1243 bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001244
Chris Lattner1890f942004-11-15 07:15:04 +00001245 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1246 AU.setPreservesCFG();
1247 }
1248 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001249
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001250 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner074be1f2004-11-15 04:44:20 +00001251} // end anonymous namespace
1252
1253
1254// createSCCPPass - This is the public interface to this file...
1255FunctionPass *llvm::createSCCPPass() {
1256 return new SCCP();
1257}
1258
1259
Chris Lattner074be1f2004-11-15 04:44:20 +00001260// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1261// and return true if the function was modified.
1262//
1263bool SCCP::runOnFunction(Function &F) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001264 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner074be1f2004-11-15 04:44:20 +00001265 SCCPSolver Solver;
1266
1267 // Mark the first block of the function as being executable.
1268 Solver.MarkBlockExecutable(F.begin());
1269
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001270 // Mark all arguments to the function as being overdefined.
1271 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner531f9e92005-03-15 04:54:21 +00001272 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E; ++AI)
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001273 Values[AI].markOverdefined();
1274
Chris Lattner074be1f2004-11-15 04:44:20 +00001275 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001276 bool ResolvedUndefs = true;
1277 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001278 Solver.Solve();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001279 DOUT << "RESOLVING UNDEFs\n";
1280 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001281 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001282
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001283 bool MadeChanges = false;
1284
1285 // If we decided that there are basic blocks that are dead in this function,
1286 // delete their contents now. Note that we cannot actually delete the blocks,
1287 // as we cannot modify the CFG of the function.
1288 //
1289 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1290 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1291 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001292 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner9a038a32004-11-15 07:02:42 +00001293 ++NumDeadBlocks;
1294
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001295 // Delete the instructions backwards, as it has a reduced likelihood of
1296 // having to update as many def-use and use-def chains.
1297 std::vector<Instruction*> Insts;
1298 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1299 I != E; ++I)
1300 Insts.push_back(I);
1301 while (!Insts.empty()) {
1302 Instruction *I = Insts.back();
1303 Insts.pop_back();
1304 if (!I->use_empty())
1305 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1306 BB->getInstList().erase(I);
1307 MadeChanges = true;
Chris Lattner9a038a32004-11-15 07:02:42 +00001308 ++NumInstRemoved;
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001309 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001310 } else {
1311 // Iterate over all of the instructions in a function, replacing them with
1312 // constants if we have found them to be of constant values.
1313 //
1314 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1315 Instruction *Inst = BI++;
1316 if (Inst->getType() != Type::VoidTy) {
1317 LatticeVal &IV = Values[Inst];
1318 if (IV.isConstant() || IV.isUndefined() &&
1319 !isa<TerminatorInst>(Inst)) {
1320 Constant *Const = IV.isConstant()
1321 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001322 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001323
Chris Lattnerb4394642004-12-10 08:02:06 +00001324 // Replaces all of the uses of a variable with uses of the constant.
1325 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001326
Chris Lattnerb4394642004-12-10 08:02:06 +00001327 // Delete the instruction.
1328 BB->getInstList().erase(Inst);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001329
Chris Lattnerb4394642004-12-10 08:02:06 +00001330 // Hey, we just changed something!
1331 MadeChanges = true;
1332 ++NumInstRemoved;
Chris Lattner074be1f2004-11-15 04:44:20 +00001333 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001334 }
1335 }
1336 }
1337
1338 return MadeChanges;
1339}
Chris Lattnerb4394642004-12-10 08:02:06 +00001340
1341namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001342 //===--------------------------------------------------------------------===//
1343 //
1344 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1345 /// Constant Propagation.
1346 ///
1347 struct IPSCCP : public ModulePass {
1348 bool runOnModule(Module &M);
1349 };
1350
Chris Lattnerc2d3d312006-08-27 22:42:52 +00001351 RegisterPass<IPSCCP>
Chris Lattnerb4394642004-12-10 08:02:06 +00001352 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1353} // end anonymous namespace
1354
1355// createIPSCCPPass - This is the public interface to this file...
1356ModulePass *llvm::createIPSCCPPass() {
1357 return new IPSCCP();
1358}
1359
1360
1361static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001362 // Delete any dead constantexpr klingons.
1363 GV->removeDeadConstantUsers();
1364
Chris Lattnerb4394642004-12-10 08:02:06 +00001365 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1366 UI != E; ++UI)
1367 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001368 if (SI->getOperand(0) == GV || SI->isVolatile())
1369 return true; // Storing addr of GV.
Chris Lattnerb4394642004-12-10 08:02:06 +00001370 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1371 // Make sure we are calling the function, not passing the address.
1372 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1373 for (CallSite::arg_iterator AI = CS.arg_begin(),
1374 E = CS.arg_end(); AI != E; ++AI)
1375 if (*AI == GV)
1376 return true;
Chris Lattner91dbae62004-12-11 05:15:59 +00001377 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1378 if (LI->isVolatile())
1379 return true;
1380 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001381 return true;
1382 }
1383 return false;
1384}
1385
1386bool IPSCCP::runOnModule(Module &M) {
1387 SCCPSolver Solver;
1388
1389 // Loop over all functions, marking arguments to those with their addresses
1390 // taken or that are external as overdefined.
1391 //
1392 hash_map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1393 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1394 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1395 if (!F->isExternal())
1396 Solver.MarkBlockExecutable(F->begin());
Chris Lattner8cb10a12005-04-19 19:16:19 +00001397 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1398 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001399 Values[AI].markOverdefined();
1400 } else {
1401 Solver.AddTrackedFunction(F);
1402 }
1403
Chris Lattner91dbae62004-12-11 05:15:59 +00001404 // Loop over global variables. We inform the solver about any internal global
1405 // variables that do not have their 'addresses taken'. If they don't have
1406 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001407 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1408 G != E; ++G)
Chris Lattner91dbae62004-12-11 05:15:59 +00001409 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1410 Solver.TrackValueOfGlobalVariable(G);
1411
Chris Lattnerb4394642004-12-10 08:02:06 +00001412 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001413 bool ResolvedUndefs = true;
1414 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001415 Solver.Solve();
1416
Chris Lattner1847f6d2006-12-20 06:21:33 +00001417 DOUT << "RESOLVING UNDEFS\n";
1418 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001419 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001420 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001421 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001422
1423 bool MadeChanges = false;
1424
1425 // Iterate over all of the instructions in the module, replacing them with
1426 // constants if we have found them to be of constant values.
1427 //
1428 std::set<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1429 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001430 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1431 AI != E; ++AI)
Chris Lattnerb4394642004-12-10 08:02:06 +00001432 if (!AI->use_empty()) {
1433 LatticeVal &IV = Values[AI];
1434 if (IV.isConstant() || IV.isUndefined()) {
1435 Constant *CST = IV.isConstant() ?
1436 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001437 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanb1c93172005-04-21 23:48:37 +00001438
Chris Lattnerb4394642004-12-10 08:02:06 +00001439 // Replaces all of the uses of a variable with uses of the
1440 // constant.
1441 AI->replaceAllUsesWith(CST);
1442 ++IPNumArgsElimed;
1443 }
1444 }
1445
Chris Lattnerbae4b642004-12-10 22:29:08 +00001446 std::vector<BasicBlock*> BlocksToErase;
Chris Lattnerb4394642004-12-10 08:02:06 +00001447 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1448 if (!ExecutableBBs.count(BB)) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001449 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb4394642004-12-10 08:02:06 +00001450 ++IPNumDeadBlocks;
Chris Lattner7285f432004-12-10 20:41:50 +00001451
Chris Lattnerb4394642004-12-10 08:02:06 +00001452 // Delete the instructions backwards, as it has a reduced likelihood of
1453 // having to update as many def-use and use-def chains.
1454 std::vector<Instruction*> Insts;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001455 TerminatorInst *TI = BB->getTerminator();
1456 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattnerb4394642004-12-10 08:02:06 +00001457 Insts.push_back(I);
Chris Lattnerbae4b642004-12-10 22:29:08 +00001458
Chris Lattnerb4394642004-12-10 08:02:06 +00001459 while (!Insts.empty()) {
1460 Instruction *I = Insts.back();
1461 Insts.pop_back();
1462 if (!I->use_empty())
1463 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1464 BB->getInstList().erase(I);
1465 MadeChanges = true;
1466 ++IPNumInstRemoved;
1467 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001468
Chris Lattnerbae4b642004-12-10 22:29:08 +00001469 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1470 BasicBlock *Succ = TI->getSuccessor(i);
1471 if (Succ->begin() != Succ->end() && isa<PHINode>(Succ->begin()))
1472 TI->getSuccessor(i)->removePredecessor(BB);
1473 }
Chris Lattner99e12952004-12-11 02:53:57 +00001474 if (!TI->use_empty())
1475 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnerbae4b642004-12-10 22:29:08 +00001476 BB->getInstList().erase(TI);
1477
Chris Lattner8525ebe2004-12-11 05:32:19 +00001478 if (&*BB != &F->front())
1479 BlocksToErase.push_back(BB);
1480 else
1481 new UnreachableInst(BB);
1482
Chris Lattnerb4394642004-12-10 08:02:06 +00001483 } else {
1484 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1485 Instruction *Inst = BI++;
1486 if (Inst->getType() != Type::VoidTy) {
1487 LatticeVal &IV = Values[Inst];
1488 if (IV.isConstant() || IV.isUndefined() &&
1489 !isa<TerminatorInst>(Inst)) {
1490 Constant *Const = IV.isConstant()
1491 ? IV.getConstant() : UndefValue::get(Inst->getType());
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001492 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001493
Chris Lattnerb4394642004-12-10 08:02:06 +00001494 // Replaces all of the uses of a variable with uses of the
1495 // constant.
1496 Inst->replaceAllUsesWith(Const);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001497
Chris Lattnerb4394642004-12-10 08:02:06 +00001498 // Delete the instruction.
1499 if (!isa<TerminatorInst>(Inst) && !isa<CallInst>(Inst))
1500 BB->getInstList().erase(Inst);
1501
1502 // Hey, we just changed something!
1503 MadeChanges = true;
1504 ++IPNumInstRemoved;
1505 }
1506 }
1507 }
1508 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001509
1510 // Now that all instructions in the function are constant folded, erase dead
1511 // blocks, because we can now use ConstantFoldTerminator to get rid of
1512 // in-edges.
1513 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1514 // If there are any PHI nodes in this successor, drop entries for BB now.
1515 BasicBlock *DeadBB = BlocksToErase[i];
1516 while (!DeadBB->use_empty()) {
1517 Instruction *I = cast<Instruction>(DeadBB->use_back());
1518 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001519 if (!Folded) {
1520 // The constant folder may not have been able to fold the termiantor
1521 // if this is a branch or switch on undef. Fold it manually as a
1522 // branch to the first successor.
1523 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1524 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1525 "Branch should be foldable!");
1526 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1527 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1528 } else {
1529 assert(0 && "Didn't fold away reference to block!");
1530 }
1531
1532 // Make this an uncond branch to the first successor.
1533 TerminatorInst *TI = I->getParent()->getTerminator();
1534 new BranchInst(TI->getSuccessor(0), TI);
1535
1536 // Remove entries in successor phi nodes to remove edges.
1537 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1538 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1539
1540 // Remove the old terminator.
1541 TI->eraseFromParent();
1542 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001543 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001544
Chris Lattnerbae4b642004-12-10 22:29:08 +00001545 // Finally, delete the basic block.
1546 F->getBasicBlockList().erase(DeadBB);
1547 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001548 }
Chris Lattner99e12952004-12-11 02:53:57 +00001549
1550 // If we inferred constant or undef return values for a function, we replaced
1551 // all call uses with the inferred value. This means we don't need to bother
1552 // actually returning anything from the function. Replace all return
1553 // instructions with return undef.
1554 const hash_map<Function*, LatticeVal> &RV =Solver.getTrackedFunctionRetVals();
1555 for (hash_map<Function*, LatticeVal>::const_iterator I = RV.begin(),
1556 E = RV.end(); I != E; ++I)
1557 if (!I->second.isOverdefined() &&
1558 I->first->getReturnType() != Type::VoidTy) {
1559 Function *F = I->first;
1560 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1561 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1562 if (!isa<UndefValue>(RI->getOperand(0)))
1563 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1564 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001565
1566 // If we infered constant or undef values for globals variables, we can delete
1567 // the global and any stores that remain to it.
1568 const hash_map<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1569 for (hash_map<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1570 E = TG.end(); I != E; ++I) {
1571 GlobalVariable *GV = I->first;
1572 assert(!I->second.isOverdefined() &&
1573 "Overdefined values should have been taken out of the map!");
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001574 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattner91dbae62004-12-11 05:15:59 +00001575 while (!GV->use_empty()) {
1576 StoreInst *SI = cast<StoreInst>(GV->use_back());
1577 SI->eraseFromParent();
1578 }
1579 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001580 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001581 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001582
Chris Lattnerb4394642004-12-10 08:02:06 +00001583 return MadeChanges;
1584}