blob: 168e54484dabb565750d8783841362a6315ad81d [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-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 Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-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 Lattneref36dfd2004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000031#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000033#include "llvm/Support/CallSite.h"
Reid Spencer9133fe22007-02-05 23:32:05 +000034#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/Debug.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000036#include "llvm/Support/InstVisitor.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnercc56aad2007-02-02 20:57:39 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000042#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000043#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumInstRemoved, "Number of instructions removed");
47STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
48
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000049STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
51STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
Chris Lattner0dbfc052002-04-29 21:26:08 +000054namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000055/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Reid Spencer9133fe22007-02-05 23:32:05 +000058class VISIBILITY_HIDDEN LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000059 enum {
Chris Lattner3bad2532006-12-20 06:21:33 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
75 } LatticeValue; // The current lattice position
76
Chris Lattnere9bb2df2001-12-03 22:26:30 +000077 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000078public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000079 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner138a1242001-06-27 23:38:11 +000081 // markOverdefined - Return true if this is a new status to be in...
82 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000083 if (LatticeValue != overdefined) {
84 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000085 return true;
86 }
87 return false;
88 }
89
Chris Lattner3bad2532006-12-20 06:21:33 +000090 // markConstant - Return true if this is a new status for us.
Chris Lattnere9bb2df2001-12-03 22:26:30 +000091 inline bool markConstant(Constant *V) {
92 if (LatticeValue != constant) {
Chris Lattner3bad2532006-12-20 06:21:33 +000093 if (LatticeValue == undefined) {
94 LatticeValue = constant;
Jim Laskey52ab9042007-01-03 00:11:03 +000095 assert(V && "Marking constant with NULL");
Chris Lattner3bad2532006-12-20 06:21:33 +000096 ConstantVal = V;
97 } else {
98 assert(LatticeValue == forcedconstant &&
99 "Cannot move from overdefined to constant!");
100 // Stay at forcedconstant if the constant is the same.
101 if (V == ConstantVal) return false;
102
103 // Otherwise, we go to overdefined. Assumptions made based on the
104 // forced value are possibly wrong. Assuming this is another constant
105 // could expose a contradiction.
106 LatticeValue = overdefined;
107 }
Chris Lattner138a1242001-06-27 23:38:11 +0000108 return true;
109 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000110 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +0000111 }
112 return false;
113 }
114
Chris Lattner3bad2532006-12-20 06:21:33 +0000115 inline void markForcedConstant(Constant *V) {
116 assert(LatticeValue == undefined && "Can't force a defined value!");
117 LatticeValue = forcedconstant;
118 ConstantVal = V;
119 }
120
121 inline bool isUndefined() const { return LatticeValue == undefined; }
122 inline bool isConstant() const {
123 return LatticeValue == constant || LatticeValue == forcedconstant;
124 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000125 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +0000126
Chris Lattner1daee8b2004-01-12 03:57:30 +0000127 inline Constant *getConstant() const {
128 assert(isConstant() && "Cannot get the constant of a non-constant!");
129 return ConstantVal;
130 }
Chris Lattner138a1242001-06-27 23:38:11 +0000131};
132
Chris Lattner138a1242001-06-27 23:38:11 +0000133//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000134//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000135/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
136/// Constant Propagation.
137///
138class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnercc56aad2007-02-02 20:57:39 +0000139 SmallSet<BasicBlock*, 16> BBExecutable;// The basic blocks that are executable
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000140 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000141
Chris Lattnerdd336d12004-12-11 05:15:59 +0000142 /// GlobalValue - If we are tracking any values for the contents of a global
143 /// variable, we keep a mapping from the constant accessor to the element of
144 /// the global, to the currently known value. If the value becomes
145 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000146 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000147
Devang Patel7c490d42008-03-11 05:46:42 +0000148 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000149 /// value out of a function, it will have an entry in this map, indicating
150 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000151 DenseMap<Function*, LatticeVal> TrackedRetVals;
152
153 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
154 /// that return multiple values.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000155 std::map<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000156
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000157 // The reason for two worklists is that overdefined is the lowest state
158 // on the lattice, and moving things to overdefined as fast as possible
159 // makes SCCP converge much faster.
160 // By having a separate worklist, we accomplish this because everything
161 // possibly overdefined will become overdefined at the soonest possible
162 // point.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000163 std::vector<Value*> OverdefinedInstWorkList;
164 std::vector<Value*> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000165
166
Chris Lattner697954c2002-01-20 22:54:45 +0000167 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000168
Chris Lattner1daee8b2004-01-12 03:57:30 +0000169 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
170 /// overdefined, despite the fact that the PHI node is overdefined.
171 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
172
Chris Lattner16b18fd2003-10-08 16:55:34 +0000173 /// KnownFeasibleEdges - Entries in this set are edges which have already had
174 /// PHI nodes retriggered.
175 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
176 std::set<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000177public:
178
Chris Lattner82bec2c2004-11-15 04:44:20 +0000179 /// MarkBlockExecutable - This method can be used by clients to mark all of
180 /// the blocks that are known to be intrinsically live in the processed unit.
181 void MarkBlockExecutable(BasicBlock *BB) {
Chris Lattner5c8e8d72008-05-11 01:55:59 +0000182 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +0000183 BBExecutable.insert(BB); // Basic block is executable!
184 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000185 }
186
Chris Lattnerdd336d12004-12-11 05:15:59 +0000187 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000188 /// inform the SCCPSolver that it should track loads and stores to the
189 /// specified global variable if it can. This is only legal to call if
190 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000191 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
192 const Type *ElTy = GV->getType()->getElementType();
193 if (ElTy->isFirstClassType()) {
194 LatticeVal &IV = TrackedGlobals[GV];
195 if (!isa<UndefValue>(GV->getInitializer()))
196 IV.markConstant(GV->getInitializer());
197 }
198 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000199
200 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
201 /// and out of the specified function (which cannot have its address taken),
202 /// this method must be called.
203 void AddTrackedFunction(Function *F) {
204 assert(F->hasInternalLinkage() && "Can only track internal functions!");
205 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000206 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
207 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000208 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
209 LatticeVal()));
210 } else
211 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000212 }
213
Chris Lattner82bec2c2004-11-15 04:44:20 +0000214 /// Solve - Solve for constants and executable blocks.
215 ///
216 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000217
Chris Lattner3bad2532006-12-20 06:21:33 +0000218 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000219 /// that branches on undef values cannot reach any of their successors.
220 /// However, this is not a safe assumption. After we solve dataflow, this
221 /// method should be use to handle this. If this returns true, the solver
222 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000223 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000224
Chris Lattner82bec2c2004-11-15 04:44:20 +0000225 /// getExecutableBlocks - Once we have solved for constants, return the set of
226 /// blocks that is known to be executable.
Chris Lattnercc56aad2007-02-02 20:57:39 +0000227 SmallSet<BasicBlock*, 16> &getExecutableBlocks() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000228 return BBExecutable;
229 }
230
231 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000232 /// LLVM values to LatticeVals.
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000233 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000234 return ValueState;
235 }
236
Devang Patel7c490d42008-03-11 05:46:42 +0000237 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000238 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000239 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
240 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000241 }
242
Chris Lattnerdd336d12004-12-11 05:15:59 +0000243 /// getTrackedGlobals - Get and return the set of inferred initializers for
244 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000245 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000246 return TrackedGlobals;
247 }
248
Chris Lattner57939df2007-03-04 04:50:21 +0000249 inline void markOverdefined(Value *V) {
250 markOverdefined(ValueState[V], V);
251 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000252
Chris Lattner138a1242001-06-27 23:38:11 +0000253private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000254 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000255 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000256 // the users of the instruction are updated later.
257 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000258 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000259 if (IV.markConstant(C)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000260 DOUT << "markConstant: " << *C << ": " << *V;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000261 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000262 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000263 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000264
265 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
266 IV.markForcedConstant(C);
267 DOUT << "markForcedConstant: " << *C << ": " << *V;
268 InstWorkList.push_back(V);
269 }
270
Chris Lattner59acc7d2004-12-10 08:02:06 +0000271 inline void markConstant(Value *V, Constant *C) {
272 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000273 }
274
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000275 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000276 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000277 // work list so that the users of the instruction are updated later.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000278 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000279 if (IV.markOverdefined()) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000280 DEBUG(DOUT << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000281 if (Function *F = dyn_cast<Function>(V))
Bill Wendlingb7427032006-11-26 09:46:52 +0000282 DOUT << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000283 else
Bill Wendlingb7427032006-11-26 09:46:52 +0000284 DOUT << *V);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000285 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000286 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000287 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000288 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000289
290 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
291 if (IV.isOverdefined() || MergeWithV.isUndefined())
292 return; // Noop.
293 if (MergeWithV.isOverdefined())
294 markOverdefined(IV, V);
295 else if (IV.isUndefined())
296 markConstant(IV, V, MergeWithV.getConstant());
297 else if (IV.getConstant() != MergeWithV.getConstant())
298 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000299 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000300
301 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
302 return mergeInValue(ValueState[V], V, MergeWithV);
303 }
304
Chris Lattner138a1242001-06-27 23:38:11 +0000305
Chris Lattneref36dfd2004-11-15 05:03:30 +0000306 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000307 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000308 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000309 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000310 // Instruction object, then use this accessor to get its value from the map.
311 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000312 inline LatticeVal &getValueState(Value *V) {
Chris Lattnerc1ec7802007-02-02 22:36:16 +0000313 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000314 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000315
Chris Lattner3bad2532006-12-20 06:21:33 +0000316 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000317 if (isa<UndefValue>(V)) {
318 // Nothing to do, remain undefined.
319 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000320 LatticeVal &LV = ValueState[C];
321 LV.markConstant(C); // Constants are constant
322 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000323 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000324 }
Chris Lattner138a1242001-06-27 23:38:11 +0000325 // All others are underdefined by default...
326 return ValueState[V];
327 }
328
Misha Brukmanfd939082005-04-21 23:48:37 +0000329 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000330 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000331 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000332 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
333 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
334 return; // This edge is already known to be executable!
335
336 if (BBExecutable.count(Dest)) {
Chris Lattner5c8e8d72008-05-11 01:55:59 +0000337 DOUT << "Marking Edge Executable: " << Source->getNameStart()
338 << " -> " << Dest->getNameStart() << "\n";
Chris Lattner16b18fd2003-10-08 16:55:34 +0000339
340 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000341 // feasible that wasn't before. Revisit the PHI nodes in the block
342 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000343 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
344 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000345
346 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000347 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000348 }
Chris Lattner138a1242001-06-27 23:38:11 +0000349 }
350
Chris Lattner82bec2c2004-11-15 04:44:20 +0000351 // getFeasibleSuccessors - Return a vector of booleans to indicate which
352 // successors are reachable from a given terminator instruction.
353 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000354 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000355
356 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
357 // block to the 'To' basic block is currently feasible...
358 //
359 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
360
361 // OperandChangedState - This method is invoked on all of the users of an
362 // instruction that was just changed state somehow.... Based on this
363 // information, we need to update the specified user of this instruction.
364 //
365 void OperandChangedState(User *U) {
366 // Only instructions use other variable values!
367 Instruction &I = cast<Instruction>(*U);
368 if (BBExecutable.count(I.getParent())) // Inst is executable?
369 visit(I);
370 }
371
372private:
373 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000374
Misha Brukmanfd939082005-04-21 23:48:37 +0000375 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000376 // operand made a transition, or the instruction is newly executable. Change
377 // the value type of I to reflect these changes if appropriate.
378 //
Chris Lattner7e708292002-06-25 16:13:24 +0000379 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000380
381 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000382 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000383 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000384
Chris Lattnerb8047602002-08-14 17:53:45 +0000385 void visitCastInst(CastInst &I);
Devang Patel7c490d42008-03-11 05:46:42 +0000386 void visitGetResultInst(GetResultInst &GRI);
Chris Lattner6e323722004-03-12 05:52:44 +0000387 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000388 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000389 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000390 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000391 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000392 void visitShuffleVectorInst(ShuffleVectorInst &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000393
394 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000395 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000396 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000397 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner59acc7d2004-12-10 08:02:06 +0000398 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
399 void visitInvokeInst (InvokeInst &II) {
400 visitCallSite(CallSite::get(&II));
401 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000402 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000403 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000404 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000405 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000406 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000407 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
408 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000409 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000410
Chris Lattner7e708292002-06-25 16:13:24 +0000411 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000412 // If a new instruction is added to LLVM that we don't handle...
Bill Wendlinge8156192006-12-07 01:30:32 +0000413 cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000414 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000415 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000416};
Chris Lattnerf6293092002-07-23 18:06:35 +0000417
Duncan Sandse2abf122007-07-20 08:56:21 +0000418} // end anonymous namespace
419
420
Chris Lattnerb9a66342002-05-02 21:44:00 +0000421// getFeasibleSuccessors - Return a vector of booleans to indicate which
422// successors are reachable from a given terminator instruction.
423//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000424void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000425 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000426 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000427 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000428 if (BI->isUnconditional()) {
429 Succs[0] = true;
430 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000431 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000432 if (BCValue.isOverdefined() ||
Reid Spencer579dca12007-01-12 04:24:46 +0000433 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattner84831642004-01-12 17:40:36 +0000434 // Overdefined condition variables, and branches on unfoldable constant
435 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000436 Succs[0] = Succs[1] = true;
437 } else if (BCValue.isConstant()) {
438 // Constant condition variables mean the branch can only go a single way
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000439 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000440 }
441 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000442 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000443 // Invoke instructions successors are always executable.
444 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000445 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000446 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000447 if (SCValue.isOverdefined() || // Overdefined condition?
448 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000449 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000450 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner3a73c9e2008-05-10 23:56:54 +0000451 } else if (SCValue.isConstant())
452 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000453 } else {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000454 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000455 }
456}
457
458
Chris Lattner59f0ce22002-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 Lattner82bec2c2004-11-15 04:44:20 +0000462bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-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 Brukmanfd939082005-04-21 23:48:37 +0000467
Chris Lattnerb9a66342002-05-02 21:44:00 +0000468 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000469 TerminatorInst *TI = From->getTerminator();
470 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
471 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000472 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000473 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000474 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-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 Lattner84831642004-01-12 17:40:36 +0000479 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000480 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000481
Chris Lattner7d275f42003-10-08 15:47:41 +0000482 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000483 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000484 ConstantInt::getFalse()) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000485 }
486 return false;
487 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000488 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-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 Lattneref36dfd2004-11-15 05:03:30 +0000492 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-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 Lattner84831642004-01-12 17:40:36 +0000498 if (!isa<ConstantInt>(CPV))
499 return true; // not a foldable constant?
500
Chris Lattner7d275f42003-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 Wendlinge8156192006-12-07 01:30:32 +0000512 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner7d275f42003-10-08 15:47:41 +0000513 abort();
514 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000515}
Chris Lattner138a1242001-06-27 23:38:11 +0000516
Chris Lattner2a632552002-04-18 15:13:15 +0000517// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-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 Lattner82bec2c2004-11-15 04:44:20 +0000535void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000536 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-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) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000544 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000545 for (; I != E; ++I) Users.push_back(I->second);
546 while (!Users.empty()) {
547 visit(Users.back());
548 Users.pop_back();
549 }
550 }
551 return; // Quick exit
552 }
Chris Lattner138a1242001-06-27 23:38:11 +0000553
Chris Lattnera2f652d2004-03-16 19:49:59 +0000554 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
555 // and slow us down a lot. Just mark them overdefined.
556 if (PN.getNumIncomingValues() > 64) {
557 markOverdefined(PNIV, &PN);
558 return;
559 }
560
Chris Lattner2a632552002-04-18 15:13:15 +0000561 // Look at all of the executable operands of the PHI node. If any of them
562 // are overdefined, the PHI becomes overdefined as well. If they are all
563 // constant, and they agree with each other, the PHI becomes the identical
564 // constant. If they are constant and don't agree, the PHI is overdefined.
565 // If there are no executable operands, the PHI remains undefined.
566 //
Chris Lattner9de28282003-04-25 02:50:03 +0000567 Constant *OperandVal = 0;
568 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000569 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000570 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000571
Chris Lattner7e708292002-06-25 16:13:24 +0000572 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000573 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000574 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000575 return;
576 }
577
Chris Lattner9de28282003-04-25 02:50:03 +0000578 if (OperandVal == 0) { // Grab the first value...
579 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000580 } else { // Another value is being merged in!
581 // There is already a reachable operand. If we conflict with it,
582 // then the PHI node becomes overdefined. If we agree with it, we
583 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000584
Chris Lattner2a632552002-04-18 15:13:15 +0000585 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000586 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000587 // Yes there is. This means the PHI node is not constant.
588 // You must be overdefined poor PHI.
589 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000590 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000591 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000592 }
Chris Lattner138a1242001-06-27 23:38:11 +0000593 }
594 }
Chris Lattner138a1242001-06-27 23:38:11 +0000595 }
596
Chris Lattner2a632552002-04-18 15:13:15 +0000597 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000598 // arguments that agree with each other(and OperandVal is the constant) or
599 // OperandVal is null because there are no defined incoming arguments. If
600 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000601 //
Chris Lattner9de28282003-04-25 02:50:03 +0000602 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000603 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000604}
605
Chris Lattner59acc7d2004-12-10 08:02:06 +0000606void SCCPSolver::visitReturnInst(ReturnInst &I) {
607 if (I.getNumOperands() == 0) return; // Ret void
608
Chris Lattner59acc7d2004-12-10 08:02:06 +0000609 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000610 // If we are tracking the return value of this function, merge it in.
611 if (!F->hasInternalLinkage())
612 return;
613
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000614 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000615 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000616 TrackedRetVals.find(F);
617 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000618 !TFRVI->second.isOverdefined()) {
619 LatticeVal &IV = getValueState(I.getOperand(0));
620 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000621 return;
622 }
623 }
624
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000625 // Handle functions that return multiple values.
626 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
627 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
628 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
629 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
630 if (It == TrackedMultipleRetVals.end()) break;
631 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000632 }
633 }
634}
635
Chris Lattner82bec2c2004-11-15 04:44:20 +0000636void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000637 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000638 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000639
Chris Lattner16b18fd2003-10-08 16:55:34 +0000640 BasicBlock *BB = TI.getParent();
641
Chris Lattnerb9a66342002-05-02 21:44:00 +0000642 // Mark all feasible successors executable...
643 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000644 if (SuccFeasible[i])
645 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000646}
647
Chris Lattner82bec2c2004-11-15 04:44:20 +0000648void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000649 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000650 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000651 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000652 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000653 else if (VState.isConstant()) // Propagate constant value
Reid Spencer4da49122006-12-12 05:05:00 +0000654 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
655 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000656}
657
Devang Patel7c490d42008-03-11 05:46:42 +0000658void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
Devang Patel7c490d42008-03-11 05:46:42 +0000659 Value *Aggr = GRI.getOperand(0);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000660
661 // If the operand to the getresult is an undef, the result is undef.
662 if (isa<UndefValue>(Aggr))
663 return;
664
665 Function *F;
Devang Pateld4e0af92008-04-09 15:58:24 +0000666 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
Devang Patel7c490d42008-03-11 05:46:42 +0000667 F = CI->getCalledFunction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000668 else
669 F = cast<InvokeInst>(Aggr)->getCalledFunction();
Devang Patel7c490d42008-03-11 05:46:42 +0000670
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000671 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
672 // result back!
673 if (F == 0 || TrackedMultipleRetVals.empty()) {
674 markOverdefined(&GRI);
Devang Pateld4e0af92008-04-09 15:58:24 +0000675 return;
Devang Patel7c490d42008-03-11 05:46:42 +0000676 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000677
678 // See if we are tracking the result of the callee.
679 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
680 It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
681
682 // If not tracking this function (for example, it is a declaration) just move
683 // to overdefined.
684 if (It == TrackedMultipleRetVals.end()) {
685 markOverdefined(&GRI);
686 return;
687 }
688
689 // Otherwise, the value will be merged in here as a result of CallSite
690 // handling.
Devang Patel7c490d42008-03-11 05:46:42 +0000691}
692
Chris Lattner82bec2c2004-11-15 04:44:20 +0000693void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000694 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000695 if (CondValue.isUndefined())
696 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000697 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000698 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000699 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000700 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000701 return;
702 }
703 }
704
705 // Otherwise, the condition is overdefined or a constant we can't evaluate.
706 // See if we can produce something better than overdefined based on the T/F
707 // value.
708 LatticeVal &TVal = getValueState(I.getTrueValue());
709 LatticeVal &FVal = getValueState(I.getFalseValue());
710
711 // select ?, C, C -> C.
712 if (TVal.isConstant() && FVal.isConstant() &&
713 TVal.getConstant() == FVal.getConstant()) {
714 markConstant(&I, FVal.getConstant());
715 return;
716 }
717
718 if (TVal.isUndefined()) { // select ?, undef, X -> X.
719 mergeInValue(&I, FVal);
720 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
721 mergeInValue(&I, TVal);
722 } else {
723 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000724 }
725}
726
Chris Lattner2a632552002-04-18 15:13:15 +0000727// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000728void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000729 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000730 if (IV.isOverdefined()) return;
731
Chris Lattneref36dfd2004-11-15 05:03:30 +0000732 LatticeVal &V1State = getValueState(I.getOperand(0));
733 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000734
Chris Lattner2a632552002-04-18 15:13:15 +0000735 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000736 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
737 // operand is overdefined.
738 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
739 LatticeVal *NonOverdefVal = 0;
740 if (!V1State.isOverdefined()) {
741 NonOverdefVal = &V1State;
742 } else if (!V2State.isOverdefined()) {
743 NonOverdefVal = &V2State;
744 }
745
746 if (NonOverdefVal) {
747 if (NonOverdefVal->isUndefined()) {
748 // Could annihilate value.
749 if (I.getOpcode() == Instruction::And)
750 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000751 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
752 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000753 else
754 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000755 return;
756 } else {
757 if (I.getOpcode() == Instruction::And) {
758 if (NonOverdefVal->getConstant()->isNullValue()) {
759 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000760 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000761 }
762 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000763 if (ConstantInt *CI =
764 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000765 if (CI->isAllOnesValue()) {
766 markConstant(IV, &I, NonOverdefVal->getConstant());
767 return; // X or -1 = -1
768 }
769 }
770 }
771 }
772 }
773
774
Chris Lattner1daee8b2004-01-12 03:57:30 +0000775 // If both operands are PHI nodes, it is possible that this instruction has
776 // a constant value, despite the fact that the PHI node doesn't. Check for
777 // this condition now.
778 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
779 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
780 if (PN1->getParent() == PN2->getParent()) {
781 // Since the two PHI nodes are in the same basic block, they must have
782 // entries for the same predecessors. Walk the predecessor list, and
783 // if all of the incoming values are constants, and the result of
784 // evaluating this expression with all incoming value pairs is the
785 // same, then this expression is a constant even though the PHI node
786 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000787 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000788 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000789 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000790 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000791 LatticeVal &In2 =
792 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000793
794 if (In1.isOverdefined() || In2.isOverdefined()) {
795 Result.markOverdefined();
796 break; // Cannot fold this operation over the PHI nodes!
797 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000798 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
799 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000800 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000801 Result.markConstant(V);
802 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000803 Result.markOverdefined();
804 break;
805 }
806 }
807 }
808
809 // If we found a constant value here, then we know the instruction is
810 // constant despite the fact that the PHI nodes are overdefined.
811 if (Result.isConstant()) {
812 markConstant(IV, &I, Result.getConstant());
813 // Remember that this instruction is virtually using the PHI node
814 // operands.
815 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
816 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
817 return;
818 } else if (Result.isUndefined()) {
819 return;
820 }
821
822 // Okay, this really is overdefined now. Since we might have
823 // speculatively thought that this was not overdefined before, and
824 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
825 // make sure to clean out any entries that we put there, for
826 // efficiency.
827 std::multimap<PHINode*, Instruction*>::iterator It, E;
828 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
829 while (It != E) {
830 if (It->second == &I) {
831 UsersOfOverdefinedPHIs.erase(It++);
832 } else
833 ++It;
834 }
835 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
836 while (It != E) {
837 if (It->second == &I) {
838 UsersOfOverdefinedPHIs.erase(It++);
839 } else
840 ++It;
841 }
842 }
843
844 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000845 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000846 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
847 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000848 }
849}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000850
Reid Spencere4d87aa2006-12-23 06:05:41 +0000851// Handle ICmpInst instruction...
852void SCCPSolver::visitCmpInst(CmpInst &I) {
853 LatticeVal &IV = ValueState[&I];
854 if (IV.isOverdefined()) return;
855
856 LatticeVal &V1State = getValueState(I.getOperand(0));
857 LatticeVal &V2State = getValueState(I.getOperand(1));
858
859 if (V1State.isOverdefined() || V2State.isOverdefined()) {
860 // If both operands are PHI nodes, it is possible that this instruction has
861 // a constant value, despite the fact that the PHI node doesn't. Check for
862 // this condition now.
863 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
864 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
865 if (PN1->getParent() == PN2->getParent()) {
866 // Since the two PHI nodes are in the same basic block, they must have
867 // entries for the same predecessors. Walk the predecessor list, and
868 // if all of the incoming values are constants, and the result of
869 // evaluating this expression with all incoming value pairs is the
870 // same, then this expression is a constant even though the PHI node
871 // is not a constant!
872 LatticeVal Result;
873 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
874 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
875 BasicBlock *InBlock = PN1->getIncomingBlock(i);
876 LatticeVal &In2 =
877 getValueState(PN2->getIncomingValueForBlock(InBlock));
878
879 if (In1.isOverdefined() || In2.isOverdefined()) {
880 Result.markOverdefined();
881 break; // Cannot fold this operation over the PHI nodes!
882 } else if (In1.isConstant() && In2.isConstant()) {
883 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
884 In1.getConstant(),
885 In2.getConstant());
886 if (Result.isUndefined())
887 Result.markConstant(V);
888 else if (Result.isConstant() && Result.getConstant() != V) {
889 Result.markOverdefined();
890 break;
891 }
892 }
893 }
894
895 // If we found a constant value here, then we know the instruction is
896 // constant despite the fact that the PHI nodes are overdefined.
897 if (Result.isConstant()) {
898 markConstant(IV, &I, Result.getConstant());
899 // Remember that this instruction is virtually using the PHI node
900 // operands.
901 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
902 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
903 return;
904 } else if (Result.isUndefined()) {
905 return;
906 }
907
908 // Okay, this really is overdefined now. Since we might have
909 // speculatively thought that this was not overdefined before, and
910 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
911 // make sure to clean out any entries that we put there, for
912 // efficiency.
913 std::multimap<PHINode*, Instruction*>::iterator It, E;
914 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
915 while (It != E) {
916 if (It->second == &I) {
917 UsersOfOverdefinedPHIs.erase(It++);
918 } else
919 ++It;
920 }
921 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
922 while (It != E) {
923 if (It->second == &I) {
924 UsersOfOverdefinedPHIs.erase(It++);
925 } else
926 ++It;
927 }
928 }
929
930 markOverdefined(IV, &I);
931 } else if (V1State.isConstant() && V2State.isConstant()) {
932 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
933 V1State.getConstant(),
934 V2State.getConstant()));
935 }
936}
937
Robert Bocchino56107e22006-01-10 19:05:05 +0000938void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000939 // FIXME : SCCP does not handle vectors properly.
940 markOverdefined(&I);
941 return;
942
943#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +0000944 LatticeVal &ValState = getValueState(I.getOperand(0));
945 LatticeVal &IdxState = getValueState(I.getOperand(1));
946
947 if (ValState.isOverdefined() || IdxState.isOverdefined())
948 markOverdefined(&I);
949 else if(ValState.isConstant() && IdxState.isConstant())
950 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
951 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000952#endif
Robert Bocchino56107e22006-01-10 19:05:05 +0000953}
954
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000955void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000956 // FIXME : SCCP does not handle vectors properly.
957 markOverdefined(&I);
958 return;
959#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000960 LatticeVal &ValState = getValueState(I.getOperand(0));
961 LatticeVal &EltState = getValueState(I.getOperand(1));
962 LatticeVal &IdxState = getValueState(I.getOperand(2));
963
964 if (ValState.isOverdefined() || EltState.isOverdefined() ||
965 IdxState.isOverdefined())
966 markOverdefined(&I);
967 else if(ValState.isConstant() && EltState.isConstant() &&
968 IdxState.isConstant())
969 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
970 EltState.getConstant(),
971 IdxState.getConstant()));
972 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +0000973 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +0000974 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
975 EltState.getConstant(),
976 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000977#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000978}
979
Chris Lattner543abdf2006-04-08 01:19:12 +0000980void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000981 // FIXME : SCCP does not handle vectors properly.
982 markOverdefined(&I);
983 return;
984#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +0000985 LatticeVal &V1State = getValueState(I.getOperand(0));
986 LatticeVal &V2State = getValueState(I.getOperand(1));
987 LatticeVal &MaskState = getValueState(I.getOperand(2));
988
989 if (MaskState.isUndefined() ||
990 (V1State.isUndefined() && V2State.isUndefined()))
991 return; // Undefined output if mask or both inputs undefined.
992
993 if (V1State.isOverdefined() || V2State.isOverdefined() ||
994 MaskState.isOverdefined()) {
995 markOverdefined(&I);
996 } else {
997 // A mix of constant/undef inputs.
998 Constant *V1 = V1State.isConstant() ?
999 V1State.getConstant() : UndefValue::get(I.getType());
1000 Constant *V2 = V2State.isConstant() ?
1001 V2State.getConstant() : UndefValue::get(I.getType());
1002 Constant *Mask = MaskState.isConstant() ?
1003 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1004 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1005 }
Devang Patel67a821d2006-12-04 23:54:59 +00001006#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001007}
1008
Chris Lattner2a88bb72002-08-30 23:39:00 +00001009// Handle getelementptr instructions... if all operands are constants then we
1010// can turn this into a getelementptr ConstantExpr.
1011//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001012void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001013 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001014 if (IV.isOverdefined()) return;
1015
Chris Lattnere777ff22007-02-02 20:51:48 +00001016 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001017 Operands.reserve(I.getNumOperands());
1018
1019 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001020 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001021 if (State.isUndefined())
1022 return; // Operands are not resolved yet...
1023 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001024 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001025 return;
1026 }
1027 assert(State.isConstant() && "Unknown state!");
1028 Operands.push_back(State.getConstant());
1029 }
1030
1031 Constant *Ptr = Operands[0];
1032 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1033
Chris Lattnere777ff22007-02-02 20:51:48 +00001034 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1035 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001036}
Brian Gaeked0fde302003-11-11 22:41:34 +00001037
Chris Lattnerdd336d12004-12-11 05:15:59 +00001038void SCCPSolver::visitStoreInst(Instruction &SI) {
1039 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1040 return;
1041 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001042 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001043 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1044
1045 // Get the value we are storing into the global.
1046 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1047
1048 mergeInValue(I->second, GV, PtrVal);
1049 if (I->second.isOverdefined())
1050 TrackedGlobals.erase(I); // No need to keep tracking this!
1051}
1052
1053
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001054// Handle load instructions. If the operand is a constant pointer to a constant
1055// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001056void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001057 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001058 if (IV.isOverdefined()) return;
1059
Chris Lattneref36dfd2004-11-15 05:03:30 +00001060 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001061 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1062 if (PtrVal.isConstant() && !I.isVolatile()) {
1063 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001064 // TODO: Consider a target hook for valid address spaces for this xform.
1065 if (isa<ConstantPointerNull>(Ptr) &&
1066 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001067 // load null -> null
1068 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1069 return;
1070 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001071
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001072 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001073 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1074 if (GV->isConstant()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001075 if (!GV->isDeclaration()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001076 markConstant(IV, &I, GV->getInitializer());
1077 return;
1078 }
1079 } else if (!TrackedGlobals.empty()) {
1080 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001081 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001082 TrackedGlobals.find(GV);
1083 if (It != TrackedGlobals.end()) {
1084 mergeInValue(IV, &I, It->second);
1085 return;
1086 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001087 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001088 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001089
1090 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1091 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1092 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001093 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00001094 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen9d809302005-04-23 21:38:35 +00001095 if (Constant *V =
Chris Lattnerebe61202005-09-26 05:28:52 +00001096 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001097 markConstant(IV, &I, V);
1098 return;
1099 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001100 }
1101
1102 // Otherwise we cannot say for certain what value this load will produce.
1103 // Bail out.
1104 markOverdefined(IV, &I);
1105}
Chris Lattner58b7b082004-04-13 19:43:54 +00001106
Chris Lattner59acc7d2004-12-10 08:02:06 +00001107void SCCPSolver::visitCallSite(CallSite CS) {
1108 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001109 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001110
1111 // The common case is that we aren't tracking the callee, either because we
1112 // are not doing interprocedural analysis or the callee is indirect, or is
1113 // external. Handle these cases first.
1114 if (F == 0 || !F->hasInternalLinkage()) {
1115CallOverdefined:
1116 // Void return and not tracking callee, just bail.
1117 if (I->getType() == Type::VoidTy) return;
1118
1119 // Otherwise, if we have a single return value case, and if the function is
1120 // a declaration, maybe we can constant fold it.
1121 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1122 canConstantFoldCallTo(F)) {
1123
1124 SmallVector<Constant*, 8> Operands;
1125 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1126 AI != E; ++AI) {
1127 LatticeVal &State = getValueState(*AI);
1128 if (State.isUndefined())
1129 return; // Operands are not resolved yet.
1130 else if (State.isOverdefined()) {
1131 markOverdefined(I);
1132 return;
1133 }
1134 assert(State.isConstant() && "Unknown state!");
1135 Operands.push_back(State.getConstant());
1136 }
1137
1138 // If we can constant fold this, mark the result of the call as a
1139 // constant.
1140 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1141 markConstant(I, C);
1142 return;
1143 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001144 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001145
1146 // Otherwise, we don't know anything about this call, mark it overdefined.
1147 markOverdefined(I);
1148 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001149 }
1150
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001151 // If this is a single/zero retval case, see if we're tracking the function.
1152 const StructType *RetSTy = dyn_cast<StructType>(I->getType());
1153 if (RetSTy == 0) {
1154 // Check to see if we're tracking this callee, if not, handle it in the
1155 // common path above.
1156 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1157 if (TFRVI == TrackedRetVals.end())
1158 goto CallOverdefined;
1159
1160 // If so, propagate the return value of the callee into this call result.
1161 mergeInValue(I, TFRVI->second);
1162 } else {
1163 // Check to see if we're tracking this callee, if not, handle it in the
1164 // common path above.
1165 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1166 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1167 if (TMRVI == TrackedMultipleRetVals.end())
1168 goto CallOverdefined;
1169
1170 // If we are tracking this callee, propagate the return values of the call
1171 // into this call site. We do this by walking all the getresult uses.
1172 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1173 UI != E; ++UI) {
1174 GetResultInst *GRI = cast<GetResultInst>(*UI);
1175 mergeInValue(GRI,
1176 TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1177 }
1178 }
1179
1180 // Finally, if this is the first call to the function hit, mark its entry
1181 // block executable.
1182 if (!BBExecutable.count(F->begin()))
1183 MarkBlockExecutable(F->begin());
1184
1185 // Propagate information from this call site into the callee.
1186 CallSite::arg_iterator CAI = CS.arg_begin();
1187 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1188 AI != E; ++AI, ++CAI) {
1189 LatticeVal &IV = ValueState[AI];
1190 if (!IV.isOverdefined())
1191 mergeInValue(IV, AI, getValueState(*CAI));
1192 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001193}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001194
1195
1196void SCCPSolver::Solve() {
1197 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001198 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001199 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001200 // Process the instruction work list...
1201 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001202 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001203 OverdefinedInstWorkList.pop_back();
1204
Bill Wendlingb7427032006-11-26 09:46:52 +00001205 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001206
Chris Lattner82bec2c2004-11-15 04:44:20 +00001207 // "I" got into the work list because it either made the transition from
1208 // bottom to constant
1209 //
1210 // Anything on this worklist that is overdefined need not be visited
1211 // since all of its users will have already been marked as overdefined
1212 // Update all of the users of this instruction's value...
1213 //
1214 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1215 UI != E; ++UI)
1216 OperandChangedState(*UI);
1217 }
1218 // Process the instruction work list...
1219 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001220 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001221 InstWorkList.pop_back();
1222
Bill Wendlingb7427032006-11-26 09:46:52 +00001223 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001224
Chris Lattner82bec2c2004-11-15 04:44:20 +00001225 // "I" got into the work list because it either made the transition from
1226 // bottom to constant
1227 //
1228 // Anything on this worklist that is overdefined need not be visited
1229 // since all of its users will have already been marked as overdefined.
1230 // Update all of the users of this instruction's value...
1231 //
1232 if (!getValueState(I).isOverdefined())
1233 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1234 UI != E; ++UI)
1235 OperandChangedState(*UI);
1236 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001237
Chris Lattner82bec2c2004-11-15 04:44:20 +00001238 // Process the basic block work list...
1239 while (!BBWorkList.empty()) {
1240 BasicBlock *BB = BBWorkList.back();
1241 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001242
Bill Wendlingb7427032006-11-26 09:46:52 +00001243 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanfd939082005-04-21 23:48:37 +00001244
Chris Lattner82bec2c2004-11-15 04:44:20 +00001245 // Notify all instructions in this basic block that they are newly
1246 // executable.
1247 visit(BB);
1248 }
1249 }
1250}
1251
Chris Lattner3bad2532006-12-20 06:21:33 +00001252/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001253/// that branches on undef values cannot reach any of their successors.
1254/// However, this is not a safe assumption. After we solve dataflow, this
1255/// method should be use to handle this. If this returns true, the solver
1256/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001257///
1258/// This method handles this by finding an unresolved branch and marking it one
1259/// of the edges from the block as being feasible, even though the condition
1260/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1261/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001262/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001263/// constraints on the condition of the branch, as that would impact other users
1264/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001265///
1266/// This scan also checks for values that use undefs, whose results are actually
1267/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1268/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1269/// even if X isn't defined.
1270bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001271 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1272 if (!BBExecutable.count(BB))
1273 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001274
1275 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1276 // Look for instructions which produce undef values.
1277 if (I->getType() == Type::VoidTy) continue;
1278
1279 LatticeVal &LV = getValueState(I);
1280 if (!LV.isUndefined()) continue;
1281
1282 // Get the lattice values of the first two operands for use below.
1283 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1284 LatticeVal Op1LV;
1285 if (I->getNumOperands() == 2) {
1286 // If this is a two-operand instruction, and if both operands are
1287 // undefs, the result stays undef.
1288 Op1LV = getValueState(I->getOperand(1));
1289 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1290 continue;
1291 }
1292
1293 // If this is an instructions whose result is defined even if the input is
1294 // not fully defined, propagate the information.
1295 const Type *ITy = I->getType();
1296 switch (I->getOpcode()) {
1297 default: break; // Leave the instruction as an undef.
1298 case Instruction::ZExt:
1299 // After a zero extend, we know the top part is zero. SExt doesn't have
1300 // to be handled here, because we don't know whether the top part is 1's
1301 // or 0's.
1302 assert(Op0LV.isUndefined());
1303 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1304 return true;
1305 case Instruction::Mul:
1306 case Instruction::And:
1307 // undef * X -> 0. X could be zero.
1308 // undef & X -> 0. X could be zero.
1309 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1310 return true;
1311
1312 case Instruction::Or:
1313 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001314 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1315 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001316 else
1317 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1318 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001319
1320 case Instruction::SDiv:
1321 case Instruction::UDiv:
1322 case Instruction::SRem:
1323 case Instruction::URem:
1324 // X / undef -> undef. No change.
1325 // X % undef -> undef. No change.
1326 if (Op1LV.isUndefined()) break;
1327
1328 // undef / X -> 0. X could be maxint.
1329 // undef % X -> 0. X could be 1.
1330 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1331 return true;
1332
1333 case Instruction::AShr:
1334 // undef >>s X -> undef. No change.
1335 if (Op0LV.isUndefined()) break;
1336
1337 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1338 if (Op0LV.isConstant())
1339 markForcedConstant(LV, I, Op0LV.getConstant());
1340 else
1341 markOverdefined(LV, I);
1342 return true;
1343 case Instruction::LShr:
1344 case Instruction::Shl:
1345 // undef >> X -> undef. No change.
1346 // undef << X -> undef. No change.
1347 if (Op0LV.isUndefined()) break;
1348
1349 // X >> undef -> 0. X could be 0.
1350 // X << undef -> 0. X could be 0.
1351 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1352 return true;
1353 case Instruction::Select:
1354 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1355 if (Op0LV.isUndefined()) {
1356 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1357 Op1LV = getValueState(I->getOperand(2));
1358 } else if (Op1LV.isUndefined()) {
1359 // c ? undef : undef -> undef. No change.
1360 Op1LV = getValueState(I->getOperand(2));
1361 if (Op1LV.isUndefined())
1362 break;
1363 // Otherwise, c ? undef : x -> x.
1364 } else {
1365 // Leave Op1LV as Operand(1)'s LatticeValue.
1366 }
1367
1368 if (Op1LV.isConstant())
1369 markForcedConstant(LV, I, Op1LV.getConstant());
1370 else
1371 markOverdefined(LV, I);
1372 return true;
1373 }
1374 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001375
1376 TerminatorInst *TI = BB->getTerminator();
1377 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1378 if (!BI->isConditional()) continue;
1379 if (!getValueState(BI->getCondition()).isUndefined())
1380 continue;
1381 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1382 if (!getValueState(SI->getCondition()).isUndefined())
1383 continue;
1384 } else {
1385 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001386 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001387
Chris Lattner05bb7892008-01-28 00:32:30 +00001388 // If the edge to the second successor isn't thought to be feasible yet,
1389 // mark it so now. We pick the second one so that this goes to some
1390 // enumerated value in a switch instead of going to the default destination.
1391 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001392 continue;
1393
1394 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1395 // and return. This will make other blocks reachable, which will allow new
1396 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001397 markEdgeExecutable(BB, TI->getSuccessor(1));
1398
1399 // This must be a conditional branch of switch on undef. At this point,
1400 // force the old terminator to branch to the first successor. This is
1401 // required because we are now influencing the dataflow of the function with
1402 // the assumption that this edge is taken. If we leave the branch condition
1403 // as undef, then further analysis could think the undef went another way
1404 // leading to an inconsistent set of conclusions.
1405 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1406 BI->setCondition(ConstantInt::getFalse());
1407 } else {
1408 SwitchInst *SI = cast<SwitchInst>(TI);
1409 SI->setCondition(SI->getCaseValue(1));
1410 }
1411
Chris Lattnerd2d86702006-10-22 05:59:17 +00001412 return true;
1413 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001414
Chris Lattnerd2d86702006-10-22 05:59:17 +00001415 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001416}
1417
Chris Lattner82bec2c2004-11-15 04:44:20 +00001418
1419namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001420 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001421 //
Chris Lattner14051812004-11-15 07:15:04 +00001422 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001423 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001424 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001425 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001426 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +00001427 SCCP() : FunctionPass((intptr_t)&ID) {}
1428
Chris Lattner14051812004-11-15 07:15:04 +00001429 // runOnFunction - Run the Sparse Conditional Constant Propagation
1430 // algorithm, and return true if the function was modified.
1431 //
1432 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001433
Chris Lattner14051812004-11-15 07:15:04 +00001434 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1435 AU.setPreservesCFG();
1436 }
1437 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001438
Devang Patel19974732007-05-03 01:11:54 +00001439 char SCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001440 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001441} // end anonymous namespace
1442
1443
1444// createSCCPPass - This is the public interface to this file...
1445FunctionPass *llvm::createSCCPPass() {
1446 return new SCCP();
1447}
1448
1449
Chris Lattner82bec2c2004-11-15 04:44:20 +00001450// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1451// and return true if the function was modified.
1452//
1453bool SCCP::runOnFunction(Function &F) {
Chris Lattner5c8e8d72008-05-11 01:55:59 +00001454 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +00001455 SCCPSolver Solver;
1456
1457 // Mark the first block of the function as being executable.
1458 Solver.MarkBlockExecutable(F.begin());
1459
Chris Lattner7e529e42004-11-15 05:45:33 +00001460 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001461 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001462 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001463
Chris Lattner82bec2c2004-11-15 04:44:20 +00001464 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001465 bool ResolvedUndefs = true;
1466 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001467 Solver.Solve();
Chris Lattner3bad2532006-12-20 06:21:33 +00001468 DOUT << "RESOLVING UNDEFs\n";
1469 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001470 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001471
Chris Lattner7e529e42004-11-15 05:45:33 +00001472 bool MadeChanges = false;
1473
1474 // If we decided that there are basic blocks that are dead in this function,
1475 // delete their contents now. Note that we cannot actually delete the blocks,
1476 // as we cannot modify the CFG of the function.
1477 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001478 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001479 SmallVector<Instruction*, 32> Insts;
Chris Lattner57939df2007-03-04 04:50:21 +00001480 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1481
Chris Lattner7e529e42004-11-15 05:45:33 +00001482 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1483 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001484 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001485 ++NumDeadBlocks;
1486
Chris Lattner7e529e42004-11-15 05:45:33 +00001487 // Delete the instructions backwards, as it has a reduced likelihood of
1488 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001489 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1490 I != E; ++I)
1491 Insts.push_back(I);
1492 while (!Insts.empty()) {
1493 Instruction *I = Insts.back();
1494 Insts.pop_back();
1495 if (!I->use_empty())
1496 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1497 BB->getInstList().erase(I);
1498 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001499 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001500 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001501 } else {
1502 // Iterate over all of the instructions in a function, replacing them with
1503 // constants if we have found them to be of constant values.
1504 //
1505 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1506 Instruction *Inst = BI++;
Chris Lattner7cb22ec2008-04-24 00:19:54 +00001507 if (Inst->getType() == Type::VoidTy ||
1508 isa<StructType>(Inst->getType()) ||
Chris Lattnerf4023a12008-04-24 00:16:28 +00001509 isa<TerminatorInst>(Inst))
1510 continue;
1511
1512 LatticeVal &IV = Values[Inst];
1513 if (!IV.isConstant() && !IV.isUndefined())
1514 continue;
1515
1516 Constant *Const = IV.isConstant()
1517 ? IV.getConstant() : UndefValue::get(Inst->getType());
1518 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001519
Chris Lattnerf4023a12008-04-24 00:16:28 +00001520 // Replaces all of the uses of a variable with uses of the constant.
1521 Inst->replaceAllUsesWith(Const);
1522
1523 // Delete the instruction.
1524 Inst->eraseFromParent();
1525
1526 // Hey, we just changed something!
1527 MadeChanges = true;
1528 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001529 }
1530 }
1531
1532 return MadeChanges;
1533}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001534
1535namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001536 //===--------------------------------------------------------------------===//
1537 //
1538 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1539 /// Constant Propagation.
1540 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001541 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001542 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +00001543 IPSCCP() : ModulePass((intptr_t)&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001544 bool runOnModule(Module &M);
1545 };
1546
Devang Patel19974732007-05-03 01:11:54 +00001547 char IPSCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001548 RegisterPass<IPSCCP>
Chris Lattner59acc7d2004-12-10 08:02:06 +00001549 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1550} // end anonymous namespace
1551
1552// createIPSCCPPass - This is the public interface to this file...
1553ModulePass *llvm::createIPSCCPPass() {
1554 return new IPSCCP();
1555}
1556
1557
1558static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001559 // Delete any dead constantexpr klingons.
1560 GV->removeDeadConstantUsers();
1561
Chris Lattner59acc7d2004-12-10 08:02:06 +00001562 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1563 UI != E; ++UI)
1564 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001565 if (SI->getOperand(0) == GV || SI->isVolatile())
1566 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001567 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1568 // Make sure we are calling the function, not passing the address.
1569 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1570 for (CallSite::arg_iterator AI = CS.arg_begin(),
1571 E = CS.arg_end(); AI != E; ++AI)
1572 if (*AI == GV)
1573 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001574 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1575 if (LI->isVolatile())
1576 return true;
1577 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001578 return true;
1579 }
1580 return false;
1581}
1582
1583bool IPSCCP::runOnModule(Module &M) {
1584 SCCPSolver Solver;
1585
1586 // Loop over all functions, marking arguments to those with their addresses
1587 // taken or that are external as overdefined.
1588 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001589 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1590 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001591 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001592 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001593 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1594 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001595 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001596 } else {
1597 Solver.AddTrackedFunction(F);
1598 }
1599
Chris Lattnerdd336d12004-12-11 05:15:59 +00001600 // Loop over global variables. We inform the solver about any internal global
1601 // variables that do not have their 'addresses taken'. If they don't have
1602 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001603 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1604 G != E; ++G)
Chris Lattnerdd336d12004-12-11 05:15:59 +00001605 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1606 Solver.TrackValueOfGlobalVariable(G);
1607
Chris Lattner59acc7d2004-12-10 08:02:06 +00001608 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001609 bool ResolvedUndefs = true;
1610 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001611 Solver.Solve();
1612
Chris Lattner3bad2532006-12-20 06:21:33 +00001613 DOUT << "RESOLVING UNDEFS\n";
1614 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001615 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001616 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001617 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001618
1619 bool MadeChanges = false;
1620
1621 // Iterate over all of the instructions in the module, replacing them with
1622 // constants if we have found them to be of constant values.
1623 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001624 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001625 SmallVector<Instruction*, 32> Insts;
1626 SmallVector<BasicBlock*, 32> BlocksToErase;
Chris Lattner57939df2007-03-04 04:50:21 +00001627 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001628
Chris Lattner59acc7d2004-12-10 08:02:06 +00001629 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001630 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1631 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001632 if (!AI->use_empty()) {
1633 LatticeVal &IV = Values[AI];
1634 if (IV.isConstant() || IV.isUndefined()) {
1635 Constant *CST = IV.isConstant() ?
1636 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001637 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanfd939082005-04-21 23:48:37 +00001638
Chris Lattner59acc7d2004-12-10 08:02:06 +00001639 // Replaces all of the uses of a variable with uses of the
1640 // constant.
1641 AI->replaceAllUsesWith(CST);
1642 ++IPNumArgsElimed;
1643 }
1644 }
1645
1646 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1647 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001648 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001649 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001650
Chris Lattner59acc7d2004-12-10 08:02:06 +00001651 // Delete the instructions backwards, as it has a reduced likelihood of
1652 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001653 TerminatorInst *TI = BB->getTerminator();
1654 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001655 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001656
Chris Lattner59acc7d2004-12-10 08:02:06 +00001657 while (!Insts.empty()) {
1658 Instruction *I = Insts.back();
1659 Insts.pop_back();
1660 if (!I->use_empty())
1661 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1662 BB->getInstList().erase(I);
1663 MadeChanges = true;
1664 ++IPNumInstRemoved;
1665 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001666
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001667 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1668 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001669 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001670 TI->getSuccessor(i)->removePredecessor(BB);
1671 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001672 if (!TI->use_empty())
1673 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001674 BB->getInstList().erase(TI);
1675
Chris Lattner864737b2004-12-11 05:32:19 +00001676 if (&*BB != &F->front())
1677 BlocksToErase.push_back(BB);
1678 else
1679 new UnreachableInst(BB);
1680
Chris Lattner59acc7d2004-12-10 08:02:06 +00001681 } else {
1682 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1683 Instruction *Inst = BI++;
Chris Lattnereb5f4092008-04-24 00:21:50 +00001684 if (Inst->getType() == Type::VoidTy ||
1685 isa<StructType>(Inst->getType()) ||
1686 isa<TerminatorInst>(Inst))
1687 continue;
1688
1689 LatticeVal &IV = Values[Inst];
1690 if (!IV.isConstant() && !IV.isUndefined())
1691 continue;
1692
1693 Constant *Const = IV.isConstant()
1694 ? IV.getConstant() : UndefValue::get(Inst->getType());
1695 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001696
Chris Lattnereb5f4092008-04-24 00:21:50 +00001697 // Replaces all of the uses of a variable with uses of the
1698 // constant.
1699 Inst->replaceAllUsesWith(Const);
1700
1701 // Delete the instruction.
1702 if (!isa<CallInst>(Inst))
1703 Inst->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001704
Chris Lattnereb5f4092008-04-24 00:21:50 +00001705 // Hey, we just changed something!
1706 MadeChanges = true;
1707 ++IPNumInstRemoved;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001708 }
1709 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001710
1711 // Now that all instructions in the function are constant folded, erase dead
1712 // blocks, because we can now use ConstantFoldTerminator to get rid of
1713 // in-edges.
1714 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1715 // If there are any PHI nodes in this successor, drop entries for BB now.
1716 BasicBlock *DeadBB = BlocksToErase[i];
1717 while (!DeadBB->use_empty()) {
1718 Instruction *I = cast<Instruction>(DeadBB->use_back());
1719 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001720 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001721 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001722 // if this is a branch or switch on undef. Fold it manually as a
1723 // branch to the first successor.
1724 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1725 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1726 "Branch should be foldable!");
1727 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1728 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1729 } else {
1730 assert(0 && "Didn't fold away reference to block!");
1731 }
1732
1733 // Make this an uncond branch to the first successor.
1734 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001735 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001736
1737 // Remove entries in successor phi nodes to remove edges.
1738 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1739 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1740
1741 // Remove the old terminator.
1742 TI->eraseFromParent();
1743 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001744 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001745
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001746 // Finally, delete the basic block.
1747 F->getBasicBlockList().erase(DeadBB);
1748 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001749 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001750 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001751
1752 // If we inferred constant or undef return values for a function, we replaced
1753 // all call uses with the inferred value. This means we don't need to bother
1754 // actually returning anything from the function. Replace all return
1755 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001756 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001757 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001758 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001759 E = RV.end(); I != E; ++I)
1760 if (!I->second.isOverdefined() &&
1761 I->first->getReturnType() != Type::VoidTy) {
1762 Function *F = I->first;
1763 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1764 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1765 if (!isa<UndefValue>(RI->getOperand(0)))
1766 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1767 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001768
1769 // If we infered constant or undef values for globals variables, we can delete
1770 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001771 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1772 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001773 E = TG.end(); I != E; ++I) {
1774 GlobalVariable *GV = I->first;
1775 assert(!I->second.isOverdefined() &&
1776 "Overdefined values should have been taken out of the map!");
Chris Lattner5c8e8d72008-05-11 01:55:59 +00001777 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
Chris Lattnerdd336d12004-12-11 05:15:59 +00001778 while (!GV->use_empty()) {
1779 StoreInst *SI = cast<StoreInst>(GV->use_back());
1780 SI->eraseFromParent();
1781 }
1782 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001783 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001784 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001785
Chris Lattner59acc7d2004-12-10 08:02:06 +00001786 return MadeChanges;
1787}