blob: be071f8b1fa5927e541e1963e74d6c760775f815 [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) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000182 DOUT << "Marking Block Executable: " << BB->getName() << "\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)) {
Bill Wendlingb7427032006-11-26 09:46:52 +0000337 DOUT << "Marking Edge Executable: " << Source->getName()
338 << " -> " << Dest->getName() << "\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 Lattnerb9a66342002-05-02 21:44:00 +0000451 } else if (SCValue.isConstant()) {
452 Constant *CPV = SCValue.getConstant();
453 // Make sure to skip the "default value" which isn't a value
454 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
455 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
456 Succs[i] = true;
457 return;
458 }
459 }
460
461 // Constant value not equal to any of the branches... must execute
462 // default branch then...
463 Succs[0] = true;
464 }
465 } else {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000466 assert(0 && "SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000467 }
468}
469
470
Chris Lattner59f0ce22002-05-02 21:18:01 +0000471// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
472// block to the 'To' basic block is currently feasible...
473//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000474bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000475 assert(BBExecutable.count(To) && "Dest should always be alive!");
476
477 // Make sure the source basic block is executable!!
478 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000479
Chris Lattnerb9a66342002-05-02 21:44:00 +0000480 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000481 TerminatorInst *TI = From->getTerminator();
482 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
483 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000484 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000485 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000486 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000487 if (BCValue.isOverdefined()) {
488 // Overdefined condition variables mean the branch could go either way.
489 return true;
490 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000491 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000492 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000493
Chris Lattner7d275f42003-10-08 15:47:41 +0000494 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000495 return BI->getSuccessor(BCValue.getConstant() ==
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000496 ConstantInt::getFalse()) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000497 }
498 return false;
499 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000500 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-10-08 15:47:41 +0000501 // Invoke instructions successors are always executable.
502 return true;
503 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000504 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000505 if (SCValue.isOverdefined()) { // Overdefined condition?
506 // All destinations are executable!
507 return true;
508 } else if (SCValue.isConstant()) {
509 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000510 if (!isa<ConstantInt>(CPV))
511 return true; // not a foldable constant?
512
Chris Lattner7d275f42003-10-08 15:47:41 +0000513 // Make sure to skip the "default value" which isn't a value
514 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
515 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
516 return SI->getSuccessor(i) == To;
517
518 // Constant value not equal to any of the branches... must execute
519 // default branch then...
520 return SI->getDefaultDest() == To;
521 }
522 return false;
523 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +0000524 cerr << "Unknown terminator instruction: " << *TI;
Chris Lattner7d275f42003-10-08 15:47:41 +0000525 abort();
526 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000527}
Chris Lattner138a1242001-06-27 23:38:11 +0000528
Chris Lattner2a632552002-04-18 15:13:15 +0000529// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000530// operand made a transition, or the instruction is newly executable. Change
531// the value type of I to reflect these changes if appropriate. This method
532// makes sure to do the following actions:
533//
534// 1. If a phi node merges two constants in, and has conflicting value coming
535// from different branches, or if the PHI node merges in an overdefined
536// value, then the PHI node becomes overdefined.
537// 2. If a phi node merges only constants in, and they all agree on value, the
538// PHI node becomes a constant value equal to that.
539// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
540// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
541// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
542// 6. If a conditional branch has a value that is constant, make the selected
543// destination executable
544// 7. If a conditional branch has a value that is overdefined, make all
545// successors executable.
546//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000547void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000548 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000549 if (PNIV.isOverdefined()) {
550 // There may be instructions using this PHI node that are not overdefined
551 // themselves. If so, make sure that they know that the PHI node operand
552 // changed.
553 std::multimap<PHINode*, Instruction*>::iterator I, E;
554 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
555 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000556 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000557 for (; I != E; ++I) Users.push_back(I->second);
558 while (!Users.empty()) {
559 visit(Users.back());
560 Users.pop_back();
561 }
562 }
563 return; // Quick exit
564 }
Chris Lattner138a1242001-06-27 23:38:11 +0000565
Chris Lattnera2f652d2004-03-16 19:49:59 +0000566 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
567 // and slow us down a lot. Just mark them overdefined.
568 if (PN.getNumIncomingValues() > 64) {
569 markOverdefined(PNIV, &PN);
570 return;
571 }
572
Chris Lattner2a632552002-04-18 15:13:15 +0000573 // Look at all of the executable operands of the PHI node. If any of them
574 // are overdefined, the PHI becomes overdefined as well. If they are all
575 // constant, and they agree with each other, the PHI becomes the identical
576 // constant. If they are constant and don't agree, the PHI is overdefined.
577 // If there are no executable operands, the PHI remains undefined.
578 //
Chris Lattner9de28282003-04-25 02:50:03 +0000579 Constant *OperandVal = 0;
580 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000581 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000582 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000583
Chris Lattner7e708292002-06-25 16:13:24 +0000584 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000585 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000586 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000587 return;
588 }
589
Chris Lattner9de28282003-04-25 02:50:03 +0000590 if (OperandVal == 0) { // Grab the first value...
591 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000592 } else { // Another value is being merged in!
593 // There is already a reachable operand. If we conflict with it,
594 // then the PHI node becomes overdefined. If we agree with it, we
595 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000596
Chris Lattner2a632552002-04-18 15:13:15 +0000597 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000598 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000599 // Yes there is. This means the PHI node is not constant.
600 // You must be overdefined poor PHI.
601 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000602 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000603 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000604 }
Chris Lattner138a1242001-06-27 23:38:11 +0000605 }
606 }
Chris Lattner138a1242001-06-27 23:38:11 +0000607 }
608
Chris Lattner2a632552002-04-18 15:13:15 +0000609 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000610 // arguments that agree with each other(and OperandVal is the constant) or
611 // OperandVal is null because there are no defined incoming arguments. If
612 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000613 //
Chris Lattner9de28282003-04-25 02:50:03 +0000614 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000615 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000616}
617
Chris Lattner59acc7d2004-12-10 08:02:06 +0000618void SCCPSolver::visitReturnInst(ReturnInst &I) {
619 if (I.getNumOperands() == 0) return; // Ret void
620
Chris Lattner59acc7d2004-12-10 08:02:06 +0000621 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000622 // If we are tracking the return value of this function, merge it in.
623 if (!F->hasInternalLinkage())
624 return;
625
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000626 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000627 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000628 TrackedRetVals.find(F);
629 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000630 !TFRVI->second.isOverdefined()) {
631 LatticeVal &IV = getValueState(I.getOperand(0));
632 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000633 return;
634 }
635 }
636
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000637 // Handle functions that return multiple values.
638 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
639 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
640 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
641 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
642 if (It == TrackedMultipleRetVals.end()) break;
643 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000644 }
645 }
646}
647
Chris Lattner82bec2c2004-11-15 04:44:20 +0000648void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000649 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000650 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000651
Chris Lattner16b18fd2003-10-08 16:55:34 +0000652 BasicBlock *BB = TI.getParent();
653
Chris Lattnerb9a66342002-05-02 21:44:00 +0000654 // Mark all feasible successors executable...
655 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000656 if (SuccFeasible[i])
657 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000658}
659
Chris Lattner82bec2c2004-11-15 04:44:20 +0000660void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000661 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000662 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000663 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000664 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000665 else if (VState.isConstant()) // Propagate constant value
Reid Spencer4da49122006-12-12 05:05:00 +0000666 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
667 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000668}
669
Devang Patel7c490d42008-03-11 05:46:42 +0000670void SCCPSolver::visitGetResultInst(GetResultInst &GRI) {
Devang Patel7c490d42008-03-11 05:46:42 +0000671 Value *Aggr = GRI.getOperand(0);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000672
673 // If the operand to the getresult is an undef, the result is undef.
674 if (isa<UndefValue>(Aggr))
675 return;
676
677 Function *F;
Devang Pateld4e0af92008-04-09 15:58:24 +0000678 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
Devang Patel7c490d42008-03-11 05:46:42 +0000679 F = CI->getCalledFunction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000680 else
681 F = cast<InvokeInst>(Aggr)->getCalledFunction();
Devang Patel7c490d42008-03-11 05:46:42 +0000682
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000683 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
684 // result back!
685 if (F == 0 || TrackedMultipleRetVals.empty()) {
686 markOverdefined(&GRI);
Devang Pateld4e0af92008-04-09 15:58:24 +0000687 return;
Devang Patel7c490d42008-03-11 05:46:42 +0000688 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000689
690 // See if we are tracking the result of the callee.
691 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
692 It = TrackedMultipleRetVals.find(std::make_pair(F, GRI.getIndex()));
693
694 // If not tracking this function (for example, it is a declaration) just move
695 // to overdefined.
696 if (It == TrackedMultipleRetVals.end()) {
697 markOverdefined(&GRI);
698 return;
699 }
700
701 // Otherwise, the value will be merged in here as a result of CallSite
702 // handling.
Devang Patel7c490d42008-03-11 05:46:42 +0000703}
704
Chris Lattner82bec2c2004-11-15 04:44:20 +0000705void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000706 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000707 if (CondValue.isUndefined())
708 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000709 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000710 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000711 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000712 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000713 return;
714 }
715 }
716
717 // Otherwise, the condition is overdefined or a constant we can't evaluate.
718 // See if we can produce something better than overdefined based on the T/F
719 // value.
720 LatticeVal &TVal = getValueState(I.getTrueValue());
721 LatticeVal &FVal = getValueState(I.getFalseValue());
722
723 // select ?, C, C -> C.
724 if (TVal.isConstant() && FVal.isConstant() &&
725 TVal.getConstant() == FVal.getConstant()) {
726 markConstant(&I, FVal.getConstant());
727 return;
728 }
729
730 if (TVal.isUndefined()) { // select ?, undef, X -> X.
731 mergeInValue(&I, FVal);
732 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
733 mergeInValue(&I, TVal);
734 } else {
735 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000736 }
737}
738
Chris Lattner2a632552002-04-18 15:13:15 +0000739// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000740void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000741 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000742 if (IV.isOverdefined()) return;
743
Chris Lattneref36dfd2004-11-15 05:03:30 +0000744 LatticeVal &V1State = getValueState(I.getOperand(0));
745 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000746
Chris Lattner2a632552002-04-18 15:13:15 +0000747 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000748 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
749 // operand is overdefined.
750 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
751 LatticeVal *NonOverdefVal = 0;
752 if (!V1State.isOverdefined()) {
753 NonOverdefVal = &V1State;
754 } else if (!V2State.isOverdefined()) {
755 NonOverdefVal = &V2State;
756 }
757
758 if (NonOverdefVal) {
759 if (NonOverdefVal->isUndefined()) {
760 // Could annihilate value.
761 if (I.getOpcode() == Instruction::And)
762 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000763 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
764 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000765 else
766 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000767 return;
768 } else {
769 if (I.getOpcode() == Instruction::And) {
770 if (NonOverdefVal->getConstant()->isNullValue()) {
771 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000772 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000773 }
774 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000775 if (ConstantInt *CI =
776 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000777 if (CI->isAllOnesValue()) {
778 markConstant(IV, &I, NonOverdefVal->getConstant());
779 return; // X or -1 = -1
780 }
781 }
782 }
783 }
784 }
785
786
Chris Lattner1daee8b2004-01-12 03:57:30 +0000787 // If both operands are PHI nodes, it is possible that this instruction has
788 // a constant value, despite the fact that the PHI node doesn't. Check for
789 // this condition now.
790 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
791 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
792 if (PN1->getParent() == PN2->getParent()) {
793 // Since the two PHI nodes are in the same basic block, they must have
794 // entries for the same predecessors. Walk the predecessor list, and
795 // if all of the incoming values are constants, and the result of
796 // evaluating this expression with all incoming value pairs is the
797 // same, then this expression is a constant even though the PHI node
798 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000799 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000800 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000801 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000802 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000803 LatticeVal &In2 =
804 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000805
806 if (In1.isOverdefined() || In2.isOverdefined()) {
807 Result.markOverdefined();
808 break; // Cannot fold this operation over the PHI nodes!
809 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000810 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
811 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000812 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000813 Result.markConstant(V);
814 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000815 Result.markOverdefined();
816 break;
817 }
818 }
819 }
820
821 // If we found a constant value here, then we know the instruction is
822 // constant despite the fact that the PHI nodes are overdefined.
823 if (Result.isConstant()) {
824 markConstant(IV, &I, Result.getConstant());
825 // Remember that this instruction is virtually using the PHI node
826 // operands.
827 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
828 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
829 return;
830 } else if (Result.isUndefined()) {
831 return;
832 }
833
834 // Okay, this really is overdefined now. Since we might have
835 // speculatively thought that this was not overdefined before, and
836 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
837 // make sure to clean out any entries that we put there, for
838 // efficiency.
839 std::multimap<PHINode*, Instruction*>::iterator It, E;
840 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
841 while (It != E) {
842 if (It->second == &I) {
843 UsersOfOverdefinedPHIs.erase(It++);
844 } else
845 ++It;
846 }
847 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
848 while (It != E) {
849 if (It->second == &I) {
850 UsersOfOverdefinedPHIs.erase(It++);
851 } else
852 ++It;
853 }
854 }
855
856 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000857 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000858 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
859 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000860 }
861}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000862
Reid Spencere4d87aa2006-12-23 06:05:41 +0000863// Handle ICmpInst instruction...
864void SCCPSolver::visitCmpInst(CmpInst &I) {
865 LatticeVal &IV = ValueState[&I];
866 if (IV.isOverdefined()) return;
867
868 LatticeVal &V1State = getValueState(I.getOperand(0));
869 LatticeVal &V2State = getValueState(I.getOperand(1));
870
871 if (V1State.isOverdefined() || V2State.isOverdefined()) {
872 // If both operands are PHI nodes, it is possible that this instruction has
873 // a constant value, despite the fact that the PHI node doesn't. Check for
874 // this condition now.
875 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
876 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
877 if (PN1->getParent() == PN2->getParent()) {
878 // Since the two PHI nodes are in the same basic block, they must have
879 // entries for the same predecessors. Walk the predecessor list, and
880 // if all of the incoming values are constants, and the result of
881 // evaluating this expression with all incoming value pairs is the
882 // same, then this expression is a constant even though the PHI node
883 // is not a constant!
884 LatticeVal Result;
885 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
886 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
887 BasicBlock *InBlock = PN1->getIncomingBlock(i);
888 LatticeVal &In2 =
889 getValueState(PN2->getIncomingValueForBlock(InBlock));
890
891 if (In1.isOverdefined() || In2.isOverdefined()) {
892 Result.markOverdefined();
893 break; // Cannot fold this operation over the PHI nodes!
894 } else if (In1.isConstant() && In2.isConstant()) {
895 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
896 In1.getConstant(),
897 In2.getConstant());
898 if (Result.isUndefined())
899 Result.markConstant(V);
900 else if (Result.isConstant() && Result.getConstant() != V) {
901 Result.markOverdefined();
902 break;
903 }
904 }
905 }
906
907 // If we found a constant value here, then we know the instruction is
908 // constant despite the fact that the PHI nodes are overdefined.
909 if (Result.isConstant()) {
910 markConstant(IV, &I, Result.getConstant());
911 // Remember that this instruction is virtually using the PHI node
912 // operands.
913 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
914 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
915 return;
916 } else if (Result.isUndefined()) {
917 return;
918 }
919
920 // Okay, this really is overdefined now. Since we might have
921 // speculatively thought that this was not overdefined before, and
922 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
923 // make sure to clean out any entries that we put there, for
924 // efficiency.
925 std::multimap<PHINode*, Instruction*>::iterator It, E;
926 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
927 while (It != E) {
928 if (It->second == &I) {
929 UsersOfOverdefinedPHIs.erase(It++);
930 } else
931 ++It;
932 }
933 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
934 while (It != E) {
935 if (It->second == &I) {
936 UsersOfOverdefinedPHIs.erase(It++);
937 } else
938 ++It;
939 }
940 }
941
942 markOverdefined(IV, &I);
943 } else if (V1State.isConstant() && V2State.isConstant()) {
944 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
945 V1State.getConstant(),
946 V2State.getConstant()));
947 }
948}
949
Robert Bocchino56107e22006-01-10 19:05:05 +0000950void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000951 // FIXME : SCCP does not handle vectors properly.
952 markOverdefined(&I);
953 return;
954
955#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +0000956 LatticeVal &ValState = getValueState(I.getOperand(0));
957 LatticeVal &IdxState = getValueState(I.getOperand(1));
958
959 if (ValState.isOverdefined() || IdxState.isOverdefined())
960 markOverdefined(&I);
961 else if(ValState.isConstant() && IdxState.isConstant())
962 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
963 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000964#endif
Robert Bocchino56107e22006-01-10 19:05:05 +0000965}
966
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000967void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000968 // FIXME : SCCP does not handle vectors properly.
969 markOverdefined(&I);
970 return;
971#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000972 LatticeVal &ValState = getValueState(I.getOperand(0));
973 LatticeVal &EltState = getValueState(I.getOperand(1));
974 LatticeVal &IdxState = getValueState(I.getOperand(2));
975
976 if (ValState.isOverdefined() || EltState.isOverdefined() ||
977 IdxState.isOverdefined())
978 markOverdefined(&I);
979 else if(ValState.isConstant() && EltState.isConstant() &&
980 IdxState.isConstant())
981 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
982 EltState.getConstant(),
983 IdxState.getConstant()));
984 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +0000985 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +0000986 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
987 EltState.getConstant(),
988 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +0000989#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000990}
991
Chris Lattner543abdf2006-04-08 01:19:12 +0000992void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +0000993 // FIXME : SCCP does not handle vectors properly.
994 markOverdefined(&I);
995 return;
996#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +0000997 LatticeVal &V1State = getValueState(I.getOperand(0));
998 LatticeVal &V2State = getValueState(I.getOperand(1));
999 LatticeVal &MaskState = getValueState(I.getOperand(2));
1000
1001 if (MaskState.isUndefined() ||
1002 (V1State.isUndefined() && V2State.isUndefined()))
1003 return; // Undefined output if mask or both inputs undefined.
1004
1005 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1006 MaskState.isOverdefined()) {
1007 markOverdefined(&I);
1008 } else {
1009 // A mix of constant/undef inputs.
1010 Constant *V1 = V1State.isConstant() ?
1011 V1State.getConstant() : UndefValue::get(I.getType());
1012 Constant *V2 = V2State.isConstant() ?
1013 V2State.getConstant() : UndefValue::get(I.getType());
1014 Constant *Mask = MaskState.isConstant() ?
1015 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1016 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1017 }
Devang Patel67a821d2006-12-04 23:54:59 +00001018#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001019}
1020
Chris Lattner2a88bb72002-08-30 23:39:00 +00001021// Handle getelementptr instructions... if all operands are constants then we
1022// can turn this into a getelementptr ConstantExpr.
1023//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001024void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001025 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001026 if (IV.isOverdefined()) return;
1027
Chris Lattnere777ff22007-02-02 20:51:48 +00001028 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001029 Operands.reserve(I.getNumOperands());
1030
1031 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001032 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001033 if (State.isUndefined())
1034 return; // Operands are not resolved yet...
1035 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001036 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001037 return;
1038 }
1039 assert(State.isConstant() && "Unknown state!");
1040 Operands.push_back(State.getConstant());
1041 }
1042
1043 Constant *Ptr = Operands[0];
1044 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1045
Chris Lattnere777ff22007-02-02 20:51:48 +00001046 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1047 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001048}
Brian Gaeked0fde302003-11-11 22:41:34 +00001049
Chris Lattnerdd336d12004-12-11 05:15:59 +00001050void SCCPSolver::visitStoreInst(Instruction &SI) {
1051 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1052 return;
1053 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001054 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001055 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1056
1057 // Get the value we are storing into the global.
1058 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1059
1060 mergeInValue(I->second, GV, PtrVal);
1061 if (I->second.isOverdefined())
1062 TrackedGlobals.erase(I); // No need to keep tracking this!
1063}
1064
1065
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001066// Handle load instructions. If the operand is a constant pointer to a constant
1067// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001068void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001069 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001070 if (IV.isOverdefined()) return;
1071
Chris Lattneref36dfd2004-11-15 05:03:30 +00001072 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001073 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1074 if (PtrVal.isConstant() && !I.isVolatile()) {
1075 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001076 // TODO: Consider a target hook for valid address spaces for this xform.
1077 if (isa<ConstantPointerNull>(Ptr) &&
1078 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001079 // load null -> null
1080 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1081 return;
1082 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001083
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001084 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001085 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1086 if (GV->isConstant()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001087 if (!GV->isDeclaration()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001088 markConstant(IV, &I, GV->getInitializer());
1089 return;
1090 }
1091 } else if (!TrackedGlobals.empty()) {
1092 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001093 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001094 TrackedGlobals.find(GV);
1095 if (It != TrackedGlobals.end()) {
1096 mergeInValue(IV, &I, It->second);
1097 return;
1098 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001099 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001100 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001101
1102 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1103 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1104 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001105 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00001106 if (GV->isConstant() && !GV->isDeclaration())
Jeff Cohen9d809302005-04-23 21:38:35 +00001107 if (Constant *V =
Chris Lattnerebe61202005-09-26 05:28:52 +00001108 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001109 markConstant(IV, &I, V);
1110 return;
1111 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001112 }
1113
1114 // Otherwise we cannot say for certain what value this load will produce.
1115 // Bail out.
1116 markOverdefined(IV, &I);
1117}
Chris Lattner58b7b082004-04-13 19:43:54 +00001118
Chris Lattner59acc7d2004-12-10 08:02:06 +00001119void SCCPSolver::visitCallSite(CallSite CS) {
1120 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001121 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001122
1123 // The common case is that we aren't tracking the callee, either because we
1124 // are not doing interprocedural analysis or the callee is indirect, or is
1125 // external. Handle these cases first.
1126 if (F == 0 || !F->hasInternalLinkage()) {
1127CallOverdefined:
1128 // Void return and not tracking callee, just bail.
1129 if (I->getType() == Type::VoidTy) return;
1130
1131 // Otherwise, if we have a single return value case, and if the function is
1132 // a declaration, maybe we can constant fold it.
1133 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1134 canConstantFoldCallTo(F)) {
1135
1136 SmallVector<Constant*, 8> Operands;
1137 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1138 AI != E; ++AI) {
1139 LatticeVal &State = getValueState(*AI);
1140 if (State.isUndefined())
1141 return; // Operands are not resolved yet.
1142 else if (State.isOverdefined()) {
1143 markOverdefined(I);
1144 return;
1145 }
1146 assert(State.isConstant() && "Unknown state!");
1147 Operands.push_back(State.getConstant());
1148 }
1149
1150 // If we can constant fold this, mark the result of the call as a
1151 // constant.
1152 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1153 markConstant(I, C);
1154 return;
1155 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001156 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001157
1158 // Otherwise, we don't know anything about this call, mark it overdefined.
1159 markOverdefined(I);
1160 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001161 }
1162
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001163 // If this is a single/zero retval case, see if we're tracking the function.
1164 const StructType *RetSTy = dyn_cast<StructType>(I->getType());
1165 if (RetSTy == 0) {
1166 // Check to see if we're tracking this callee, if not, handle it in the
1167 // common path above.
1168 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1169 if (TFRVI == TrackedRetVals.end())
1170 goto CallOverdefined;
1171
1172 // If so, propagate the return value of the callee into this call result.
1173 mergeInValue(I, TFRVI->second);
1174 } else {
1175 // Check to see if we're tracking this callee, if not, handle it in the
1176 // common path above.
1177 std::map<std::pair<Function*, unsigned>, LatticeVal>::iterator
1178 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
1179 if (TMRVI == TrackedMultipleRetVals.end())
1180 goto CallOverdefined;
1181
1182 // If we are tracking this callee, propagate the return values of the call
1183 // into this call site. We do this by walking all the getresult uses.
1184 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1185 UI != E; ++UI) {
1186 GetResultInst *GRI = cast<GetResultInst>(*UI);
1187 mergeInValue(GRI,
1188 TrackedMultipleRetVals[std::make_pair(F, GRI->getIndex())]);
1189 }
1190 }
1191
1192 // Finally, if this is the first call to the function hit, mark its entry
1193 // block executable.
1194 if (!BBExecutable.count(F->begin()))
1195 MarkBlockExecutable(F->begin());
1196
1197 // Propagate information from this call site into the callee.
1198 CallSite::arg_iterator CAI = CS.arg_begin();
1199 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1200 AI != E; ++AI, ++CAI) {
1201 LatticeVal &IV = ValueState[AI];
1202 if (!IV.isOverdefined())
1203 mergeInValue(IV, AI, getValueState(*CAI));
1204 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001205}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001206
1207
1208void SCCPSolver::Solve() {
1209 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001210 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001211 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001212 // Process the instruction work list...
1213 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001214 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001215 OverdefinedInstWorkList.pop_back();
1216
Bill Wendlingb7427032006-11-26 09:46:52 +00001217 DOUT << "\nPopped off OI-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001218
Chris Lattner82bec2c2004-11-15 04:44:20 +00001219 // "I" got into the work list because it either made the transition from
1220 // bottom to constant
1221 //
1222 // Anything on this worklist that is overdefined need not be visited
1223 // since all of its users will have already been marked as overdefined
1224 // Update all of the users of this instruction's value...
1225 //
1226 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1227 UI != E; ++UI)
1228 OperandChangedState(*UI);
1229 }
1230 // Process the instruction work list...
1231 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001232 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001233 InstWorkList.pop_back();
1234
Bill Wendlingb7427032006-11-26 09:46:52 +00001235 DOUT << "\nPopped off I-WL: " << *I;
Misha Brukmanfd939082005-04-21 23:48:37 +00001236
Chris Lattner82bec2c2004-11-15 04:44:20 +00001237 // "I" got into the work list because it either made the transition from
1238 // bottom to constant
1239 //
1240 // Anything on this worklist that is overdefined need not be visited
1241 // since all of its users will have already been marked as overdefined.
1242 // Update all of the users of this instruction's value...
1243 //
1244 if (!getValueState(I).isOverdefined())
1245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1246 UI != E; ++UI)
1247 OperandChangedState(*UI);
1248 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001249
Chris Lattner82bec2c2004-11-15 04:44:20 +00001250 // Process the basic block work list...
1251 while (!BBWorkList.empty()) {
1252 BasicBlock *BB = BBWorkList.back();
1253 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001254
Bill Wendlingb7427032006-11-26 09:46:52 +00001255 DOUT << "\nPopped off BBWL: " << *BB;
Misha Brukmanfd939082005-04-21 23:48:37 +00001256
Chris Lattner82bec2c2004-11-15 04:44:20 +00001257 // Notify all instructions in this basic block that they are newly
1258 // executable.
1259 visit(BB);
1260 }
1261 }
1262}
1263
Chris Lattner3bad2532006-12-20 06:21:33 +00001264/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001265/// that branches on undef values cannot reach any of their successors.
1266/// However, this is not a safe assumption. After we solve dataflow, this
1267/// method should be use to handle this. If this returns true, the solver
1268/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001269///
1270/// This method handles this by finding an unresolved branch and marking it one
1271/// of the edges from the block as being feasible, even though the condition
1272/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1273/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001274/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001275/// constraints on the condition of the branch, as that would impact other users
1276/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001277///
1278/// This scan also checks for values that use undefs, whose results are actually
1279/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1280/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1281/// even if X isn't defined.
1282bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001283 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1284 if (!BBExecutable.count(BB))
1285 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001286
1287 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1288 // Look for instructions which produce undef values.
1289 if (I->getType() == Type::VoidTy) continue;
1290
1291 LatticeVal &LV = getValueState(I);
1292 if (!LV.isUndefined()) continue;
1293
1294 // Get the lattice values of the first two operands for use below.
1295 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1296 LatticeVal Op1LV;
1297 if (I->getNumOperands() == 2) {
1298 // If this is a two-operand instruction, and if both operands are
1299 // undefs, the result stays undef.
1300 Op1LV = getValueState(I->getOperand(1));
1301 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1302 continue;
1303 }
1304
1305 // If this is an instructions whose result is defined even if the input is
1306 // not fully defined, propagate the information.
1307 const Type *ITy = I->getType();
1308 switch (I->getOpcode()) {
1309 default: break; // Leave the instruction as an undef.
1310 case Instruction::ZExt:
1311 // After a zero extend, we know the top part is zero. SExt doesn't have
1312 // to be handled here, because we don't know whether the top part is 1's
1313 // or 0's.
1314 assert(Op0LV.isUndefined());
1315 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1316 return true;
1317 case Instruction::Mul:
1318 case Instruction::And:
1319 // undef * X -> 0. X could be zero.
1320 // undef & X -> 0. X could be zero.
1321 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1322 return true;
1323
1324 case Instruction::Or:
1325 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001326 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1327 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001328 else
1329 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1330 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001331
1332 case Instruction::SDiv:
1333 case Instruction::UDiv:
1334 case Instruction::SRem:
1335 case Instruction::URem:
1336 // X / undef -> undef. No change.
1337 // X % undef -> undef. No change.
1338 if (Op1LV.isUndefined()) break;
1339
1340 // undef / X -> 0. X could be maxint.
1341 // undef % X -> 0. X could be 1.
1342 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1343 return true;
1344
1345 case Instruction::AShr:
1346 // undef >>s X -> undef. No change.
1347 if (Op0LV.isUndefined()) break;
1348
1349 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1350 if (Op0LV.isConstant())
1351 markForcedConstant(LV, I, Op0LV.getConstant());
1352 else
1353 markOverdefined(LV, I);
1354 return true;
1355 case Instruction::LShr:
1356 case Instruction::Shl:
1357 // undef >> X -> undef. No change.
1358 // undef << X -> undef. No change.
1359 if (Op0LV.isUndefined()) break;
1360
1361 // X >> undef -> 0. X could be 0.
1362 // X << undef -> 0. X could be 0.
1363 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1364 return true;
1365 case Instruction::Select:
1366 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1367 if (Op0LV.isUndefined()) {
1368 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1369 Op1LV = getValueState(I->getOperand(2));
1370 } else if (Op1LV.isUndefined()) {
1371 // c ? undef : undef -> undef. No change.
1372 Op1LV = getValueState(I->getOperand(2));
1373 if (Op1LV.isUndefined())
1374 break;
1375 // Otherwise, c ? undef : x -> x.
1376 } else {
1377 // Leave Op1LV as Operand(1)'s LatticeValue.
1378 }
1379
1380 if (Op1LV.isConstant())
1381 markForcedConstant(LV, I, Op1LV.getConstant());
1382 else
1383 markOverdefined(LV, I);
1384 return true;
1385 }
1386 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001387
1388 TerminatorInst *TI = BB->getTerminator();
1389 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1390 if (!BI->isConditional()) continue;
1391 if (!getValueState(BI->getCondition()).isUndefined())
1392 continue;
1393 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1394 if (!getValueState(SI->getCondition()).isUndefined())
1395 continue;
1396 } else {
1397 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001398 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001399
Chris Lattner05bb7892008-01-28 00:32:30 +00001400 // If the edge to the second successor isn't thought to be feasible yet,
1401 // mark it so now. We pick the second one so that this goes to some
1402 // enumerated value in a switch instead of going to the default destination.
1403 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001404 continue;
1405
1406 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1407 // and return. This will make other blocks reachable, which will allow new
1408 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001409 markEdgeExecutable(BB, TI->getSuccessor(1));
1410
1411 // This must be a conditional branch of switch on undef. At this point,
1412 // force the old terminator to branch to the first successor. This is
1413 // required because we are now influencing the dataflow of the function with
1414 // the assumption that this edge is taken. If we leave the branch condition
1415 // as undef, then further analysis could think the undef went another way
1416 // leading to an inconsistent set of conclusions.
1417 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1418 BI->setCondition(ConstantInt::getFalse());
1419 } else {
1420 SwitchInst *SI = cast<SwitchInst>(TI);
1421 SI->setCondition(SI->getCaseValue(1));
1422 }
1423
Chris Lattnerd2d86702006-10-22 05:59:17 +00001424 return true;
1425 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001426
Chris Lattnerd2d86702006-10-22 05:59:17 +00001427 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001428}
1429
Chris Lattner82bec2c2004-11-15 04:44:20 +00001430
1431namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001432 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001433 //
Chris Lattner14051812004-11-15 07:15:04 +00001434 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001435 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001436 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001437 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001438 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +00001439 SCCP() : FunctionPass((intptr_t)&ID) {}
1440
Chris Lattner14051812004-11-15 07:15:04 +00001441 // runOnFunction - Run the Sparse Conditional Constant Propagation
1442 // algorithm, and return true if the function was modified.
1443 //
1444 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001445
Chris Lattner14051812004-11-15 07:15:04 +00001446 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1447 AU.setPreservesCFG();
1448 }
1449 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001450
Devang Patel19974732007-05-03 01:11:54 +00001451 char SCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001452 RegisterPass<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001453} // end anonymous namespace
1454
1455
1456// createSCCPPass - This is the public interface to this file...
1457FunctionPass *llvm::createSCCPPass() {
1458 return new SCCP();
1459}
1460
1461
Chris Lattner82bec2c2004-11-15 04:44:20 +00001462// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1463// and return true if the function was modified.
1464//
1465bool SCCP::runOnFunction(Function &F) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001466 DOUT << "SCCP on function '" << F.getName() << "'\n";
Chris Lattner82bec2c2004-11-15 04:44:20 +00001467 SCCPSolver Solver;
1468
1469 // Mark the first block of the function as being executable.
1470 Solver.MarkBlockExecutable(F.begin());
1471
Chris Lattner7e529e42004-11-15 05:45:33 +00001472 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001473 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001474 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001475
Chris Lattner82bec2c2004-11-15 04:44:20 +00001476 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001477 bool ResolvedUndefs = true;
1478 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001479 Solver.Solve();
Chris Lattner3bad2532006-12-20 06:21:33 +00001480 DOUT << "RESOLVING UNDEFs\n";
1481 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001482 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001483
Chris Lattner7e529e42004-11-15 05:45:33 +00001484 bool MadeChanges = false;
1485
1486 // If we decided that there are basic blocks that are dead in this function,
1487 // delete their contents now. Note that we cannot actually delete the blocks,
1488 // as we cannot modify the CFG of the function.
1489 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001490 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001491 SmallVector<Instruction*, 32> Insts;
Chris Lattner57939df2007-03-04 04:50:21 +00001492 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
1493
Chris Lattner7e529e42004-11-15 05:45:33 +00001494 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1495 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001496 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001497 ++NumDeadBlocks;
1498
Chris Lattner7e529e42004-11-15 05:45:33 +00001499 // Delete the instructions backwards, as it has a reduced likelihood of
1500 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001501 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1502 I != E; ++I)
1503 Insts.push_back(I);
1504 while (!Insts.empty()) {
1505 Instruction *I = Insts.back();
1506 Insts.pop_back();
1507 if (!I->use_empty())
1508 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1509 BB->getInstList().erase(I);
1510 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001511 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001512 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001513 } else {
1514 // Iterate over all of the instructions in a function, replacing them with
1515 // constants if we have found them to be of constant values.
1516 //
1517 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1518 Instruction *Inst = BI++;
Chris Lattner7cb22ec2008-04-24 00:19:54 +00001519 if (Inst->getType() == Type::VoidTy ||
1520 isa<StructType>(Inst->getType()) ||
Chris Lattnerf4023a12008-04-24 00:16:28 +00001521 isa<TerminatorInst>(Inst))
1522 continue;
1523
1524 LatticeVal &IV = Values[Inst];
1525 if (!IV.isConstant() && !IV.isUndefined())
1526 continue;
1527
1528 Constant *Const = IV.isConstant()
1529 ? IV.getConstant() : UndefValue::get(Inst->getType());
1530 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001531
Chris Lattnerf4023a12008-04-24 00:16:28 +00001532 // Replaces all of the uses of a variable with uses of the constant.
1533 Inst->replaceAllUsesWith(Const);
1534
1535 // Delete the instruction.
1536 Inst->eraseFromParent();
1537
1538 // Hey, we just changed something!
1539 MadeChanges = true;
1540 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001541 }
1542 }
1543
1544 return MadeChanges;
1545}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001546
1547namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001548 //===--------------------------------------------------------------------===//
1549 //
1550 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1551 /// Constant Propagation.
1552 ///
Reid Spencer9133fe22007-02-05 23:32:05 +00001553 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001554 static char ID;
Devang Patel794fd752007-05-01 21:15:47 +00001555 IPSCCP() : ModulePass((intptr_t)&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001556 bool runOnModule(Module &M);
1557 };
1558
Devang Patel19974732007-05-03 01:11:54 +00001559 char IPSCCP::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +00001560 RegisterPass<IPSCCP>
Chris Lattner59acc7d2004-12-10 08:02:06 +00001561 Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1562} // end anonymous namespace
1563
1564// createIPSCCPPass - This is the public interface to this file...
1565ModulePass *llvm::createIPSCCPPass() {
1566 return new IPSCCP();
1567}
1568
1569
1570static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001571 // Delete any dead constantexpr klingons.
1572 GV->removeDeadConstantUsers();
1573
Chris Lattner59acc7d2004-12-10 08:02:06 +00001574 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1575 UI != E; ++UI)
1576 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001577 if (SI->getOperand(0) == GV || SI->isVolatile())
1578 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001579 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1580 // Make sure we are calling the function, not passing the address.
1581 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1582 for (CallSite::arg_iterator AI = CS.arg_begin(),
1583 E = CS.arg_end(); AI != E; ++AI)
1584 if (*AI == GV)
1585 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001586 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1587 if (LI->isVolatile())
1588 return true;
1589 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001590 return true;
1591 }
1592 return false;
1593}
1594
1595bool IPSCCP::runOnModule(Module &M) {
1596 SCCPSolver Solver;
1597
1598 // Loop over all functions, marking arguments to those with their addresses
1599 // taken or that are external as overdefined.
1600 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001601 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1602 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001603 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001604 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001605 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1606 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001607 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001608 } else {
1609 Solver.AddTrackedFunction(F);
1610 }
1611
Chris Lattnerdd336d12004-12-11 05:15:59 +00001612 // Loop over global variables. We inform the solver about any internal global
1613 // variables that do not have their 'addresses taken'. If they don't have
1614 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001615 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1616 G != E; ++G)
Chris Lattnerdd336d12004-12-11 05:15:59 +00001617 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1618 Solver.TrackValueOfGlobalVariable(G);
1619
Chris Lattner59acc7d2004-12-10 08:02:06 +00001620 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001621 bool ResolvedUndefs = true;
1622 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001623 Solver.Solve();
1624
Chris Lattner3bad2532006-12-20 06:21:33 +00001625 DOUT << "RESOLVING UNDEFS\n";
1626 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001627 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001628 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001629 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001630
1631 bool MadeChanges = false;
1632
1633 // Iterate over all of the instructions in the module, replacing them with
1634 // constants if we have found them to be of constant values.
1635 //
Chris Lattnercc56aad2007-02-02 20:57:39 +00001636 SmallSet<BasicBlock*, 16> &ExecutableBBs = Solver.getExecutableBlocks();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001637 SmallVector<Instruction*, 32> Insts;
1638 SmallVector<BasicBlock*, 32> BlocksToErase;
Chris Lattner57939df2007-03-04 04:50:21 +00001639 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001640
Chris Lattner59acc7d2004-12-10 08:02:06 +00001641 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001642 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1643 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001644 if (!AI->use_empty()) {
1645 LatticeVal &IV = Values[AI];
1646 if (IV.isConstant() || IV.isUndefined()) {
1647 Constant *CST = IV.isConstant() ?
1648 IV.getConstant() : UndefValue::get(AI->getType());
Bill Wendlingb7427032006-11-26 09:46:52 +00001649 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
Misha Brukmanfd939082005-04-21 23:48:37 +00001650
Chris Lattner59acc7d2004-12-10 08:02:06 +00001651 // Replaces all of the uses of a variable with uses of the
1652 // constant.
1653 AI->replaceAllUsesWith(CST);
1654 ++IPNumArgsElimed;
1655 }
1656 }
1657
1658 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1659 if (!ExecutableBBs.count(BB)) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001660 DOUT << " BasicBlock Dead:" << *BB;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001661 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001662
Chris Lattner59acc7d2004-12-10 08:02:06 +00001663 // Delete the instructions backwards, as it has a reduced likelihood of
1664 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001665 TerminatorInst *TI = BB->getTerminator();
1666 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001667 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001668
Chris Lattner59acc7d2004-12-10 08:02:06 +00001669 while (!Insts.empty()) {
1670 Instruction *I = Insts.back();
1671 Insts.pop_back();
1672 if (!I->use_empty())
1673 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1674 BB->getInstList().erase(I);
1675 MadeChanges = true;
1676 ++IPNumInstRemoved;
1677 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001678
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001679 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1680 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001681 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001682 TI->getSuccessor(i)->removePredecessor(BB);
1683 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001684 if (!TI->use_empty())
1685 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001686 BB->getInstList().erase(TI);
1687
Chris Lattner864737b2004-12-11 05:32:19 +00001688 if (&*BB != &F->front())
1689 BlocksToErase.push_back(BB);
1690 else
1691 new UnreachableInst(BB);
1692
Chris Lattner59acc7d2004-12-10 08:02:06 +00001693 } else {
1694 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1695 Instruction *Inst = BI++;
Chris Lattnereb5f4092008-04-24 00:21:50 +00001696 if (Inst->getType() == Type::VoidTy ||
1697 isa<StructType>(Inst->getType()) ||
1698 isa<TerminatorInst>(Inst))
1699 continue;
1700
1701 LatticeVal &IV = Values[Inst];
1702 if (!IV.isConstant() && !IV.isUndefined())
1703 continue;
1704
1705 Constant *Const = IV.isConstant()
1706 ? IV.getConstant() : UndefValue::get(Inst->getType());
1707 DOUT << " Constant: " << *Const << " = " << *Inst;
Misha Brukmanfd939082005-04-21 23:48:37 +00001708
Chris Lattnereb5f4092008-04-24 00:21:50 +00001709 // Replaces all of the uses of a variable with uses of the
1710 // constant.
1711 Inst->replaceAllUsesWith(Const);
1712
1713 // Delete the instruction.
1714 if (!isa<CallInst>(Inst))
1715 Inst->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001716
Chris Lattnereb5f4092008-04-24 00:21:50 +00001717 // Hey, we just changed something!
1718 MadeChanges = true;
1719 ++IPNumInstRemoved;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001720 }
1721 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001722
1723 // Now that all instructions in the function are constant folded, erase dead
1724 // blocks, because we can now use ConstantFoldTerminator to get rid of
1725 // in-edges.
1726 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1727 // If there are any PHI nodes in this successor, drop entries for BB now.
1728 BasicBlock *DeadBB = BlocksToErase[i];
1729 while (!DeadBB->use_empty()) {
1730 Instruction *I = cast<Instruction>(DeadBB->use_back());
1731 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001732 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001733 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001734 // if this is a branch or switch on undef. Fold it manually as a
1735 // branch to the first successor.
1736 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1737 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1738 "Branch should be foldable!");
1739 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1740 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1741 } else {
1742 assert(0 && "Didn't fold away reference to block!");
1743 }
1744
1745 // Make this an uncond branch to the first successor.
1746 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001747 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001748
1749 // Remove entries in successor phi nodes to remove edges.
1750 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1751 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1752
1753 // Remove the old terminator.
1754 TI->eraseFromParent();
1755 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001756 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001757
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001758 // Finally, delete the basic block.
1759 F->getBasicBlockList().erase(DeadBB);
1760 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001761 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001762 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001763
1764 // If we inferred constant or undef return values for a function, we replaced
1765 // all call uses with the inferred value. This means we don't need to bother
1766 // actually returning anything from the function. Replace all return
1767 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001768 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001769 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001770 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001771 E = RV.end(); I != E; ++I)
1772 if (!I->second.isOverdefined() &&
1773 I->first->getReturnType() != Type::VoidTy) {
1774 Function *F = I->first;
1775 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1776 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1777 if (!isa<UndefValue>(RI->getOperand(0)))
1778 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1779 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001780
1781 // If we infered constant or undef values for globals variables, we can delete
1782 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001783 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1784 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001785 E = TG.end(); I != E; ++I) {
1786 GlobalVariable *GV = I->first;
1787 assert(!I->second.isOverdefined() &&
1788 "Overdefined values should have been taken out of the map!");
Bill Wendlingb7427032006-11-26 09:46:52 +00001789 DOUT << "Found that GV '" << GV->getName()<< "' is constant!\n";
Chris Lattnerdd336d12004-12-11 05:15:59 +00001790 while (!GV->use_empty()) {
1791 StoreInst *SI = cast<StoreInst>(GV->use_back());
1792 SI->eraseFromParent();
1793 }
1794 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001795 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001796 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001797
Chris Lattner59acc7d2004-12-10 08:02:06 +00001798 return MadeChanges;
1799}