blob: 509a6dbc12f055c87a4f36180acf8f9c78c5b1bb [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//
Chris Lattner138a1242001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattneref36dfd2004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000022#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000023#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000024#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000025#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000026#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000031#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattner09275292009-11-02 06:11:23 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000043#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000044#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(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///
Chris Lattner3e8b6632009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000059 enum LatticeValueTy {
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
Chris Lattner79272202009-11-02 02:20:32 +000075 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner79272202009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Chris Lattner138a1242001-06-27 23:38:11 +000085public:
Chris Lattner38871e42009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000087
Chris Lattner38871e42009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattner38871e42009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner79272202009-11-02 02:20:32 +000093
Chris Lattner38871e42009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000095 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
97 }
98
99 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000106 }
107
Chris Lattner79272202009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattnerc175e5d2009-11-03 16:50:11 +0000110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattner79272202009-11-02 02:20:32 +0000111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000113 }
Chris Lattner79272202009-11-02 02:20:32 +0000114
115 if (isUndefined()) {
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
118 Val.setPointer(V);
119 } else {
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
124
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
129 }
130 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000131 }
132
Chris Lattner36c99522009-11-02 03:21:36 +0000133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
136 if (isConstant())
137 return dyn_cast<ConstantInt>(getConstant());
138 return 0;
139 }
140
Chris Lattner38871e42009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000145 }
Chris Lattner138a1242001-06-27 23:38:11 +0000146};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000151
Chris Lattner138a1242001-06-27 23:38:11 +0000152//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000153//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000154/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155/// Constant Propagation.
156///
157class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000158 const TargetData *TD;
Chris Lattner09275292009-11-02 06:11:23 +0000159 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000161
Chris Lattnerfc36a562009-11-03 23:40:48 +0000162 /// StructValueState - This maintains ValueState for values that have
163 /// StructType, for example for formal arguments, calls, insertelement, etc.
164 ///
165 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
166
Chris Lattnerdd336d12004-12-11 05:15:59 +0000167 /// GlobalValue - If we are tracking any values for the contents of a global
168 /// variable, we keep a mapping from the constant accessor to the element of
169 /// the global, to the currently known value. If the value becomes
170 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000171 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000172
Devang Patel7c490d42008-03-11 05:46:42 +0000173 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000174 /// value out of a function, it will have an entry in this map, indicating
175 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000176 DenseMap<Function*, LatticeVal> TrackedRetVals;
177
178 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
179 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000181
182 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
183 /// represented here for efficient lookup.
184 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000185
Chris Lattnerabf67ef2009-11-03 20:52:57 +0000186 /// TrackingIncomingArguments - This is the set of functions for whose
187 /// arguments we make optimistic assumptions about and try to prove as
188 /// constants.
Chris Lattner2396cc32009-11-03 19:24:51 +0000189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
190
Chris Lattner38871e42009-11-02 03:03:42 +0000191 /// The reason for two worklists is that overdefined is the lowest state
192 /// on the lattice, and moving things to overdefined as fast as possible
193 /// makes SCCP converge much faster.
194 ///
195 /// By having a separate worklist, we accomplish this because everything
196 /// possibly overdefined will become overdefined at the soonest possible
197 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000200
201
Chris Lattnercf712de2008-08-23 23:36:38 +0000202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000203
Chris Lattner1daee8b2004-01-12 03:57:30 +0000204 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
205 /// overdefined, despite the fact that the PHI node is overdefined.
206 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
207
Chris Lattner16b18fd2003-10-08 16:55:34 +0000208 /// KnownFeasibleEdges - Entries in this set are edges which have already had
209 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000210 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
211 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000212public:
Chris Lattner5638dc62009-11-02 06:06:14 +0000213 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000214
Chris Lattner82bec2c2004-11-15 04:44:20 +0000215 /// MarkBlockExecutable - This method can be used by clients to mark all of
216 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner09275292009-11-02 06:11:23 +0000217 ///
218 /// This returns true if the block was not considered live before.
219 bool MarkBlockExecutable(BasicBlock *BB) {
220 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000221 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000222 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner09275292009-11-02 06:11:23 +0000223 return true;
Chris Lattner0dbfc052002-04-29 21:26:08 +0000224 }
225
Chris Lattnerdd336d12004-12-11 05:15:59 +0000226 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000227 /// inform the SCCPSolver that it should track loads and stores to the
228 /// specified global variable if it can. This is only legal to call if
229 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000230 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000231 // We only track the contents of scalar globals.
232 if (GV->getType()->getElementType()->isSingleValueType()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000233 LatticeVal &IV = TrackedGlobals[GV];
234 if (!isa<UndefValue>(GV->getInitializer()))
235 IV.markConstant(GV->getInitializer());
236 }
237 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000238
239 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
240 /// and out of the specified function (which cannot have its address taken),
241 /// this method must be called.
242 void AddTrackedFunction(Function *F) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000243 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000244 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000245 MRVFunctionsTracked.insert(F);
Devang Patel7c490d42008-03-11 05:46:42 +0000246 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000247 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248 LatticeVal()));
249 } else
250 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000251 }
252
Chris Lattner2396cc32009-11-03 19:24:51 +0000253 void AddArgumentTrackedFunction(Function *F) {
254 TrackingIncomingArguments.insert(F);
255 }
256
Chris Lattner82bec2c2004-11-15 04:44:20 +0000257 /// Solve - Solve for constants and executable blocks.
258 ///
259 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000260
Chris Lattner3bad2532006-12-20 06:21:33 +0000261 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000262 /// that branches on undef values cannot reach any of their successors.
263 /// However, this is not a safe assumption. After we solve dataflow, this
264 /// method should be use to handle this. If this returns true, the solver
265 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000266 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000267
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000268 bool isBlockExecutable(BasicBlock *BB) const {
269 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000270 }
271
Chris Lattner8db50122009-11-02 02:54:24 +0000272 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000273 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000274 assert(I != ValueState.end() && "V is not in valuemap!");
275 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000276 }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000277
278 LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
279 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
280 StructValueState.find(std::make_pair(V, i));
281 assert(I != StructValueState.end() && "V is not in valuemap!");
282 return I->second;
283 }
Chris Lattner82bec2c2004-11-15 04:44:20 +0000284
Devang Patel7c490d42008-03-11 05:46:42 +0000285 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000286 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000287 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000289 }
290
Chris Lattnerdd336d12004-12-11 05:15:59 +0000291 /// getTrackedGlobals - Get and return the set of inferred initializers for
292 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000293 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000294 return TrackedGlobals;
295 }
296
Chris Lattner36c99522009-11-02 03:21:36 +0000297 void markOverdefined(Value *V) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000298 assert(!isa<StructType>(V->getType()) && "Should use other method");
Chris Lattner57939df2007-03-04 04:50:21 +0000299 markOverdefined(ValueState[V], V);
300 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000301
Chris Lattnerfc36a562009-11-03 23:40:48 +0000302 /// markAnythingOverdefined - Mark the specified value overdefined. This
303 /// works with both scalars and structs.
304 void markAnythingOverdefined(Value *V) {
305 if (const StructType *STy = dyn_cast<StructType>(V->getType()))
306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
307 markOverdefined(getStructValueState(V, i), V);
308 else
309 markOverdefined(V);
310 }
311
Chris Lattner138a1242001-06-27 23:38:11 +0000312private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000313 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000314 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000315 // the users of the instruction are updated later.
316 //
Chris Lattner38871e42009-11-02 03:03:42 +0000317 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
318 if (!IV.markConstant(C)) return;
319 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
320 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000321 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000322
Chris Lattner38871e42009-11-02 03:03:42 +0000323 void markConstant(Value *V, Constant *C) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000324 assert(!isa<StructType>(V->getType()) && "Should use other method");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000325 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000326 }
327
Chris Lattner2a0433b2009-11-02 05:55:40 +0000328 void markForcedConstant(Value *V, Constant *C) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000329 assert(!isa<StructType>(V->getType()) && "Should use other method");
Chris Lattner2a0433b2009-11-02 05:55:40 +0000330 ValueState[V].markForcedConstant(C);
331 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
332 InstWorkList.push_back(V);
333 }
334
335
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000336 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000337 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000338 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000339 void markOverdefined(LatticeVal &IV, Value *V) {
340 if (!IV.markOverdefined()) return;
341
342 DEBUG(errs() << "markOverdefined: ";
343 if (Function *F = dyn_cast<Function>(V))
344 errs() << "Function '" << F->getName() << "'\n";
345 else
346 errs() << *V << '\n');
347 // Only instructions go on the work list
348 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000349 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000350
Chris Lattner2a0433b2009-11-02 05:55:40 +0000351 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000352 if (IV.isOverdefined() || MergeWithV.isUndefined())
353 return; // Noop.
354 if (MergeWithV.isOverdefined())
355 markOverdefined(IV, V);
356 else if (IV.isUndefined())
357 markConstant(IV, V, MergeWithV.getConstant());
358 else if (IV.getConstant() != MergeWithV.getConstant())
359 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000360 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000361
Chris Lattner2a0433b2009-11-02 05:55:40 +0000362 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000363 assert(!isa<StructType>(V->getType()) && "Should use other method");
Chris Lattner36c99522009-11-02 03:21:36 +0000364 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000365 }
366
Chris Lattner138a1242001-06-27 23:38:11 +0000367
Chris Lattner2a0433b2009-11-02 05:55:40 +0000368 /// getValueState - Return the LatticeVal object that corresponds to the
369 /// value. This function handles the case when the value hasn't been seen yet
370 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000371 LatticeVal &getValueState(Value *V) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000372 assert(!isa<StructType>(V->getType()) && "Should use getStructValueState");
Chris Lattner5d356a72004-10-16 18:09:41 +0000373
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000374 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
375 ValueState.insert(std::make_pair(V, LatticeVal()));
376 LatticeVal &LV = I.first->second;
377
378 if (!I.second)
379 return LV; // Common case, already in the map.
Chris Lattner36c99522009-11-02 03:21:36 +0000380
Chris Lattner3bad2532006-12-20 06:21:33 +0000381 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000382 // Undef values remain undefined.
383 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000384 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000385 }
Chris Lattner36c99522009-11-02 03:21:36 +0000386
Chris Lattner2f096252009-11-02 02:33:50 +0000387 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000388 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000389 }
390
Chris Lattnerfc36a562009-11-03 23:40:48 +0000391 /// getStructValueState - Return the LatticeVal object that corresponds to the
392 /// value/field pair. This function handles the case when the value hasn't
393 /// been seen yet by properly seeding constants etc.
394 LatticeVal &getStructValueState(Value *V, unsigned i) {
395 assert(isa<StructType>(V->getType()) && "Should use getValueState");
396 assert(i < cast<StructType>(V->getType())->getNumElements() &&
397 "Invalid element #");
Benjamin Kramerbcaa2152009-11-05 14:33:27 +0000398
399 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
400 bool> I = StructValueState.insert(
401 std::make_pair(std::make_pair(V, i), LatticeVal()));
402 LatticeVal &LV = I.first->second;
403
404 if (!I.second)
405 return LV; // Common case, already in the map.
406
Chris Lattnerfc36a562009-11-03 23:40:48 +0000407 if (Constant *C = dyn_cast<Constant>(V)) {
408 if (isa<UndefValue>(C))
409 ; // Undef values remain undefined.
410 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
411 LV.markConstant(CS->getOperand(i)); // Constants are constant.
412 else if (isa<ConstantAggregateZero>(C)) {
413 const Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
414 LV.markConstant(Constant::getNullValue(FieldTy));
415 } else
416 LV.markOverdefined(); // Unknown sort of constant.
417 }
418
419 // All others are underdefined by default.
420 return LV;
421 }
422
423
Chris Lattner2a0433b2009-11-02 05:55:40 +0000424 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
425 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000426 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
427 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
428 return; // This edge is already known to be executable!
429
Chris Lattner09275292009-11-02 06:11:23 +0000430 if (!MarkBlockExecutable(Dest)) {
431 // If the destination is already executable, we just made an *edge*
432 // feasible that wasn't before. Revisit the PHI nodes in the block
433 // because they have potentially new operands.
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000434 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
435 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000436
Chris Lattner09275292009-11-02 06:11:23 +0000437 PHINode *PN;
438 for (BasicBlock::iterator I = Dest->begin();
439 (PN = dyn_cast<PHINode>(I)); ++I)
440 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000441 }
Chris Lattner138a1242001-06-27 23:38:11 +0000442 }
443
Chris Lattner82bec2c2004-11-15 04:44:20 +0000444 // getFeasibleSuccessors - Return a vector of booleans to indicate which
445 // successors are reachable from a given terminator instruction.
446 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000447 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000448
449 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000450 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000451 //
452 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
453
454 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000455 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000456 // information, we need to update the specified user of this instruction.
457 //
Chris Lattner14532d02009-11-03 03:42:51 +0000458 void OperandChangedState(Instruction *I) {
459 if (BBExecutable.count(I->getParent())) // Inst is executable?
460 visit(*I);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000461 }
Chris Lattnere01985c2009-11-02 06:28:16 +0000462
463 /// RemoveFromOverdefinedPHIs - If I has any entries in the
464 /// UsersOfOverdefinedPHIs map for PN, remove them now.
465 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
466 if (UsersOfOverdefinedPHIs.empty()) return;
467 std::multimap<PHINode*, Instruction*>::iterator It, E;
468 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN);
469 while (It != E) {
470 if (It->second == I)
471 UsersOfOverdefinedPHIs.erase(It++);
472 else
473 ++It;
474 }
475 }
Chris Lattner82bec2c2004-11-15 04:44:20 +0000476
477private:
478 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000479
Chris Lattner2f096252009-11-02 02:33:50 +0000480 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000481 // operand made a transition, or the instruction is newly executable. Change
482 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000483 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000484
485 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000486 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000487 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000488
Chris Lattnerb8047602002-08-14 17:53:45 +0000489 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000490 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000491 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000492 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000493 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000494 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000495 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000496 void visitExtractValueInst(ExtractValueInst &EVI);
497 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000498
Chris Lattner2f096252009-11-02 02:33:50 +0000499 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000500 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000501 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000502 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000503 void visitCallInst (CallInst &I) {
Chris Lattner32c0d222009-09-27 21:35:11 +0000504 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000505 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000506 void visitInvokeInst (InvokeInst &II) {
507 visitCallSite(CallSite::get(&II));
508 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000509 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000510 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000511 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000512 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000513 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000514 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnerfc36a562009-11-03 23:40:48 +0000515 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000516
Chris Lattner7e708292002-06-25 16:13:24 +0000517 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000518 // If a new instruction is added to LLVM that we don't handle.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000519 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattnerfc36a562009-11-03 23:40:48 +0000520 markAnythingOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000521 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000522};
Chris Lattnerf6293092002-07-23 18:06:35 +0000523
Duncan Sandse2abf122007-07-20 08:56:21 +0000524} // end anonymous namespace
525
526
Chris Lattnerb9a66342002-05-02 21:44:00 +0000527// getFeasibleSuccessors - Return a vector of booleans to indicate which
528// successors are reachable from a given terminator instruction.
529//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000530void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000531 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000532 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000533 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000534 if (BI->isUnconditional()) {
535 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000536 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000537 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000538
Chris Lattner2a0433b2009-11-02 05:55:40 +0000539 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000540 ConstantInt *CI = BCValue.getConstantInt();
541 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000542 // Overdefined condition variables, and branches on unfoldable constant
543 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000544 if (!BCValue.isUndefined())
545 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000546 return;
547 }
548
549 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000550 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000551 return;
552 }
553
Chris Lattner36c99522009-11-02 03:21:36 +0000554 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000555 // Invoke instructions successors are always executable.
556 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000557 return;
558 }
559
560 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000561 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000562 ConstantInt *CI = SCValue.getConstantInt();
563
564 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000565 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000566 if (!SCValue.isUndefined())
567 Succs.assign(TI.getNumSuccessors(), true);
568 return;
569 }
570
571 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000572 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000573 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000574
575 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
576 if (isa<IndirectBrInst>(&TI)) {
577 // Just mark all destinations executable!
578 Succs.assign(TI.getNumSuccessors(), true);
579 return;
580 }
581
582#ifndef NDEBUG
583 errs() << "Unknown terminator instruction: " << TI << '\n';
584#endif
585 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000586}
587
588
Chris Lattner59f0ce22002-05-02 21:18:01 +0000589// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000590// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000591//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000592bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000593 assert(BBExecutable.count(To) && "Dest should always be alive!");
594
595 // Make sure the source basic block is executable!!
596 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000597
Chris Lattner2f096252009-11-02 02:33:50 +0000598 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000599 TerminatorInst *TI = From->getTerminator();
600 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
601 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000602 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000603
Chris Lattner2a0433b2009-11-02 05:55:40 +0000604 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000605
Chris Lattnerea0db072009-11-02 02:30:06 +0000606 // Overdefined condition variables mean the branch could go either way,
607 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000608 ConstantInt *CI = BCValue.getConstantInt();
609 if (CI == 0)
610 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000611
Chris Lattnerea0db072009-11-02 02:30:06 +0000612 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000613 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000614 }
615
616 // Invoke instructions successors are always executable.
617 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000618 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000619
620 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000621 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000622 ConstantInt *CI = SCValue.getConstantInt();
623
624 if (CI == 0)
625 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000626
Chris Lattner36c99522009-11-02 03:21:36 +0000627 // Make sure to skip the "default value" which isn't a value
628 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
629 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
630 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000631
Chris Lattner36c99522009-11-02 03:21:36 +0000632 // If the constant value is not equal to any of the branches, we must
633 // execute default branch.
634 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000635 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000636
637 // Just mark all destinations executable!
638 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
639 if (isa<IndirectBrInst>(&TI))
640 return true;
641
642#ifndef NDEBUG
643 errs() << "Unknown terminator instruction: " << *TI << '\n';
644#endif
645 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000646}
Chris Lattner138a1242001-06-27 23:38:11 +0000647
Chris Lattner2f096252009-11-02 02:33:50 +0000648// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000649// operand made a transition, or the instruction is newly executable. Change
650// the value type of I to reflect these changes if appropriate. This method
651// makes sure to do the following actions:
652//
653// 1. If a phi node merges two constants in, and has conflicting value coming
654// from different branches, or if the PHI node merges in an overdefined
655// value, then the PHI node becomes overdefined.
656// 2. If a phi node merges only constants in, and they all agree on value, the
657// PHI node becomes a constant value equal to that.
658// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
659// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
660// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
661// 6. If a conditional branch has a value that is constant, make the selected
662// destination executable
663// 7. If a conditional branch has a value that is overdefined, make all
664// successors executable.
665//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000666void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000667 // If this PN returns a struct, just mark the result overdefined.
668 // TODO: We could do a lot better than this if code actually uses this.
669 if (isa<StructType>(PN.getType()))
670 return markAnythingOverdefined(&PN);
671
Chris Lattner2a0433b2009-11-02 05:55:40 +0000672 if (getValueState(&PN).isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000673 // There may be instructions using this PHI node that are not overdefined
674 // themselves. If so, make sure that they know that the PHI node operand
675 // changed.
676 std::multimap<PHINode*, Instruction*>::iterator I, E;
677 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000678 if (I == E)
679 return;
680
681 SmallVector<Instruction*, 16> Users;
682 for (; I != E; ++I)
683 Users.push_back(I->second);
684 while (!Users.empty())
685 visit(Users.pop_back_val());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000686 return; // Quick exit
687 }
Chris Lattner138a1242001-06-27 23:38:11 +0000688
Chris Lattnera2f652d2004-03-16 19:49:59 +0000689 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
690 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000691 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000692 return markOverdefined(&PN);
Chris Lattnerfc36a562009-11-03 23:40:48 +0000693
Chris Lattner2a632552002-04-18 15:13:15 +0000694 // Look at all of the executable operands of the PHI node. If any of them
695 // are overdefined, the PHI becomes overdefined as well. If they are all
696 // constant, and they agree with each other, the PHI becomes the identical
697 // constant. If they are constant and don't agree, the PHI is overdefined.
698 // If there are no executable operands, the PHI remains undefined.
699 //
Chris Lattner9de28282003-04-25 02:50:03 +0000700 Constant *OperandVal = 0;
701 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000702 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000703 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000704
Chris Lattner38871e42009-11-02 03:03:42 +0000705 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
706 continue;
707
708 if (IV.isOverdefined()) // PHI node becomes overdefined!
709 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000710
Chris Lattner38871e42009-11-02 03:03:42 +0000711 if (OperandVal == 0) { // Grab the first value.
712 OperandVal = IV.getConstant();
713 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000714 }
Chris Lattner38871e42009-11-02 03:03:42 +0000715
716 // There is already a reachable operand. If we conflict with it,
717 // then the PHI node becomes overdefined. If we agree with it, we
718 // can continue on.
719
720 // Check to see if there are two different constants merging, if so, the PHI
721 // node is overdefined.
722 if (IV.getConstant() != OperandVal)
723 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000724 }
725
Chris Lattner2a632552002-04-18 15:13:15 +0000726 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000727 // arguments that agree with each other(and OperandVal is the constant) or
728 // OperandVal is null because there are no defined incoming arguments. If
729 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000730 //
Chris Lattner9de28282003-04-25 02:50:03 +0000731 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000732 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000733}
734
Chris Lattner14532d02009-11-03 03:42:51 +0000735
736
737
Chris Lattner59acc7d2004-12-10 08:02:06 +0000738void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000739 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000740
Chris Lattner59acc7d2004-12-10 08:02:06 +0000741 Function *F = I.getParent()->getParent();
Chris Lattnerfc36a562009-11-03 23:40:48 +0000742 Value *ResultOp = I.getOperand(0);
Chris Lattner14532d02009-11-03 03:42:51 +0000743
Devang Patel7c490d42008-03-11 05:46:42 +0000744 // If we are tracking the return value of this function, merge it in.
Chris Lattnerfc36a562009-11-03 23:40:48 +0000745 if (!TrackedRetVals.empty() && !isa<StructType>(ResultOp->getType())) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000746 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000747 TrackedRetVals.find(F);
Chris Lattner14532d02009-11-03 03:42:51 +0000748 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000749 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patel7c490d42008-03-11 05:46:42 +0000750 return;
751 }
752 }
753
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000754 // Handle functions that return multiple values.
Chris Lattnerfc36a562009-11-03 23:40:48 +0000755 if (!TrackedMultipleRetVals.empty()) {
756 if (const StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
757 if (MRVFunctionsTracked.count(F))
758 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
759 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
760 getStructValueState(ResultOp, i));
761
Chris Lattner59acc7d2004-12-10 08:02:06 +0000762 }
763}
764
Chris Lattner82bec2c2004-11-15 04:44:20 +0000765void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000766 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000767 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000768
Chris Lattner16b18fd2003-10-08 16:55:34 +0000769 BasicBlock *BB = TI.getParent();
770
Chris Lattner2f096252009-11-02 02:33:50 +0000771 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000772 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000773 if (SuccFeasible[i])
774 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000775}
776
Chris Lattner82bec2c2004-11-15 04:44:20 +0000777void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000778 LatticeVal OpSt = getValueState(I.getOperand(0));
779 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000780 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000781 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000782 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000783 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000784}
785
Chris Lattnerfc36a562009-11-03 23:40:48 +0000786
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000787void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000788 // If this returns a struct, mark all elements over defined, we don't track
789 // structs in structs.
790 if (isa<StructType>(EVI.getType()))
791 return markAnythingOverdefined(&EVI);
792
793 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner38871e42009-11-02 03:03:42 +0000794 if (EVI.getNumIndices() != 1)
795 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000796
Chris Lattnerfc36a562009-11-03 23:40:48 +0000797 Value *AggVal = EVI.getAggregateOperand();
798 unsigned i = *EVI.idx_begin();
799 LatticeVal EltVal = getStructValueState(AggVal, i);
800 mergeInValue(getValueState(&EVI), &EVI, EltVal);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000801}
802
803void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000804 const StructType *STy = dyn_cast<StructType>(IVI.getType());
805 if (STy == 0)
Chris Lattner38871e42009-11-02 03:03:42 +0000806 return markOverdefined(&IVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000807
Chris Lattnerfc36a562009-11-03 23:40:48 +0000808 // If this has more than one index, we can't handle it, drive all results to
809 // undef.
810 if (IVI.getNumIndices() != 1)
811 return markAnythingOverdefined(&IVI);
812
813 Value *Aggr = IVI.getAggregateOperand();
814 unsigned Idx = *IVI.idx_begin();
815
816 // Compute the result based on what we're inserting.
817 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
818 // This passes through all values that aren't the inserted element.
819 if (i != Idx) {
820 LatticeVal EltVal = getStructValueState(Aggr, i);
821 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
822 continue;
823 }
824
825 Value *Val = IVI.getInsertedValueOperand();
826 if (isa<StructType>(Val->getType()))
827 // We don't track structs in structs.
828 markOverdefined(getStructValueState(&IVI, i), &IVI);
829 else {
830 LatticeVal InVal = getValueState(Val);
831 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
832 }
833 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000834}
835
Chris Lattner82bec2c2004-11-15 04:44:20 +0000836void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +0000837 // If this select returns a struct, just mark the result overdefined.
838 // TODO: We could do a lot better than this if code actually uses this.
839 if (isa<StructType>(I.getType()))
840 return markAnythingOverdefined(&I);
841
Chris Lattner2a0433b2009-11-02 05:55:40 +0000842 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000843 if (CondValue.isUndefined())
844 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000845
846 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000847 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
848 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000849 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000850 }
851
852 // Otherwise, the condition is overdefined or a constant we can't evaluate.
853 // See if we can produce something better than overdefined based on the T/F
854 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000855 LatticeVal TVal = getValueState(I.getTrueValue());
856 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000857
858 // select ?, C, C -> C.
859 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000860 TVal.getConstant() == FVal.getConstant())
861 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000862
Chris Lattner2a0433b2009-11-02 05:55:40 +0000863 if (TVal.isUndefined()) // select ?, undef, X -> X.
864 return mergeInValue(&I, FVal);
865 if (FVal.isUndefined()) // select ?, X, undef -> X.
866 return mergeInValue(&I, TVal);
867 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000868}
869
Chris Lattner2a0433b2009-11-02 05:55:40 +0000870// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000871void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000872 LatticeVal V1State = getValueState(I.getOperand(0));
873 LatticeVal V2State = getValueState(I.getOperand(1));
874
Chris Lattneref36dfd2004-11-15 05:03:30 +0000875 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000876 if (IV.isOverdefined()) return;
877
Chris Lattner2a0433b2009-11-02 05:55:40 +0000878 if (V1State.isConstant() && V2State.isConstant())
879 return markConstant(IV, &I,
880 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
881 V2State.getConstant()));
882
883 // If something is undef, wait for it to resolve.
884 if (!V1State.isOverdefined() && !V2State.isOverdefined())
885 return;
886
887 // Otherwise, one of our operands is overdefined. Try to produce something
888 // better than overdefined with some tricks.
889
890 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
891 // operand is overdefined.
892 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
893 LatticeVal *NonOverdefVal = 0;
894 if (!V1State.isOverdefined())
895 NonOverdefVal = &V1State;
896 else if (!V2State.isOverdefined())
897 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000898
Chris Lattner2a0433b2009-11-02 05:55:40 +0000899 if (NonOverdefVal) {
900 if (NonOverdefVal->isUndefined()) {
901 // Could annihilate value.
902 if (I.getOpcode() == Instruction::And)
903 markConstant(IV, &I, Constant::getNullValue(I.getType()));
904 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
905 markConstant(IV, &I, Constant::getAllOnesValue(PT));
906 else
907 markConstant(IV, &I,
908 Constant::getAllOnesValue(I.getType()));
909 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000910 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000911
912 if (I.getOpcode() == Instruction::And) {
913 // X and 0 = 0
914 if (NonOverdefVal->getConstant()->isNullValue())
915 return markConstant(IV, &I, NonOverdefVal->getConstant());
916 } else {
917 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
918 if (CI->isAllOnesValue()) // X or -1 = -1
919 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000920 }
921 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000922 }
Chris Lattnera177c672004-12-11 23:15:19 +0000923
924
Chris Lattner2a0433b2009-11-02 05:55:40 +0000925 // If both operands are PHI nodes, it is possible that this instruction has
926 // a constant value, despite the fact that the PHI node doesn't. Check for
927 // this condition now.
928 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
929 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
930 if (PN1->getParent() == PN2->getParent()) {
931 // Since the two PHI nodes are in the same basic block, they must have
932 // entries for the same predecessors. Walk the predecessor list, and
933 // if all of the incoming values are constants, and the result of
934 // evaluating this expression with all incoming value pairs is the
935 // same, then this expression is a constant even though the PHI node
936 // is not a constant!
937 LatticeVal Result;
938 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
939 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
940 BasicBlock *InBlock = PN1->getIncomingBlock(i);
941 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000942
Chris Lattner2a0433b2009-11-02 05:55:40 +0000943 if (In1.isOverdefined() || In2.isOverdefined()) {
944 Result.markOverdefined();
945 break; // Cannot fold this operation over the PHI nodes!
946 }
947
948 if (In1.isConstant() && In2.isConstant()) {
949 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
950 In2.getConstant());
951 if (Result.isUndefined())
952 Result.markConstant(V);
953 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000954 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000955 break;
Chris Lattner38871e42009-11-02 03:03:42 +0000956 }
Chris Lattner1daee8b2004-01-12 03:57:30 +0000957 }
958 }
959
Chris Lattner2a0433b2009-11-02 05:55:40 +0000960 // If we found a constant value here, then we know the instruction is
961 // constant despite the fact that the PHI nodes are overdefined.
962 if (Result.isConstant()) {
963 markConstant(IV, &I, Result.getConstant());
964 // Remember that this instruction is virtually using the PHI node
965 // operands.
966 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
967 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
968 return;
969 }
970
971 if (Result.isUndefined())
972 return;
973
974 // Okay, this really is overdefined now. Since we might have
975 // speculatively thought that this was not overdefined before, and
976 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
977 // make sure to clean out any entries that we put there, for
978 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +0000979 RemoveFromOverdefinedPHIs(&I, PN1);
980 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000981 }
982
983 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000984}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000985
Chris Lattner2f096252009-11-02 02:33:50 +0000986// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000987void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000988 LatticeVal V1State = getValueState(I.getOperand(0));
989 LatticeVal V2State = getValueState(I.getOperand(1));
990
Reid Spencere4d87aa2006-12-23 06:05:41 +0000991 LatticeVal &IV = ValueState[&I];
992 if (IV.isOverdefined()) return;
993
Chris Lattner2a0433b2009-11-02 05:55:40 +0000994 if (V1State.isConstant() && V2State.isConstant())
995 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
996 V1State.getConstant(),
997 V2State.getConstant()));
998
999 // If operands are still undefined, wait for it to resolve.
1000 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1001 return;
1002
1003 // If something is overdefined, use some tricks to avoid ending up and over
1004 // defined if we can.
1005
1006 // If both operands are PHI nodes, it is possible that this instruction has
1007 // a constant value, despite the fact that the PHI node doesn't. Check for
1008 // this condition now.
1009 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1010 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1011 if (PN1->getParent() == PN2->getParent()) {
1012 // Since the two PHI nodes are in the same basic block, they must have
1013 // entries for the same predecessors. Walk the predecessor list, and
1014 // if all of the incoming values are constants, and the result of
1015 // evaluating this expression with all incoming value pairs is the
1016 // same, then this expression is a constant even though the PHI node
1017 // is not a constant!
1018 LatticeVal Result;
1019 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1020 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1021 BasicBlock *InBlock = PN1->getIncomingBlock(i);
1022 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001023
Chris Lattner2a0433b2009-11-02 05:55:40 +00001024 if (In1.isOverdefined() || In2.isOverdefined()) {
1025 Result.markOverdefined();
1026 break; // Cannot fold this operation over the PHI nodes!
1027 }
1028
1029 if (In1.isConstant() && In2.isConstant()) {
1030 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
1031 In1.getConstant(),
1032 In2.getConstant());
1033 if (Result.isUndefined())
1034 Result.markConstant(V);
1035 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001036 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +00001037 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001038 }
1039 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001040 }
1041
Chris Lattner2a0433b2009-11-02 05:55:40 +00001042 // If we found a constant value here, then we know the instruction is
1043 // constant despite the fact that the PHI nodes are overdefined.
1044 if (Result.isConstant()) {
1045 markConstant(&I, Result.getConstant());
1046 // Remember that this instruction is virtually using the PHI node
1047 // operands.
1048 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1049 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1050 return;
1051 }
1052
1053 if (Result.isUndefined())
1054 return;
1055
1056 // Okay, this really is overdefined now. Since we might have
1057 // speculatively thought that this was not overdefined before, and
1058 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1059 // make sure to clean out any entries that we put there, for
1060 // efficiency.
Chris Lattnere01985c2009-11-02 06:28:16 +00001061 RemoveFromOverdefinedPHIs(&I, PN1);
1062 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001063 }
1064
1065 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001066}
1067
Robert Bocchino56107e22006-01-10 19:05:05 +00001068void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001069 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001070 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001071
1072#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001073 LatticeVal &ValState = getValueState(I.getOperand(0));
1074 LatticeVal &IdxState = getValueState(I.getOperand(1));
1075
1076 if (ValState.isOverdefined() || IdxState.isOverdefined())
1077 markOverdefined(&I);
1078 else if(ValState.isConstant() && IdxState.isConstant())
1079 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1080 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001081#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001082}
1083
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001084void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001085 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001086 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001087#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001088 LatticeVal &ValState = getValueState(I.getOperand(0));
1089 LatticeVal &EltState = getValueState(I.getOperand(1));
1090 LatticeVal &IdxState = getValueState(I.getOperand(2));
1091
1092 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1093 IdxState.isOverdefined())
1094 markOverdefined(&I);
1095 else if(ValState.isConstant() && EltState.isConstant() &&
1096 IdxState.isConstant())
1097 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1098 EltState.getConstant(),
1099 IdxState.getConstant()));
1100 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001101 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001102 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1103 EltState.getConstant(),
1104 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001105#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001106}
1107
Chris Lattner543abdf2006-04-08 01:19:12 +00001108void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001109 // TODO : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001110 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001111#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001112 LatticeVal &V1State = getValueState(I.getOperand(0));
1113 LatticeVal &V2State = getValueState(I.getOperand(1));
1114 LatticeVal &MaskState = getValueState(I.getOperand(2));
1115
1116 if (MaskState.isUndefined() ||
1117 (V1State.isUndefined() && V2State.isUndefined()))
1118 return; // Undefined output if mask or both inputs undefined.
1119
1120 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1121 MaskState.isOverdefined()) {
1122 markOverdefined(&I);
1123 } else {
1124 // A mix of constant/undef inputs.
1125 Constant *V1 = V1State.isConstant() ?
1126 V1State.getConstant() : UndefValue::get(I.getType());
1127 Constant *V2 = V2State.isConstant() ?
1128 V2State.getConstant() : UndefValue::get(I.getType());
1129 Constant *Mask = MaskState.isConstant() ?
1130 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1131 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1132 }
Devang Patel67a821d2006-12-04 23:54:59 +00001133#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001134}
1135
Chris Lattner2f096252009-11-02 02:33:50 +00001136// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001137// can turn this into a getelementptr ConstantExpr.
1138//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001139void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner5cc66d92009-11-02 23:25:39 +00001140 if (ValueState[&I].isOverdefined()) return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001141
Chris Lattnere777ff22007-02-02 20:51:48 +00001142 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001143 Operands.reserve(I.getNumOperands());
1144
1145 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001146 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001147 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001148 return; // Operands are not resolved yet.
1149
Chris Lattner38871e42009-11-02 03:03:42 +00001150 if (State.isOverdefined())
Chris Lattner5cc66d92009-11-02 23:25:39 +00001151 return markOverdefined(&I);
Chris Lattner38871e42009-11-02 03:03:42 +00001152
Chris Lattner2a88bb72002-08-30 23:39:00 +00001153 assert(State.isConstant() && "Unknown state!");
1154 Operands.push_back(State.getConstant());
1155 }
1156
1157 Constant *Ptr = Operands[0];
Chris Lattner2a0433b2009-11-02 05:55:40 +00001158 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1159 Operands.size()-1));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001160}
Brian Gaeked0fde302003-11-11 22:41:34 +00001161
Chris Lattner2a0433b2009-11-02 05:55:40 +00001162void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001163 // If this store is of a struct, ignore it.
1164 if (isa<StructType>(SI.getOperand(0)->getType()))
1165 return;
1166
Chris Lattnerdd336d12004-12-11 05:15:59 +00001167 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1168 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001169
Chris Lattnerdd336d12004-12-11 05:15:59 +00001170 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001171 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001172 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1173
Chris Lattner2a0433b2009-11-02 05:55:40 +00001174 // Get the value we are storing into the global, then merge it.
1175 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001176 if (I->second.isOverdefined())
1177 TrackedGlobals.erase(I); // No need to keep tracking this!
1178}
1179
1180
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001181// Handle load instructions. If the operand is a constant pointer to a constant
1182// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001183void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001184 // If this load is of a struct, just mark the result overdefined.
1185 if (isa<StructType>(I.getType()))
1186 return markAnythingOverdefined(&I);
1187
Chris Lattner2a0433b2009-11-02 05:55:40 +00001188 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001189 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001190
Chris Lattneref36dfd2004-11-15 05:03:30 +00001191 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001192 if (IV.isOverdefined()) return;
1193
Chris Lattner2a0433b2009-11-02 05:55:40 +00001194 if (!PtrVal.isConstant() || I.isVolatile())
1195 return markOverdefined(IV, &I);
1196
Chris Lattner5638dc62009-11-02 06:06:14 +00001197 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001198
Chris Lattner2a0433b2009-11-02 05:55:40 +00001199 // load null -> null
1200 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1201 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1202
1203 // Transform load (constant global) into the value loaded.
1204 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001205 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001206 // If we are tracking this global, merge in the known value for it.
1207 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1208 TrackedGlobals.find(GV);
1209 if (It != TrackedGlobals.end()) {
1210 mergeInValue(IV, &I, It->second);
1211 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001212 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001213 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001214 }
1215
Chris Lattner5638dc62009-11-02 06:06:14 +00001216 // Transform load from a constant into a constant if possible.
1217 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1218 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001219
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001220 // Otherwise we cannot say for certain what value this load will produce.
1221 // Bail out.
1222 markOverdefined(IV, &I);
1223}
Chris Lattner58b7b082004-04-13 19:43:54 +00001224
Chris Lattner59acc7d2004-12-10 08:02:06 +00001225void SCCPSolver::visitCallSite(CallSite CS) {
1226 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001227 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001228
1229 // The common case is that we aren't tracking the callee, either because we
1230 // are not doing interprocedural analysis or the callee is indirect, or is
1231 // external. Handle these cases first.
Chris Lattner14532d02009-11-03 03:42:51 +00001232 if (F == 0 || F->isDeclaration()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001233CallOverdefined:
1234 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001235 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001236
1237 // Otherwise, if we have a single return value case, and if the function is
1238 // a declaration, maybe we can constant fold it.
Chris Lattner14532d02009-11-03 03:42:51 +00001239 if (F && F->isDeclaration() && !isa<StructType>(I->getType()) &&
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001240 canConstantFoldCallTo(F)) {
1241
1242 SmallVector<Constant*, 8> Operands;
1243 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1244 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001245 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001246
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001247 if (State.isUndefined())
1248 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001249 if (State.isOverdefined())
1250 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001251 assert(State.isConstant() && "Unknown state!");
1252 Operands.push_back(State.getConstant());
1253 }
1254
1255 // If we can constant fold this, mark the result of the call as a
1256 // constant.
Chris Lattner38871e42009-11-02 03:03:42 +00001257 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1258 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001259 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001260
1261 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001262 return markAnythingOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001263 }
1264
Chris Lattner2396cc32009-11-03 19:24:51 +00001265 // If this is a local function that doesn't have its address taken, mark its
1266 // entry block executable and merge in the actual arguments to the call into
1267 // the formal arguments of the function.
1268 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1269 MarkBlockExecutable(F->begin());
1270
1271 // Propagate information from this call site into the callee.
1272 CallSite::arg_iterator CAI = CS.arg_begin();
1273 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1274 AI != E; ++AI, ++CAI) {
1275 // If this argument is byval, and if the function is not readonly, there
1276 // will be an implicit copy formed of the input aggregate.
1277 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1278 markOverdefined(AI);
1279 continue;
1280 }
1281
Chris Lattnerfc36a562009-11-03 23:40:48 +00001282 if (const StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner0fb7e182009-11-04 18:57:42 +00001283 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1284 LatticeVal CallArg = getStructValueState(*CAI, i);
1285 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1286 }
Chris Lattnerfc36a562009-11-03 23:40:48 +00001287 } else {
1288 mergeInValue(AI, getValueState(*CAI));
1289 }
Chris Lattner2396cc32009-11-03 19:24:51 +00001290 }
1291 }
1292
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001293 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001294 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1295 if (!MRVFunctionsTracked.count(F))
1296 goto CallOverdefined; // Not tracking this callee.
1297
1298 // If we are tracking this callee, propagate the result of the function
1299 // into this call site.
1300 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1301 mergeInValue(getStructValueState(I, i), I,
1302 TrackedMultipleRetVals[std::make_pair(F, i)]);
1303 } else {
1304 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1305 if (TFRVI == TrackedRetVals.end())
1306 goto CallOverdefined; // Not tracking this callee.
1307
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001308 // If so, propagate the return value of the callee into this call result.
1309 mergeInValue(I, TFRVI->second);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001310 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001311}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001312
Chris Lattner82bec2c2004-11-15 04:44:20 +00001313void SCCPSolver::Solve() {
1314 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001315 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001316 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001317 // Process the overdefined instruction's work list first, which drives other
1318 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001319 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001320 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001321
Dan Gohman87325772009-08-17 15:25:05 +00001322 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001323
Chris Lattner82bec2c2004-11-15 04:44:20 +00001324 // "I" got into the work list because it either made the transition from
1325 // bottom to constant
1326 //
1327 // Anything on this worklist that is overdefined need not be visited
1328 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001329 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001330 //
1331 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1332 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001333 if (Instruction *I = dyn_cast<Instruction>(*UI))
1334 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001335 }
Chris Lattner2f096252009-11-02 02:33:50 +00001336
1337 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001338 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001339 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001340
Dan Gohman87325772009-08-17 15:25:05 +00001341 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001342
Chris Lattner2a0433b2009-11-02 05:55:40 +00001343 // "I" got into the work list because it made the transition from undef to
1344 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001345 //
1346 // Anything on this worklist that is overdefined need not be visited
1347 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001348 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001349 //
Chris Lattnerfc36a562009-11-03 23:40:48 +00001350 if (isa<StructType>(I->getType()) || !getValueState(I).isOverdefined())
Chris Lattner82bec2c2004-11-15 04:44:20 +00001351 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1352 UI != E; ++UI)
Chris Lattner14532d02009-11-03 03:42:51 +00001353 if (Instruction *I = dyn_cast<Instruction>(*UI))
1354 OperandChangedState(I);
Chris Lattner82bec2c2004-11-15 04:44:20 +00001355 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001356
Chris Lattner2f096252009-11-02 02:33:50 +00001357 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001358 while (!BBWorkList.empty()) {
1359 BasicBlock *BB = BBWorkList.back();
1360 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001361
Dan Gohman87325772009-08-17 15:25:05 +00001362 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001363
Chris Lattner82bec2c2004-11-15 04:44:20 +00001364 // Notify all instructions in this basic block that they are newly
1365 // executable.
1366 visit(BB);
1367 }
1368 }
1369}
1370
Chris Lattner3bad2532006-12-20 06:21:33 +00001371/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001372/// that branches on undef values cannot reach any of their successors.
1373/// However, this is not a safe assumption. After we solve dataflow, this
1374/// method should be use to handle this. If this returns true, the solver
1375/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001376///
1377/// This method handles this by finding an unresolved branch and marking it one
1378/// of the edges from the block as being feasible, even though the condition
1379/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1380/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001381/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001382/// constraints on the condition of the branch, as that would impact other users
1383/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001384///
1385/// This scan also checks for values that use undefs, whose results are actually
1386/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1387/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1388/// even if X isn't defined.
1389bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001390 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1391 if (!BBExecutable.count(BB))
1392 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001393
1394 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1395 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001396 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001397
Chris Lattnerfc36a562009-11-03 23:40:48 +00001398 if (const StructType *STy = dyn_cast<StructType>(I->getType())) {
1399 // Only a few things that can be structs matter for undef. Just send
1400 // all their results to overdefined. We could be more precise than this
1401 // but it isn't worth bothering.
1402 if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1403 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1404 LatticeVal &LV = getStructValueState(I, i);
1405 if (LV.isUndefined())
1406 markOverdefined(LV, I);
1407 }
1408 }
1409 continue;
1410 }
1411
Chris Lattner3bad2532006-12-20 06:21:33 +00001412 LatticeVal &LV = getValueState(I);
1413 if (!LV.isUndefined()) continue;
1414
Chris Lattnerfc36a562009-11-03 23:40:48 +00001415 // No instructions using structs need disambiguation.
1416 if (isa<StructType>(I->getOperand(0)->getType()))
1417 continue;
1418
Chris Lattner3bad2532006-12-20 06:21:33 +00001419 // Get the lattice values of the first two operands for use below.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001420 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001421 LatticeVal Op1LV;
1422 if (I->getNumOperands() == 2) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001423 // No instructions using structs need disambiguation.
1424 if (isa<StructType>(I->getOperand(1)->getType()))
1425 continue;
1426
Chris Lattner3bad2532006-12-20 06:21:33 +00001427 // If this is a two-operand instruction, and if both operands are
1428 // undefs, the result stays undef.
1429 Op1LV = getValueState(I->getOperand(1));
1430 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1431 continue;
1432 }
1433
1434 // If this is an instructions whose result is defined even if the input is
1435 // not fully defined, propagate the information.
1436 const Type *ITy = I->getType();
1437 switch (I->getOpcode()) {
1438 default: break; // Leave the instruction as an undef.
1439 case Instruction::ZExt:
1440 // After a zero extend, we know the top part is zero. SExt doesn't have
1441 // to be handled here, because we don't know whether the top part is 1's
1442 // or 0's.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001443 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001444 return true;
1445 case Instruction::Mul:
1446 case Instruction::And:
1447 // undef * X -> 0. X could be zero.
1448 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001449 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001450 return true;
1451
1452 case Instruction::Or:
1453 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001454 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001455 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001456
1457 case Instruction::SDiv:
1458 case Instruction::UDiv:
1459 case Instruction::SRem:
1460 case Instruction::URem:
1461 // X / undef -> undef. No change.
1462 // X % undef -> undef. No change.
1463 if (Op1LV.isUndefined()) break;
1464
1465 // undef / X -> 0. X could be maxint.
1466 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001467 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001468 return true;
1469
1470 case Instruction::AShr:
1471 // undef >>s X -> undef. No change.
1472 if (Op0LV.isUndefined()) break;
1473
1474 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1475 if (Op0LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001476 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001477 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001478 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001479 return true;
1480 case Instruction::LShr:
1481 case Instruction::Shl:
1482 // undef >> X -> undef. No change.
1483 // undef << X -> undef. No change.
1484 if (Op0LV.isUndefined()) break;
1485
1486 // X >> undef -> 0. X could be 0.
1487 // X << undef -> 0. X could be 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001488 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001489 return true;
1490 case Instruction::Select:
1491 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1492 if (Op0LV.isUndefined()) {
1493 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1494 Op1LV = getValueState(I->getOperand(2));
1495 } else if (Op1LV.isUndefined()) {
1496 // c ? undef : undef -> undef. No change.
1497 Op1LV = getValueState(I->getOperand(2));
1498 if (Op1LV.isUndefined())
1499 break;
1500 // Otherwise, c ? undef : x -> x.
1501 } else {
1502 // Leave Op1LV as Operand(1)'s LatticeValue.
1503 }
1504
1505 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001506 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001507 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001508 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001509 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001510 case Instruction::Call:
1511 // If a call has an undef result, it is because it is constant foldable
1512 // but one of the inputs was undef. Just force the result to
1513 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001514 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001515 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001516 }
1517 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001518
1519 TerminatorInst *TI = BB->getTerminator();
1520 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1521 if (!BI->isConditional()) continue;
1522 if (!getValueState(BI->getCondition()).isUndefined())
1523 continue;
1524 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001525 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001526 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001527 if (!getValueState(SI->getCondition()).isUndefined())
1528 continue;
1529 } else {
1530 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001531 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001532
Chris Lattner05bb7892008-01-28 00:32:30 +00001533 // If the edge to the second successor isn't thought to be feasible yet,
1534 // mark it so now. We pick the second one so that this goes to some
1535 // enumerated value in a switch instead of going to the default destination.
1536 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001537 continue;
1538
1539 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1540 // and return. This will make other blocks reachable, which will allow new
1541 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001542 markEdgeExecutable(BB, TI->getSuccessor(1));
1543
1544 // This must be a conditional branch of switch on undef. At this point,
1545 // force the old terminator to branch to the first successor. This is
1546 // required because we are now influencing the dataflow of the function with
1547 // the assumption that this edge is taken. If we leave the branch condition
1548 // as undef, then further analysis could think the undef went another way
1549 // leading to an inconsistent set of conclusions.
1550 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001551 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001552 } else {
1553 SwitchInst *SI = cast<SwitchInst>(TI);
1554 SI->setCondition(SI->getCaseValue(1));
1555 }
1556
Chris Lattnerd2d86702006-10-22 05:59:17 +00001557 return true;
1558 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001559
Chris Lattnerd2d86702006-10-22 05:59:17 +00001560 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001561}
1562
Chris Lattner82bec2c2004-11-15 04:44:20 +00001563
1564namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001565 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001566 //
Chris Lattner14051812004-11-15 07:15:04 +00001567 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001568 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001569 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001570 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001571 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001572 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001573
Chris Lattner14051812004-11-15 07:15:04 +00001574 // runOnFunction - Run the Sparse Conditional Constant Propagation
1575 // algorithm, and return true if the function was modified.
1576 //
1577 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001578
Chris Lattner14051812004-11-15 07:15:04 +00001579 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1580 AU.setPreservesCFG();
1581 }
1582 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001583} // end anonymous namespace
1584
Dan Gohman844731a2008-05-13 00:00:25 +00001585char SCCP::ID = 0;
1586static RegisterPass<SCCP>
1587X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001588
Chris Lattner2f096252009-11-02 02:33:50 +00001589// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001590FunctionPass *llvm::createSCCPPass() {
1591 return new SCCP();
1592}
1593
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001594static void DeleteInstructionInBlock(BasicBlock *BB) {
1595 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1596 ++NumDeadBlocks;
1597
1598 // Delete the instructions backwards, as it has a reduced likelihood of
1599 // having to update as many def-use and use-def chains.
1600 while (!isa<TerminatorInst>(BB->begin())) {
1601 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1602
1603 if (!I->use_empty())
1604 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1605 BB->getInstList().erase(I);
1606 ++NumInstRemoved;
1607 }
1608}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001609
Chris Lattner82bec2c2004-11-15 04:44:20 +00001610// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1611// and return true if the function was modified.
1612//
1613bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001614 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner5638dc62009-11-02 06:06:14 +00001615 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001616
1617 // Mark the first block of the function as being executable.
1618 Solver.MarkBlockExecutable(F.begin());
1619
Chris Lattner7e529e42004-11-15 05:45:33 +00001620 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001621 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001622 Solver.markAnythingOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001623
Chris Lattner82bec2c2004-11-15 04:44:20 +00001624 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001625 bool ResolvedUndefs = true;
1626 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001627 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001628 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001629 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001630 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001631
Chris Lattner7e529e42004-11-15 05:45:33 +00001632 bool MadeChanges = false;
1633
1634 // If we decided that there are basic blocks that are dead in this function,
1635 // delete their contents now. Note that we cannot actually delete the blocks,
1636 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001637
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001638 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001639 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001640 DeleteInstructionInBlock(BB);
1641 MadeChanges = true;
1642 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001643 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001644
1645 // Iterate over all of the instructions in a function, replacing them with
1646 // constants if we have found them to be of constant values.
1647 //
1648 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1649 Instruction *Inst = BI++;
1650 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1651 continue;
1652
Chris Lattnerfc36a562009-11-03 23:40:48 +00001653 // TODO: Reconstruct structs from their elements.
1654 if (isa<StructType>(Inst->getType()))
1655 continue;
1656
Chris Lattner8db50122009-11-02 02:54:24 +00001657 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1658 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001659 continue;
1660
1661 Constant *Const = IV.isConstant()
1662 ? IV.getConstant() : UndefValue::get(Inst->getType());
1663 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1664
1665 // Replaces all of the uses of a variable with uses of the constant.
1666 Inst->replaceAllUsesWith(Const);
1667
1668 // Delete the instruction.
1669 Inst->eraseFromParent();
1670
1671 // Hey, we just changed something!
1672 MadeChanges = true;
1673 ++NumInstRemoved;
1674 }
1675 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001676
1677 return MadeChanges;
1678}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001679
1680namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001681 //===--------------------------------------------------------------------===//
1682 //
1683 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1684 /// Constant Propagation.
1685 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001686 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001687 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001688 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001689 bool runOnModule(Module &M);
1690 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001691} // end anonymous namespace
1692
Dan Gohman844731a2008-05-13 00:00:25 +00001693char IPSCCP::ID = 0;
1694static RegisterPass<IPSCCP>
1695Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1696
Chris Lattner2f096252009-11-02 02:33:50 +00001697// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001698ModulePass *llvm::createIPSCCPPass() {
1699 return new IPSCCP();
1700}
1701
1702
1703static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001704 // Delete any dead constantexpr klingons.
1705 GV->removeDeadConstantUsers();
1706
Chris Lattner59acc7d2004-12-10 08:02:06 +00001707 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1708 UI != E; ++UI)
1709 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001710 if (SI->getOperand(0) == GV || SI->isVolatile())
1711 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001712 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1713 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001714 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001715 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001716 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1717 if (LI->isVolatile())
1718 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001719 } else if (isa<BlockAddress>(*UI)) {
1720 // blockaddress doesn't take the address of the function, it takes addr
1721 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001722 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001723 return true;
1724 }
1725 return false;
1726}
1727
1728bool IPSCCP::runOnModule(Module &M) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001729 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner59acc7d2004-12-10 08:02:06 +00001730
1731 // Loop over all functions, marking arguments to those with their addresses
1732 // taken or that are external as overdefined.
1733 //
Chris Lattnerff3ca152009-11-02 06:34:04 +00001734 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1735 if (F->isDeclaration())
1736 continue;
1737
Chris Lattner14532d02009-11-03 03:42:51 +00001738 // If this is a strong or ODR definition of this function, then we can
1739 // propagate information about its result into callsites of it.
Chris Lattnerfc36a562009-11-03 23:40:48 +00001740 if (!F->mayBeOverridden())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001741 Solver.AddTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001742
1743 // If this function only has direct calls that we can see, we can track its
1744 // arguments and return value aggressively, and can assume it is not called
1745 // unless we see evidence to the contrary.
Chris Lattner2396cc32009-11-03 19:24:51 +00001746 if (F->hasLocalLinkage() && !AddressIsTaken(F)) {
1747 Solver.AddArgumentTrackedFunction(F);
Chris Lattner14532d02009-11-03 03:42:51 +00001748 continue;
Chris Lattner2396cc32009-11-03 19:24:51 +00001749 }
Chris Lattner14532d02009-11-03 03:42:51 +00001750
1751 // Assume the function is called.
1752 Solver.MarkBlockExecutable(F->begin());
1753
1754 // Assume nothing about the incoming arguments.
1755 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1756 AI != E; ++AI)
Chris Lattnerfc36a562009-11-03 23:40:48 +00001757 Solver.markAnythingOverdefined(AI);
Chris Lattnerff3ca152009-11-02 06:34:04 +00001758 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001759
Chris Lattnerdd336d12004-12-11 05:15:59 +00001760 // Loop over global variables. We inform the solver about any internal global
1761 // variables that do not have their 'addresses taken'. If they don't have
1762 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001763 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1764 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001765 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001766 Solver.TrackValueOfGlobalVariable(G);
1767
Chris Lattner59acc7d2004-12-10 08:02:06 +00001768 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001769 bool ResolvedUndefs = true;
1770 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001771 Solver.Solve();
1772
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001773 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001774 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001775 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001776 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001777 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001778
1779 bool MadeChanges = false;
1780
1781 // Iterate over all of the instructions in the module, replacing them with
1782 // constants if we have found them to be of constant values.
1783 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001784 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001785
Chris Lattner59acc7d2004-12-10 08:02:06 +00001786 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001787 if (Solver.isBlockExecutable(F->begin())) {
1788 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1789 AI != E; ++AI) {
Chris Lattnerfc36a562009-11-03 23:40:48 +00001790 if (AI->use_empty() || isa<StructType>(AI->getType())) continue;
Chris Lattner89112b62009-11-02 03:25:55 +00001791
Chris Lattnerfc36a562009-11-03 23:40:48 +00001792 // TODO: Could use getStructLatticeValueFor to find out if the entire
1793 // result is a constant and replace it entirely if so.
1794
Chris Lattner89112b62009-11-02 03:25:55 +00001795 LatticeVal IV = Solver.getLatticeValueFor(AI);
1796 if (IV.isOverdefined()) continue;
1797
1798 Constant *CST = IV.isConstant() ?
1799 IV.getConstant() : UndefValue::get(AI->getType());
1800 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1801
1802 // Replaces all of the uses of a variable with uses of the
1803 // constant.
1804 AI->replaceAllUsesWith(CST);
1805 ++IPNumArgsElimed;
1806 }
Chris Lattner8db50122009-11-02 02:54:24 +00001807 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001808
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001809 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001810 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001811 DeleteInstructionInBlock(BB);
1812 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001813
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001814 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001815 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1816 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001817 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001818 TI->getSuccessor(i)->removePredecessor(BB);
1819 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001820 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001821 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001822 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001823
Chris Lattner864737b2004-12-11 05:32:19 +00001824 if (&*BB != &F->front())
1825 BlocksToErase.push_back(BB);
1826 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001827 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001828 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001829 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001830
1831 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1832 Instruction *Inst = BI++;
Chris Lattnerfc36a562009-11-03 23:40:48 +00001833 if (Inst->getType()->isVoidTy() || isa<StructType>(Inst->getType()))
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001834 continue;
1835
Chris Lattnerfc36a562009-11-03 23:40:48 +00001836 // TODO: Could use getStructLatticeValueFor to find out if the entire
1837 // result is a constant and replace it entirely if so.
1838
Chris Lattner8db50122009-11-02 02:54:24 +00001839 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1840 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001841 continue;
1842
1843 Constant *Const = IV.isConstant()
1844 ? IV.getConstant() : UndefValue::get(Inst->getType());
1845 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1846
1847 // Replaces all of the uses of a variable with uses of the
1848 // constant.
1849 Inst->replaceAllUsesWith(Const);
1850
1851 // Delete the instruction.
1852 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1853 Inst->eraseFromParent();
1854
1855 // Hey, we just changed something!
1856 MadeChanges = true;
1857 ++IPNumInstRemoved;
1858 }
1859 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001860
1861 // Now that all instructions in the function are constant folded, erase dead
1862 // blocks, because we can now use ConstantFoldTerminator to get rid of
1863 // in-edges.
1864 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1865 // If there are any PHI nodes in this successor, drop entries for BB now.
1866 BasicBlock *DeadBB = BlocksToErase[i];
1867 while (!DeadBB->use_empty()) {
1868 Instruction *I = cast<Instruction>(DeadBB->use_back());
1869 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001870 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001871 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001872 // if this is a branch or switch on undef. Fold it manually as a
1873 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001874#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001875 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1876 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1877 "Branch should be foldable!");
1878 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1879 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1880 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001881 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001882 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001883#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001884
1885 // Make this an uncond branch to the first successor.
1886 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001887 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001888
1889 // Remove entries in successor phi nodes to remove edges.
1890 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1891 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1892
1893 // Remove the old terminator.
1894 TI->eraseFromParent();
1895 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001896 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001897
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001898 // Finally, delete the basic block.
1899 F->getBasicBlockList().erase(DeadBB);
1900 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001901 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001902 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001903
1904 // If we inferred constant or undef return values for a function, we replaced
1905 // all call uses with the inferred value. This means we don't need to bother
1906 // actually returning anything from the function. Replace all return
1907 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001908 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001909 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001910 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner14532d02009-11-03 03:42:51 +00001911 E = RV.end(); I != E; ++I) {
1912 Function *F = I->first;
1913 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1914 continue;
1915
1916 // We can only do this if we know that nothing else can call the function.
1917 if (!F->hasLocalLinkage() || AddressIsTaken(F))
1918 continue;
1919
1920 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1921 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1922 if (!isa<UndefValue>(RI->getOperand(0)))
1923 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1924 }
1925
Chris Lattnerdd336d12004-12-11 05:15:59 +00001926 // If we infered constant or undef values for globals variables, we can delete
1927 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001928 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1929 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001930 E = TG.end(); I != E; ++I) {
1931 GlobalVariable *GV = I->first;
1932 assert(!I->second.isOverdefined() &&
1933 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001934 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001935 while (!GV->use_empty()) {
1936 StoreInst *SI = cast<StoreInst>(GV->use_back());
1937 SI->eraseFromParent();
1938 }
1939 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001940 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001941 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001942
Chris Lattner59acc7d2004-12-10 08:02:06 +00001943 return MadeChanges;
1944}