blob: 749ba40a64b83ea550a1280dba1549347a4f6232 [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
Chris Lattner347389d2001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattner4f031622004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000022#include "llvm/Transforms/IPO.h"
Chris Lattner0fe5b322004-01-12 17:43:40 +000023#include "llvm/Constants.h"
Chris Lattner91dbae62004-12-11 05:15:59 +000024#include "llvm/DerivedTypes.h"
Chris Lattnercccc5c72003-04-25 02:50:03 +000025#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000026#include "llvm/Pass.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Dan Gohman041f9d02008-06-20 01:15:44 +000028#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerff9362a2004-04-13 19:43:54 +000029#include "llvm/Transforms/Utils/Local.h"
Chris Lattnere77c9aa2009-11-02 06:06:14 +000030#include "llvm/Target/TargetData.h"
Chris Lattnerb4394642004-12-10 08:02:06 +000031#include "llvm/Support/CallSite.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner067d6072007-02-02 20:38:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattner65938fc2008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattner809aee22009-11-02 06:11:23 +000039#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Chris Lattner347389d2001-06-27 23:38:11 +000043#include <algorithm>
Dan Gohman99885692008-03-21 23:51:57 +000044#include <map>
Chris Lattner49525f82004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000046
Chris Lattner79a42ac2006-12-19 21:40:18 +000047STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewycky35e92c72008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-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 Lattner7d325382002-04-29 21:26:08 +000054namespace {
Chris Lattner1847f6d2006-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 Lattner2dd09db2009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000059 enum LatticeValueTy {
Chris Lattner1847f6d2006-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 Lattnerefdd2bb2009-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 Lattner1847f6d2006-12-20 06:21:33 +000080
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Chris Lattner347389d2001-06-27 23:38:11 +000085public:
Chris Lattner7ccf1a62009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Chris Lattner1847f6d2006-12-20 06:21:33 +000087
Chris Lattner7ccf1a62009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattner7ccf1a62009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000093
Chris Lattner7ccf1a62009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-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 Lattner7ccf1a62009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000106 }
107
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000110 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000113 }
Chris Lattnerefdd2bb2009-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 Lattner347389d2001-06-27 23:38:11 +0000131 }
132
Chris Lattner9e97fbe2009-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 Lattner7ccf1a62009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000145 }
Chris Lattner347389d2001-06-27 23:38:11 +0000146};
Chris Lattnere405ed92009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Chris Lattner347389d2001-06-27 23:38:11 +0000151
Chris Lattner347389d2001-06-27 23:38:11 +0000152//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000153//
Chris Lattner074be1f2004-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 Lattnere77c9aa2009-11-02 06:06:14 +0000158 const TargetData *TD;
Nick Lewycky77cb8e62011-07-25 21:16:04 +0000159 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattnerf5484032009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000161
Chris Lattner156b8c72009-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 Lattner91dbae62004-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 Lattner067d6072007-02-02 20:38:30 +0000171 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000172
Devang Patela7a20752008-03-11 05:46:42 +0000173 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-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 Patela7a20752008-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 Lattner65938fc2008-08-23 23:36:38 +0000180 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner156b8c72009-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 Lattnerb4394642004-12-10 08:02:06 +0000185
Chris Lattner2c427232009-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 Lattnercde8de52009-11-03 19:24:51 +0000189 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
190
Chris Lattner7ccf1a62009-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 Lattner65938fc2008-08-23 23:36:38 +0000198 SmallVector<Value*, 64> OverdefinedInstWorkList;
199 SmallVector<Value*, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000200
201
Chris Lattner65938fc2008-08-23 23:36:38 +0000202 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000203
Chris Lattner05fe6842004-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 Lattner0bbbe5d2003-10-08 16:55:34 +0000208 /// KnownFeasibleEdges - Entries in this set are edges which have already had
209 /// PHI nodes retriggered.
Chris Lattner65938fc2008-08-23 23:36:38 +0000210 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
211 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000212public:
Chris Lattnere77c9aa2009-11-02 06:06:14 +0000213 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000214
Chris Lattner074be1f2004-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 Lattner809aee22009-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;
David Greene389fc3b2010-01-05 01:27:15 +0000221 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner074be1f2004-11-15 04:44:20 +0000222 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000223 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000224 }
225
Chris Lattner91dbae62004-12-11 05:15:59 +0000226 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-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 Lattner91dbae62004-12-11 05:15:59 +0000230 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000231 // We only track the contents of scalar globals.
232 if (GV->getType()->getElementType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000233 LatticeVal &IV = TrackedGlobals[GV];
234 if (!isa<UndefValue>(GV->getInitializer()))
235 IV.markConstant(GV->getInitializer());
236 }
237 }
Chris Lattnerb4394642004-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 Lattnerb4394642004-12-10 08:02:06 +0000243 // Add an entry, F -> undef.
Chris Lattner229907c2011-07-18 04:54:35 +0000244 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000245 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000246 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-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 Lattnerb4394642004-12-10 08:02:06 +0000251 }
252
Chris Lattnercde8de52009-11-03 19:24:51 +0000253 void AddArgumentTrackedFunction(Function *F) {
254 TrackingIncomingArguments.insert(F);
255 }
256
Chris Lattner074be1f2004-11-15 04:44:20 +0000257 /// Solve - Solve for constants and executable blocks.
258 ///
259 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000260
Chris Lattner1847f6d2006-12-20 06:21:33 +0000261 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-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 Lattner1847f6d2006-12-20 06:21:33 +0000266 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000267
Chris Lattneradd44f32008-08-23 23:39:31 +0000268 bool isBlockExecutable(BasicBlock *BB) const {
269 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000270 }
271
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000272 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattnerf5484032009-11-02 05:55:40 +0000273 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000274 assert(I != ValueState.end() && "V is not in valuemap!");
275 return I->second;
Chris Lattner074be1f2004-11-15 04:44:20 +0000276 }
Chris Lattner156b8c72009-11-03 23:40:48 +0000277
Chris Lattnerb45de952010-08-18 02:41:56 +0000278 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
Chris Lattner156b8c72009-11-03 23:40:48 +0000279 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;
Chris Lattnerb45de952010-08-18 02:41:56 +0000283 }*/
Chris Lattner074be1f2004-11-15 04:44:20 +0000284
Devang Patela7a20752008-03-11 05:46:42 +0000285 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000286 ///
Devang Patela7a20752008-03-11 05:46:42 +0000287 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
288 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000289 }
290
Chris Lattner91dbae62004-12-11 05:15:59 +0000291 /// getTrackedGlobals - Get and return the set of inferred initializers for
292 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000293 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000294 return TrackedGlobals;
295 }
296
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000297 void markOverdefined(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000298 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerc33fd462007-03-04 04:50:21 +0000299 markOverdefined(ValueState[V], V);
300 }
Chris Lattner99e12952004-12-11 02:53:57 +0000301
Chris Lattner156b8c72009-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) {
Chris Lattner229907c2011-07-18 04:54:35 +0000305 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
307 markOverdefined(getStructValueState(V, i), V);
308 else
309 markOverdefined(V);
310 }
311
Chris Lattner347389d2001-06-27 23:38:11 +0000312private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000313 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000314 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000315 // the users of the instruction are updated later.
316 //
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000317 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
318 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000319 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000320 if (IV.isOverdefined())
321 OverdefinedInstWorkList.push_back(V);
322 else
323 InstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000324 }
Chris Lattner1847f6d2006-12-20 06:21:33 +0000325
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000326 void markConstant(Value *V, Constant *C) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000327 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerb4394642004-12-10 08:02:06 +0000328 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000329 }
330
Chris Lattnerf5484032009-11-02 05:55:40 +0000331 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000332 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000333 LatticeVal &IV = ValueState[V];
334 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000335 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000336 if (IV.isOverdefined())
337 OverdefinedInstWorkList.push_back(V);
338 else
339 InstWorkList.push_back(V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000340 }
341
342
Chris Lattnerd79334d2004-07-15 23:36:43 +0000343 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000344 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000345 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000346 void markOverdefined(LatticeVal &IV, Value *V) {
347 if (!IV.markOverdefined()) return;
348
David Greene389fc3b2010-01-05 01:27:15 +0000349 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000350 if (Function *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000351 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000352 else
David Greene389fc3b2010-01-05 01:27:15 +0000353 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000354 // Only instructions go on the work list
355 OverdefinedInstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000356 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000357
Chris Lattnerf5484032009-11-02 05:55:40 +0000358 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000359 if (IV.isOverdefined() || MergeWithV.isUndefined())
360 return; // Noop.
361 if (MergeWithV.isOverdefined())
362 markOverdefined(IV, V);
363 else if (IV.isUndefined())
364 markConstant(IV, V, MergeWithV.getConstant());
365 else if (IV.getConstant() != MergeWithV.getConstant())
366 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000367 }
Chris Lattner06a0ed12006-02-08 02:38:11 +0000368
Chris Lattnerf5484032009-11-02 05:55:40 +0000369 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000370 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000371 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000372 }
373
Chris Lattner347389d2001-06-27 23:38:11 +0000374
Chris Lattnerf5484032009-11-02 05:55:40 +0000375 /// getValueState - Return the LatticeVal object that corresponds to the
376 /// value. This function handles the case when the value hasn't been seen yet
377 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000378 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000379 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000380
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000381 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
382 ValueState.insert(std::make_pair(V, LatticeVal()));
383 LatticeVal &LV = I.first->second;
384
385 if (!I.second)
386 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000387
Chris Lattner1847f6d2006-12-20 06:21:33 +0000388 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000389 // Undef values remain undefined.
390 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000391 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000392 }
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000393
Chris Lattnera3c39d32009-11-02 02:33:50 +0000394 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000395 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000396 }
397
Chris Lattner156b8c72009-11-03 23:40:48 +0000398 /// getStructValueState - Return the LatticeVal object that corresponds to the
399 /// value/field pair. This function handles the case when the value hasn't
400 /// been seen yet by properly seeding constants etc.
401 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000402 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000403 assert(i < cast<StructType>(V->getType())->getNumElements() &&
404 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000405
406 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
407 bool> I = StructValueState.insert(
408 std::make_pair(std::make_pair(V, i), LatticeVal()));
409 LatticeVal &LV = I.first->second;
410
411 if (!I.second)
412 return LV; // Common case, already in the map.
413
Chris Lattner156b8c72009-11-03 23:40:48 +0000414 if (Constant *C = dyn_cast<Constant>(V)) {
415 if (isa<UndefValue>(C))
416 ; // Undef values remain undefined.
417 else if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C))
418 LV.markConstant(CS->getOperand(i)); // Constants are constant.
419 else if (isa<ConstantAggregateZero>(C)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000420 Type *FieldTy = cast<StructType>(V->getType())->getElementType(i);
Chris Lattner156b8c72009-11-03 23:40:48 +0000421 LV.markConstant(Constant::getNullValue(FieldTy));
422 } else
423 LV.markOverdefined(); // Unknown sort of constant.
424 }
425
426 // All others are underdefined by default.
427 return LV;
428 }
429
430
Chris Lattnerf5484032009-11-02 05:55:40 +0000431 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
432 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000433 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
434 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
435 return; // This edge is already known to be executable!
436
Chris Lattner809aee22009-11-02 06:11:23 +0000437 if (!MarkBlockExecutable(Dest)) {
438 // If the destination is already executable, we just made an *edge*
439 // feasible that wasn't before. Revisit the PHI nodes in the block
440 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000441 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Daniel Dunbar9813b0b2009-07-26 07:49:05 +0000442 << " -> " << Dest->getName() << "\n");
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000443
Chris Lattner809aee22009-11-02 06:11:23 +0000444 PHINode *PN;
445 for (BasicBlock::iterator I = Dest->begin();
446 (PN = dyn_cast<PHINode>(I)); ++I)
447 visitPHINode(*PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000448 }
Chris Lattner347389d2001-06-27 23:38:11 +0000449 }
450
Chris Lattner074be1f2004-11-15 04:44:20 +0000451 // getFeasibleSuccessors - Return a vector of booleans to indicate which
452 // successors are reachable from a given terminator instruction.
453 //
Chris Lattner37d400a2007-02-02 21:15:06 +0000454 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000455
456 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000457 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000458 //
459 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
460
461 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000462 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000463 // information, we need to update the specified user of this instruction.
464 //
Chris Lattnerfb141812009-11-03 03:42:51 +0000465 void OperandChangedState(Instruction *I) {
466 if (BBExecutable.count(I->getParent())) // Inst is executable?
467 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000468 }
Chris Lattner55033282009-11-02 06:28:16 +0000469
470 /// RemoveFromOverdefinedPHIs - If I has any entries in the
471 /// UsersOfOverdefinedPHIs map for PN, remove them now.
472 void RemoveFromOverdefinedPHIs(Instruction *I, PHINode *PN) {
473 if (UsersOfOverdefinedPHIs.empty()) return;
Chris Lattner5cf753c2011-07-21 06:21:31 +0000474 typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
475 std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(PN);
476 for (ItTy It = Range.first, E = Range.second; It != E;) {
Chris Lattner55033282009-11-02 06:28:16 +0000477 if (It->second == I)
478 UsersOfOverdefinedPHIs.erase(It++);
479 else
480 ++It;
481 }
482 }
Chris Lattner074be1f2004-11-15 04:44:20 +0000483
Dale Johannesend3a58c82010-11-30 20:23:21 +0000484 /// InsertInOverdefinedPHIs - Insert an entry in the UsersOfOverdefinedPHIS
485 /// map for I and PN, but if one is there already, do not create another.
486 /// (Duplicate entries do not break anything directly, but can lead to
487 /// exponential growth of the table in rare cases.)
488 void InsertInOverdefinedPHIs(Instruction *I, PHINode *PN) {
Chris Lattner5cf753c2011-07-21 06:21:31 +0000489 typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
490 std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(PN);
491 for (ItTy J = Range.first, E = Range.second; J != E; ++J)
Chris Lattnered1fb922011-01-16 07:11:21 +0000492 if (J->second == I)
493 return;
494 UsersOfOverdefinedPHIs.insert(std::make_pair(PN, I));
Dale Johannesend3a58c82010-11-30 20:23:21 +0000495 }
496
Chris Lattner074be1f2004-11-15 04:44:20 +0000497private:
498 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000499
Chris Lattnera3c39d32009-11-02 02:33:50 +0000500 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000501 // operand made a transition, or the instruction is newly executable. Change
502 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000503 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000504
505 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000506 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000507 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000508
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000509 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000510 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000511 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000512 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000513 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000514 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000515 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000516 void visitExtractValueInst(ExtractValueInst &EVI);
517 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner6e560792002-04-18 15:13:15 +0000518
Chris Lattnera3c39d32009-11-02 02:33:50 +0000519 // Instructions that cannot be folded away.
Chris Lattnerf5484032009-11-02 05:55:40 +0000520 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000521 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000522 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandeze2971492009-10-24 04:23:03 +0000523 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000524 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000525 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000526 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000527 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000528 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000529 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000530 void visitCallSite (CallSite CS);
Chris Lattner9c58cf62003-09-08 18:54:55 +0000531 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000532 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Eli Friedman89b694b2011-07-27 01:08:30 +0000533 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Victor Hernandez8acf2952009-10-23 21:09:37 +0000534 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner156b8c72009-11-03 23:40:48 +0000535 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000536
Chris Lattner113f4f42002-06-25 16:13:24 +0000537 void visitInstruction(Instruction &I) {
Chris Lattnera3c39d32009-11-02 02:33:50 +0000538 // If a new instruction is added to LLVM that we don't handle.
David Greene389fc3b2010-01-05 01:27:15 +0000539 dbgs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner156b8c72009-11-03 23:40:48 +0000540 markAnythingOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000541 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000542};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000543
Duncan Sands2be91fc2007-07-20 08:56:21 +0000544} // end anonymous namespace
545
546
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000547// getFeasibleSuccessors - Return a vector of booleans to indicate which
548// successors are reachable from a given terminator instruction.
549//
Chris Lattner074be1f2004-11-15 04:44:20 +0000550void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner37d400a2007-02-02 21:15:06 +0000551 SmallVector<bool, 16> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000552 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000553 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000554 if (BI->isUnconditional()) {
555 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000556 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000557 }
Chris Lattner6df5cec2009-11-02 02:30:06 +0000558
Chris Lattnerf5484032009-11-02 05:55:40 +0000559 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000560 ConstantInt *CI = BCValue.getConstantInt();
561 if (CI == 0) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000562 // Overdefined condition variables, and branches on unfoldable constant
563 // conditions, mean the branch could go either way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000564 if (!BCValue.isUndefined())
565 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000566 return;
567 }
568
569 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000570 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000571 return;
572 }
573
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000574 if (isa<InvokeInst>(TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000575 // Invoke instructions successors are always executable.
576 Succs[0] = Succs[1] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000577 return;
578 }
579
580 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000581 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000582 ConstantInt *CI = SCValue.getConstantInt();
583
584 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000585 // All destinations are executable!
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000586 if (!SCValue.isUndefined())
587 Succs.assign(TI.getNumSuccessors(), true);
588 return;
589 }
590
591 Succs[SI->findCaseValue(CI)] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000592 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000593 }
Chris Lattneree8b9512009-10-29 01:21:20 +0000594
595 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
596 if (isa<IndirectBrInst>(&TI)) {
597 // Just mark all destinations executable!
598 Succs.assign(TI.getNumSuccessors(), true);
599 return;
600 }
601
602#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000603 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000604#endif
605 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000606}
607
608
Chris Lattner13b52e72002-05-02 21:18:01 +0000609// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000610// block to the 'To' basic block is currently feasible.
Chris Lattner13b52e72002-05-02 21:18:01 +0000611//
Chris Lattner074be1f2004-11-15 04:44:20 +0000612bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000613 assert(BBExecutable.count(To) && "Dest should always be alive!");
614
615 // Make sure the source basic block is executable!!
616 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000617
Chris Lattnera3c39d32009-11-02 02:33:50 +0000618 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000619 TerminatorInst *TI = From->getTerminator();
620 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
621 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000622 return true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000623
Chris Lattnerf5484032009-11-02 05:55:40 +0000624 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000625
Chris Lattner6df5cec2009-11-02 02:30:06 +0000626 // Overdefined condition variables mean the branch could go either way,
627 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000628 ConstantInt *CI = BCValue.getConstantInt();
629 if (CI == 0)
630 return !BCValue.isUndefined();
Chris Lattner6df5cec2009-11-02 02:30:06 +0000631
Chris Lattner6df5cec2009-11-02 02:30:06 +0000632 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000633 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000634 }
635
636 // Invoke instructions successors are always executable.
637 if (isa<InvokeInst>(TI))
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000638 return true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000639
640 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000641 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000642 ConstantInt *CI = SCValue.getConstantInt();
643
644 if (CI == 0)
645 return !SCValue.isUndefined();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000646
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000647 // Make sure to skip the "default value" which isn't a value
648 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
649 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
650 return SI->getSuccessor(i) == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000651
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000652 // If the constant value is not equal to any of the branches, we must
653 // execute default branch.
654 return SI->getDefaultDest() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000655 }
Chris Lattneree8b9512009-10-29 01:21:20 +0000656
657 // Just mark all destinations executable!
658 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman3de2ddc2011-05-21 19:13:10 +0000659 if (isa<IndirectBrInst>(TI))
Chris Lattneree8b9512009-10-29 01:21:20 +0000660 return true;
661
662#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000663 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000664#endif
665 llvm_unreachable(0);
Chris Lattner13b52e72002-05-02 21:18:01 +0000666}
Chris Lattner347389d2001-06-27 23:38:11 +0000667
Chris Lattnera3c39d32009-11-02 02:33:50 +0000668// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000669// operand made a transition, or the instruction is newly executable. Change
670// the value type of I to reflect these changes if appropriate. This method
671// makes sure to do the following actions:
672//
673// 1. If a phi node merges two constants in, and has conflicting value coming
674// from different branches, or if the PHI node merges in an overdefined
675// value, then the PHI node becomes overdefined.
676// 2. If a phi node merges only constants in, and they all agree on value, the
677// PHI node becomes a constant value equal to that.
678// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
679// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
680// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
681// 6. If a conditional branch has a value that is constant, make the selected
682// destination executable
683// 7. If a conditional branch has a value that is overdefined, make all
684// successors executable.
685//
Chris Lattner074be1f2004-11-15 04:44:20 +0000686void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000687 // If this PN returns a struct, just mark the result overdefined.
688 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000689 if (PN.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000690 return markAnythingOverdefined(&PN);
691
Chris Lattnerf5484032009-11-02 05:55:40 +0000692 if (getValueState(&PN).isOverdefined()) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000693 // There may be instructions using this PHI node that are not overdefined
694 // themselves. If so, make sure that they know that the PHI node operand
695 // changed.
Chris Lattner5cf753c2011-07-21 06:21:31 +0000696 typedef std::multimap<PHINode*, Instruction*>::iterator ItTy;
697 std::pair<ItTy, ItTy> Range = UsersOfOverdefinedPHIs.equal_range(&PN);
698
699 if (Range.first == Range.second)
Chris Lattnerf5484032009-11-02 05:55:40 +0000700 return;
701
702 SmallVector<Instruction*, 16> Users;
Chris Lattner5cf753c2011-07-21 06:21:31 +0000703 for (ItTy I = Range.first, E = Range.second; I != E; ++I)
Chris Lattnerf5484032009-11-02 05:55:40 +0000704 Users.push_back(I->second);
705 while (!Users.empty())
706 visit(Users.pop_back_val());
Chris Lattner05fe6842004-01-12 03:57:30 +0000707 return; // Quick exit
708 }
Chris Lattner347389d2001-06-27 23:38:11 +0000709
Chris Lattner7a7b1142004-03-16 19:49:59 +0000710 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
711 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000712 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000713 return markOverdefined(&PN);
Chris Lattner156b8c72009-11-03 23:40:48 +0000714
Chris Lattner6e560792002-04-18 15:13:15 +0000715 // Look at all of the executable operands of the PHI node. If any of them
716 // are overdefined, the PHI becomes overdefined as well. If they are all
717 // constant, and they agree with each other, the PHI becomes the identical
718 // constant. If they are constant and don't agree, the PHI is overdefined.
719 // If there are no executable operands, the PHI remains undefined.
720 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000721 Constant *OperandVal = 0;
722 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000723 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000724 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000725
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000726 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
727 continue;
728
729 if (IV.isOverdefined()) // PHI node becomes overdefined!
730 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000731
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000732 if (OperandVal == 0) { // Grab the first value.
733 OperandVal = IV.getConstant();
734 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000735 }
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000736
737 // There is already a reachable operand. If we conflict with it,
738 // then the PHI node becomes overdefined. If we agree with it, we
739 // can continue on.
740
741 // Check to see if there are two different constants merging, if so, the PHI
742 // node is overdefined.
743 if (IV.getConstant() != OperandVal)
744 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000745 }
746
Chris Lattner6e560792002-04-18 15:13:15 +0000747 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000748 // arguments that agree with each other(and OperandVal is the constant) or
749 // OperandVal is null because there are no defined incoming arguments. If
750 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000751 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000752 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000753 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000754}
755
Chris Lattnerfb141812009-11-03 03:42:51 +0000756
757
758
Chris Lattnerb4394642004-12-10 08:02:06 +0000759void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000760 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000761
Chris Lattnerb4394642004-12-10 08:02:06 +0000762 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000763 Value *ResultOp = I.getOperand(0);
Chris Lattnerfb141812009-11-03 03:42:51 +0000764
Devang Patela7a20752008-03-11 05:46:42 +0000765 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000766 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000767 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000768 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000769 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000770 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000771 return;
772 }
773 }
774
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000775 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000776 if (!TrackedMultipleRetVals.empty()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000777 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000778 if (MRVFunctionsTracked.count(F))
779 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
780 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
781 getStructValueState(ResultOp, i));
782
Chris Lattnerb4394642004-12-10 08:02:06 +0000783 }
784}
785
Chris Lattner074be1f2004-11-15 04:44:20 +0000786void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000787 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000788 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000789
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000790 BasicBlock *BB = TI.getParent();
791
Chris Lattnera3c39d32009-11-02 02:33:50 +0000792 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000793 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000794 if (SuccFeasible[i])
795 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000796}
797
Chris Lattner074be1f2004-11-15 04:44:20 +0000798void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000799 LatticeVal OpSt = getValueState(I.getOperand(0));
800 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000801 markOverdefined(&I);
Chris Lattnerf5484032009-11-02 05:55:40 +0000802 else if (OpSt.isConstant()) // Propagate constant value
Owen Anderson487375e2009-07-29 18:55:55 +0000803 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattnerf5484032009-11-02 05:55:40 +0000804 OpSt.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000805}
806
Chris Lattner156b8c72009-11-03 23:40:48 +0000807
Dan Gohman041f9d02008-06-20 01:15:44 +0000808void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000809 // If this returns a struct, mark all elements over defined, we don't track
810 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000811 if (EVI.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000812 return markAnythingOverdefined(&EVI);
813
814 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000815 if (EVI.getNumIndices() != 1)
816 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000817
Chris Lattner156b8c72009-11-03 23:40:48 +0000818 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000819 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000820 unsigned i = *EVI.idx_begin();
821 LatticeVal EltVal = getStructValueState(AggVal, i);
822 mergeInValue(getValueState(&EVI), &EVI, EltVal);
823 } else {
824 // Otherwise, must be extracting from an array.
825 return markOverdefined(&EVI);
826 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000827}
828
829void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000830 StructType *STy = dyn_cast<StructType>(IVI.getType());
Chris Lattner156b8c72009-11-03 23:40:48 +0000831 if (STy == 0)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000832 return markOverdefined(&IVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000833
Chris Lattner156b8c72009-11-03 23:40:48 +0000834 // If this has more than one index, we can't handle it, drive all results to
835 // undef.
836 if (IVI.getNumIndices() != 1)
837 return markAnythingOverdefined(&IVI);
838
839 Value *Aggr = IVI.getAggregateOperand();
840 unsigned Idx = *IVI.idx_begin();
841
842 // Compute the result based on what we're inserting.
843 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
844 // This passes through all values that aren't the inserted element.
845 if (i != Idx) {
846 LatticeVal EltVal = getStructValueState(Aggr, i);
847 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
848 continue;
849 }
850
851 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000852 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000853 // We don't track structs in structs.
854 markOverdefined(getStructValueState(&IVI, i), &IVI);
855 else {
856 LatticeVal InVal = getValueState(Val);
857 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
858 }
859 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000860}
861
Chris Lattner074be1f2004-11-15 04:44:20 +0000862void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000863 // If this select returns a struct, just mark the result overdefined.
864 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000865 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000866 return markAnythingOverdefined(&I);
867
Chris Lattnerf5484032009-11-02 05:55:40 +0000868 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000869 if (CondValue.isUndefined())
870 return;
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000871
872 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000873 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
874 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000875 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000876 }
877
878 // Otherwise, the condition is overdefined or a constant we can't evaluate.
879 // See if we can produce something better than overdefined based on the T/F
880 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000881 LatticeVal TVal = getValueState(I.getTrueValue());
882 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000883
884 // select ?, C, C -> C.
885 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000886 TVal.getConstant() == FVal.getConstant())
887 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000888
Chris Lattnerf5484032009-11-02 05:55:40 +0000889 if (TVal.isUndefined()) // select ?, undef, X -> X.
890 return mergeInValue(&I, FVal);
891 if (FVal.isUndefined()) // select ?, X, undef -> X.
892 return mergeInValue(&I, TVal);
893 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000894}
895
Chris Lattnerf5484032009-11-02 05:55:40 +0000896// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000897void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000898 LatticeVal V1State = getValueState(I.getOperand(0));
899 LatticeVal V2State = getValueState(I.getOperand(1));
900
Chris Lattner4f031622004-11-15 05:03:30 +0000901 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000902 if (IV.isOverdefined()) return;
903
Chris Lattnerf5484032009-11-02 05:55:40 +0000904 if (V1State.isConstant() && V2State.isConstant())
905 return markConstant(IV, &I,
906 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
907 V2State.getConstant()));
908
909 // If something is undef, wait for it to resolve.
910 if (!V1State.isOverdefined() && !V2State.isOverdefined())
911 return;
912
913 // Otherwise, one of our operands is overdefined. Try to produce something
914 // better than overdefined with some tricks.
915
916 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
917 // operand is overdefined.
918 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
919 LatticeVal *NonOverdefVal = 0;
920 if (!V1State.isOverdefined())
921 NonOverdefVal = &V1State;
922 else if (!V2State.isOverdefined())
923 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000924
Chris Lattnerf5484032009-11-02 05:55:40 +0000925 if (NonOverdefVal) {
926 if (NonOverdefVal->isUndefined()) {
927 // Could annihilate value.
928 if (I.getOpcode() == Instruction::And)
929 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner229907c2011-07-18 04:54:35 +0000930 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattnerf5484032009-11-02 05:55:40 +0000931 markConstant(IV, &I, Constant::getAllOnesValue(PT));
932 else
933 markConstant(IV, &I,
934 Constant::getAllOnesValue(I.getType()));
935 return;
Chris Lattnercbc01612004-12-11 23:15:19 +0000936 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000937
938 if (I.getOpcode() == Instruction::And) {
939 // X and 0 = 0
940 if (NonOverdefVal->getConstant()->isNullValue())
941 return markConstant(IV, &I, NonOverdefVal->getConstant());
942 } else {
943 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
944 if (CI->isAllOnesValue()) // X or -1 = -1
945 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +0000946 }
947 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000948 }
Chris Lattnercbc01612004-12-11 23:15:19 +0000949
950
Chris Lattnerf5484032009-11-02 05:55:40 +0000951 // If both operands are PHI nodes, it is possible that this instruction has
952 // a constant value, despite the fact that the PHI node doesn't. Check for
953 // this condition now.
954 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
955 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
956 if (PN1->getParent() == PN2->getParent()) {
957 // Since the two PHI nodes are in the same basic block, they must have
958 // entries for the same predecessors. Walk the predecessor list, and
959 // if all of the incoming values are constants, and the result of
960 // evaluating this expression with all incoming value pairs is the
961 // same, then this expression is a constant even though the PHI node
962 // is not a constant!
963 LatticeVal Result;
964 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
965 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
966 BasicBlock *InBlock = PN1->getIncomingBlock(i);
967 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner05fe6842004-01-12 03:57:30 +0000968
Chris Lattnerf5484032009-11-02 05:55:40 +0000969 if (In1.isOverdefined() || In2.isOverdefined()) {
970 Result.markOverdefined();
971 break; // Cannot fold this operation over the PHI nodes!
972 }
973
974 if (In1.isConstant() && In2.isConstant()) {
975 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
976 In2.getConstant());
977 if (Result.isUndefined())
978 Result.markConstant(V);
979 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner05fe6842004-01-12 03:57:30 +0000980 Result.markOverdefined();
Chris Lattnerf5484032009-11-02 05:55:40 +0000981 break;
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000982 }
Chris Lattner05fe6842004-01-12 03:57:30 +0000983 }
984 }
985
Chris Lattnerf5484032009-11-02 05:55:40 +0000986 // If we found a constant value here, then we know the instruction is
987 // constant despite the fact that the PHI nodes are overdefined.
988 if (Result.isConstant()) {
989 markConstant(IV, &I, Result.getConstant());
990 // Remember that this instruction is virtually using the PHI node
Dale Johannesend3a58c82010-11-30 20:23:21 +0000991 // operands.
992 InsertInOverdefinedPHIs(&I, PN1);
993 InsertInOverdefinedPHIs(&I, PN2);
Chris Lattnerf5484032009-11-02 05:55:40 +0000994 return;
995 }
996
997 if (Result.isUndefined())
998 return;
999
1000 // Okay, this really is overdefined now. Since we might have
1001 // speculatively thought that this was not overdefined before, and
1002 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1003 // make sure to clean out any entries that we put there, for
1004 // efficiency.
Chris Lattner55033282009-11-02 06:28:16 +00001005 RemoveFromOverdefinedPHIs(&I, PN1);
1006 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattnerf5484032009-11-02 05:55:40 +00001007 }
1008
1009 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +00001010}
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001011
Chris Lattnera3c39d32009-11-02 02:33:50 +00001012// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +00001013void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001014 LatticeVal V1State = getValueState(I.getOperand(0));
1015 LatticeVal V2State = getValueState(I.getOperand(1));
1016
Reid Spencer266e42b2006-12-23 06:05:41 +00001017 LatticeVal &IV = ValueState[&I];
1018 if (IV.isOverdefined()) return;
1019
Chris Lattnerf5484032009-11-02 05:55:40 +00001020 if (V1State.isConstant() && V2State.isConstant())
1021 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
1022 V1State.getConstant(),
1023 V2State.getConstant()));
1024
1025 // If operands are still undefined, wait for it to resolve.
1026 if (!V1State.isOverdefined() && !V2State.isOverdefined())
1027 return;
1028
1029 // If something is overdefined, use some tricks to avoid ending up and over
1030 // defined if we can.
1031
1032 // If both operands are PHI nodes, it is possible that this instruction has
1033 // a constant value, despite the fact that the PHI node doesn't. Check for
1034 // this condition now.
1035 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
1036 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
1037 if (PN1->getParent() == PN2->getParent()) {
1038 // Since the two PHI nodes are in the same basic block, they must have
1039 // entries for the same predecessors. Walk the predecessor list, and
1040 // if all of the incoming values are constants, and the result of
1041 // evaluating this expression with all incoming value pairs is the
1042 // same, then this expression is a constant even though the PHI node
1043 // is not a constant!
1044 LatticeVal Result;
1045 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
1046 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
1047 BasicBlock *InBlock = PN1->getIncomingBlock(i);
1048 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencer266e42b2006-12-23 06:05:41 +00001049
Chris Lattnerf5484032009-11-02 05:55:40 +00001050 if (In1.isOverdefined() || In2.isOverdefined()) {
1051 Result.markOverdefined();
1052 break; // Cannot fold this operation over the PHI nodes!
1053 }
1054
1055 if (In1.isConstant() && In2.isConstant()) {
1056 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
1057 In1.getConstant(),
1058 In2.getConstant());
1059 if (Result.isUndefined())
1060 Result.markConstant(V);
1061 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencer266e42b2006-12-23 06:05:41 +00001062 Result.markOverdefined();
Chris Lattnerf5484032009-11-02 05:55:40 +00001063 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00001064 }
1065 }
Reid Spencer266e42b2006-12-23 06:05:41 +00001066 }
1067
Chris Lattnerf5484032009-11-02 05:55:40 +00001068 // If we found a constant value here, then we know the instruction is
1069 // constant despite the fact that the PHI nodes are overdefined.
1070 if (Result.isConstant()) {
1071 markConstant(&I, Result.getConstant());
1072 // Remember that this instruction is virtually using the PHI node
1073 // operands.
Dale Johannesend3a58c82010-11-30 20:23:21 +00001074 InsertInOverdefinedPHIs(&I, PN1);
1075 InsertInOverdefinedPHIs(&I, PN2);
Chris Lattnerf5484032009-11-02 05:55:40 +00001076 return;
1077 }
1078
1079 if (Result.isUndefined())
1080 return;
1081
1082 // Okay, this really is overdefined now. Since we might have
1083 // speculatively thought that this was not overdefined before, and
1084 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1085 // make sure to clean out any entries that we put there, for
1086 // efficiency.
Chris Lattner55033282009-11-02 06:28:16 +00001087 RemoveFromOverdefinedPHIs(&I, PN1);
1088 RemoveFromOverdefinedPHIs(&I, PN2);
Chris Lattnerf5484032009-11-02 05:55:40 +00001089 }
1090
1091 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +00001092}
1093
Robert Bocchinobd518d12006-01-10 19:05:05 +00001094void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001095 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001096 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +00001097
1098#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +00001099 LatticeVal &ValState = getValueState(I.getOperand(0));
1100 LatticeVal &IdxState = getValueState(I.getOperand(1));
1101
1102 if (ValState.isOverdefined() || IdxState.isOverdefined())
1103 markOverdefined(&I);
1104 else if(ValState.isConstant() && IdxState.isConstant())
1105 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1106 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +00001107#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +00001108}
1109
Robert Bocchino6dce2502006-01-17 20:06:55 +00001110void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001111 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001112 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +00001113#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +00001114 LatticeVal &ValState = getValueState(I.getOperand(0));
1115 LatticeVal &EltState = getValueState(I.getOperand(1));
1116 LatticeVal &IdxState = getValueState(I.getOperand(2));
1117
1118 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1119 IdxState.isOverdefined())
1120 markOverdefined(&I);
1121 else if(ValState.isConstant() && EltState.isConstant() &&
1122 IdxState.isConstant())
1123 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1124 EltState.getConstant(),
1125 IdxState.getConstant()));
1126 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel21efc732006-12-04 23:54:59 +00001127 IdxState.isConstant())
Chris Lattner28d921d2007-04-14 23:32:02 +00001128 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1129 EltState.getConstant(),
1130 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +00001131#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +00001132}
1133
Chris Lattner17bd6052006-04-08 01:19:12 +00001134void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001135 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001136 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +00001137#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +00001138 LatticeVal &V1State = getValueState(I.getOperand(0));
1139 LatticeVal &V2State = getValueState(I.getOperand(1));
1140 LatticeVal &MaskState = getValueState(I.getOperand(2));
1141
1142 if (MaskState.isUndefined() ||
1143 (V1State.isUndefined() && V2State.isUndefined()))
1144 return; // Undefined output if mask or both inputs undefined.
1145
1146 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1147 MaskState.isOverdefined()) {
1148 markOverdefined(&I);
1149 } else {
1150 // A mix of constant/undef inputs.
1151 Constant *V1 = V1State.isConstant() ?
1152 V1State.getConstant() : UndefValue::get(I.getType());
1153 Constant *V2 = V2State.isConstant() ?
1154 V2State.getConstant() : UndefValue::get(I.getType());
1155 Constant *Mask = MaskState.isConstant() ?
1156 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1157 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1158 }
Devang Patel21efc732006-12-04 23:54:59 +00001159#endif
Chris Lattner17bd6052006-04-08 01:19:12 +00001160}
1161
Chris Lattnera3c39d32009-11-02 02:33:50 +00001162// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001163// can turn this into a getelementptr ConstantExpr.
1164//
Chris Lattner074be1f2004-11-15 04:44:20 +00001165void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001166 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001167
Chris Lattner0e7ec672007-02-02 20:51:48 +00001168 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001169 Operands.reserve(I.getNumOperands());
1170
1171 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001172 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001173 if (State.isUndefined())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001174 return; // Operands are not resolved yet.
1175
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001176 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001177 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001178
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001179 assert(State.isConstant() && "Unknown state!");
1180 Operands.push_back(State.getConstant());
1181 }
1182
1183 Constant *Ptr = Operands[0];
Jay Foaded8db7d2011-07-21 14:31:17 +00001184 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1185 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001186}
Brian Gaeke960707c2003-11-11 22:41:34 +00001187
Chris Lattnerf5484032009-11-02 05:55:40 +00001188void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001189 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001190 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001191 return;
1192
Chris Lattner91dbae62004-12-11 05:15:59 +00001193 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1194 return;
Chris Lattnerf5484032009-11-02 05:55:40 +00001195
Chris Lattner91dbae62004-12-11 05:15:59 +00001196 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001197 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001198 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1199
Chris Lattnerf5484032009-11-02 05:55:40 +00001200 // Get the value we are storing into the global, then merge it.
1201 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001202 if (I->second.isOverdefined())
1203 TrackedGlobals.erase(I); // No need to keep tracking this!
1204}
1205
1206
Chris Lattner49f74522004-01-12 04:29:41 +00001207// Handle load instructions. If the operand is a constant pointer to a constant
1208// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001209void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001210 // If this load is of a struct, just mark the result overdefined.
Duncan Sands19d0b472010-02-16 11:11:14 +00001211 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001212 return markAnythingOverdefined(&I);
1213
Chris Lattnerf5484032009-11-02 05:55:40 +00001214 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001215 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattnerf5484032009-11-02 05:55:40 +00001216
Chris Lattner4f031622004-11-15 05:03:30 +00001217 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001218 if (IV.isOverdefined()) return;
1219
Chris Lattnerf5484032009-11-02 05:55:40 +00001220 if (!PtrVal.isConstant() || I.isVolatile())
1221 return markOverdefined(IV, &I);
1222
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001223 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001224
Chris Lattnerf5484032009-11-02 05:55:40 +00001225 // load null -> null
1226 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1227 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1228
1229 // Transform load (constant global) into the value loaded.
1230 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001231 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001232 // If we are tracking this global, merge in the known value for it.
1233 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1234 TrackedGlobals.find(GV);
1235 if (It != TrackedGlobals.end()) {
1236 mergeInValue(IV, &I, It->second);
1237 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001238 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001239 }
Chris Lattner49f74522004-01-12 04:29:41 +00001240 }
1241
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001242 // Transform load from a constant into a constant if possible.
1243 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1244 return markConstant(IV, &I, C);
Chris Lattnerf5484032009-11-02 05:55:40 +00001245
Chris Lattner49f74522004-01-12 04:29:41 +00001246 // Otherwise we cannot say for certain what value this load will produce.
1247 // Bail out.
1248 markOverdefined(IV, &I);
1249}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001250
Chris Lattnerb4394642004-12-10 08:02:06 +00001251void SCCPSolver::visitCallSite(CallSite CS) {
1252 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001253 Instruction *I = CS.getInstruction();
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001254
1255 // The common case is that we aren't tracking the callee, either because we
1256 // are not doing interprocedural analysis or the callee is indirect, or is
1257 // external. Handle these cases first.
Chris Lattnerfb141812009-11-03 03:42:51 +00001258 if (F == 0 || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001259CallOverdefined:
1260 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001261 if (I->getType()->isVoidTy()) return;
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001262
1263 // Otherwise, if we have a single return value case, and if the function is
1264 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001265 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001266 canConstantFoldCallTo(F)) {
1267
1268 SmallVector<Constant*, 8> Operands;
1269 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1270 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001271 LatticeVal State = getValueState(*AI);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001272
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001273 if (State.isUndefined())
1274 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001275 if (State.isOverdefined())
1276 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001277 assert(State.isConstant() && "Unknown state!");
1278 Operands.push_back(State.getConstant());
1279 }
1280
1281 // If we can constant fold this, mark the result of the call as a
1282 // constant.
Jay Foadf4b14a22011-07-19 13:32:40 +00001283 if (Constant *C = ConstantFoldCall(F, Operands))
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001284 return markConstant(I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001285 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001286
1287 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner156b8c72009-11-03 23:40:48 +00001288 return markAnythingOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001289 }
1290
Chris Lattnercde8de52009-11-03 19:24:51 +00001291 // If this is a local function that doesn't have its address taken, mark its
1292 // entry block executable and merge in the actual arguments to the call into
1293 // the formal arguments of the function.
1294 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1295 MarkBlockExecutable(F->begin());
1296
1297 // Propagate information from this call site into the callee.
1298 CallSite::arg_iterator CAI = CS.arg_begin();
1299 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1300 AI != E; ++AI, ++CAI) {
1301 // If this argument is byval, and if the function is not readonly, there
1302 // will be an implicit copy formed of the input aggregate.
1303 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1304 markOverdefined(AI);
1305 continue;
1306 }
1307
Chris Lattner229907c2011-07-18 04:54:35 +00001308 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001309 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1310 LatticeVal CallArg = getStructValueState(*CAI, i);
1311 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1312 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001313 } else {
1314 mergeInValue(AI, getValueState(*CAI));
1315 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001316 }
1317 }
1318
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001319 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattner229907c2011-07-18 04:54:35 +00001320 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001321 if (!MRVFunctionsTracked.count(F))
1322 goto CallOverdefined; // Not tracking this callee.
1323
1324 // If we are tracking this callee, propagate the result of the function
1325 // into this call site.
1326 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1327 mergeInValue(getStructValueState(I, i), I,
1328 TrackedMultipleRetVals[std::make_pair(F, i)]);
1329 } else {
1330 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1331 if (TFRVI == TrackedRetVals.end())
1332 goto CallOverdefined; // Not tracking this callee.
1333
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001334 // If so, propagate the return value of the callee into this call result.
1335 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001336 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001337}
Chris Lattner074be1f2004-11-15 04:44:20 +00001338
Chris Lattner074be1f2004-11-15 04:44:20 +00001339void SCCPSolver::Solve() {
1340 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001341 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001342 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001343 // Process the overdefined instruction's work list first, which drives other
1344 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001345 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001346 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001347
David Greene389fc3b2010-01-05 01:27:15 +00001348 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001349
Chris Lattner074be1f2004-11-15 04:44:20 +00001350 // "I" got into the work list because it either made the transition from
1351 // bottom to constant
1352 //
1353 // Anything on this worklist that is overdefined need not be visited
1354 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001355 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001356 //
1357 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1358 UI != E; ++UI)
Chris Lattnerfb141812009-11-03 03:42:51 +00001359 if (Instruction *I = dyn_cast<Instruction>(*UI))
1360 OperandChangedState(I);
Chris Lattner074be1f2004-11-15 04:44:20 +00001361 }
Chris Lattnera3c39d32009-11-02 02:33:50 +00001362
1363 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001364 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001365 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001366
David Greene389fc3b2010-01-05 01:27:15 +00001367 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001368
Chris Lattnerf5484032009-11-02 05:55:40 +00001369 // "I" got into the work list because it made the transition from undef to
1370 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001371 //
1372 // Anything on this worklist that is overdefined need not be visited
1373 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001374 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001375 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001376 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chris Lattner074be1f2004-11-15 04:44:20 +00001377 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1378 UI != E; ++UI)
Chris Lattnerfb141812009-11-03 03:42:51 +00001379 if (Instruction *I = dyn_cast<Instruction>(*UI))
1380 OperandChangedState(I);
Chris Lattner074be1f2004-11-15 04:44:20 +00001381 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001382
Chris Lattnera3c39d32009-11-02 02:33:50 +00001383 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001384 while (!BBWorkList.empty()) {
1385 BasicBlock *BB = BBWorkList.back();
1386 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001387
David Greene389fc3b2010-01-05 01:27:15 +00001388 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001389
Chris Lattner074be1f2004-11-15 04:44:20 +00001390 // Notify all instructions in this basic block that they are newly
1391 // executable.
1392 visit(BB);
1393 }
1394 }
1395}
1396
Chris Lattner1847f6d2006-12-20 06:21:33 +00001397/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001398/// that branches on undef values cannot reach any of their successors.
1399/// However, this is not a safe assumption. After we solve dataflow, this
1400/// method should be use to handle this. If this returns true, the solver
1401/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001402///
1403/// This method handles this by finding an unresolved branch and marking it one
1404/// of the edges from the block as being feasible, even though the condition
1405/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1406/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001407/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001408/// constraints on the condition of the branch, as that would impact other users
1409/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001410///
1411/// This scan also checks for values that use undefs, whose results are actually
1412/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1413/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1414/// even if X isn't defined.
1415bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001416 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1417 if (!BBExecutable.count(BB))
1418 continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001419
1420 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1421 // Look for instructions which produce undef values.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001422 if (I->getType()->isVoidTy()) continue;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001423
Chris Lattner229907c2011-07-18 04:54:35 +00001424 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001425 // Only a few things that can be structs matter for undef. Just send
1426 // all their results to overdefined. We could be more precise than this
1427 // but it isn't worth bothering.
1428 if (isa<CallInst>(I) || isa<SelectInst>(I)) {
1429 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1430 LatticeVal &LV = getStructValueState(I, i);
1431 if (LV.isUndefined())
1432 markOverdefined(LV, I);
1433 }
1434 }
1435 continue;
1436 }
1437
Chris Lattner1847f6d2006-12-20 06:21:33 +00001438 LatticeVal &LV = getValueState(I);
1439 if (!LV.isUndefined()) continue;
1440
Chris Lattner156b8c72009-11-03 23:40:48 +00001441 // No instructions using structs need disambiguation.
Duncan Sands19d0b472010-02-16 11:11:14 +00001442 if (I->getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001443 continue;
1444
Chris Lattner1847f6d2006-12-20 06:21:33 +00001445 // Get the lattice values of the first two operands for use below.
Chris Lattnerf5484032009-11-02 05:55:40 +00001446 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001447 LatticeVal Op1LV;
1448 if (I->getNumOperands() == 2) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001449 // No instructions using structs need disambiguation.
Duncan Sands19d0b472010-02-16 11:11:14 +00001450 if (I->getOperand(1)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001451 continue;
1452
Chris Lattner1847f6d2006-12-20 06:21:33 +00001453 // If this is a two-operand instruction, and if both operands are
1454 // undefs, the result stays undef.
1455 Op1LV = getValueState(I->getOperand(1));
1456 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1457 continue;
1458 }
1459
1460 // If this is an instructions whose result is defined even if the input is
1461 // not fully defined, propagate the information.
Chris Lattner229907c2011-07-18 04:54:35 +00001462 Type *ITy = I->getType();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001463 switch (I->getOpcode()) {
1464 default: break; // Leave the instruction as an undef.
1465 case Instruction::ZExt:
1466 // After a zero extend, we know the top part is zero. SExt doesn't have
1467 // to be handled here, because we don't know whether the top part is 1's
1468 // or 0's.
Chris Lattner87aa2242010-04-26 18:21:23 +00001469 case Instruction::SIToFP: // some FP values are not possible, just use 0.
1470 case Instruction::UIToFP: // some FP values are not possible, just use 0.
Chris Lattnerf5484032009-11-02 05:55:40 +00001471 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001472 return true;
1473 case Instruction::Mul:
1474 case Instruction::And:
1475 // undef * X -> 0. X could be zero.
1476 // undef & X -> 0. X could be zero.
Chris Lattnerf5484032009-11-02 05:55:40 +00001477 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001478 return true;
1479
1480 case Instruction::Or:
1481 // undef | X -> -1. X could be -1.
Chris Lattnerf5484032009-11-02 05:55:40 +00001482 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001483 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001484
1485 case Instruction::SDiv:
1486 case Instruction::UDiv:
1487 case Instruction::SRem:
1488 case Instruction::URem:
1489 // X / undef -> undef. No change.
1490 // X % undef -> undef. No change.
1491 if (Op1LV.isUndefined()) break;
1492
1493 // undef / X -> 0. X could be maxint.
1494 // undef % X -> 0. X could be 1.
Chris Lattnerf5484032009-11-02 05:55:40 +00001495 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001496 return true;
1497
1498 case Instruction::AShr:
1499 // undef >>s X -> undef. No change.
1500 if (Op0LV.isUndefined()) break;
1501
1502 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1503 if (Op0LV.isConstant())
Chris Lattnerf5484032009-11-02 05:55:40 +00001504 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001505 else
Chris Lattnerf5484032009-11-02 05:55:40 +00001506 markOverdefined(I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001507 return true;
1508 case Instruction::LShr:
1509 case Instruction::Shl:
1510 // undef >> X -> undef. No change.
1511 // undef << X -> undef. No change.
1512 if (Op0LV.isUndefined()) break;
1513
1514 // X >> undef -> 0. X could be 0.
1515 // X << undef -> 0. X could be 0.
Chris Lattnerf5484032009-11-02 05:55:40 +00001516 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001517 return true;
1518 case Instruction::Select:
1519 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1520 if (Op0LV.isUndefined()) {
1521 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1522 Op1LV = getValueState(I->getOperand(2));
1523 } else if (Op1LV.isUndefined()) {
1524 // c ? undef : undef -> undef. No change.
1525 Op1LV = getValueState(I->getOperand(2));
1526 if (Op1LV.isUndefined())
1527 break;
1528 // Otherwise, c ? undef : x -> x.
1529 } else {
1530 // Leave Op1LV as Operand(1)'s LatticeValue.
1531 }
1532
1533 if (Op1LV.isConstant())
Chris Lattnerf5484032009-11-02 05:55:40 +00001534 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001535 else
Chris Lattnerf5484032009-11-02 05:55:40 +00001536 markOverdefined(I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001537 return true;
Chris Lattner5c207c82008-05-24 03:59:33 +00001538 case Instruction::Call:
1539 // If a call has an undef result, it is because it is constant foldable
1540 // but one of the inputs was undef. Just force the result to
1541 // overdefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001542 markOverdefined(I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001543 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001544 }
1545 }
Chris Lattneraf170962006-10-22 05:59:17 +00001546
Chris Lattneradca6082010-04-05 22:14:48 +00001547 // Check to see if we have a branch or switch on an undefined value. If so
1548 // we force the branch to go one way or the other to make the successor
1549 // values live. It doesn't really matter which way we force it.
Chris Lattneraf170962006-10-22 05:59:17 +00001550 TerminatorInst *TI = BB->getTerminator();
1551 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1552 if (!BI->isConditional()) continue;
1553 if (!getValueState(BI->getCondition()).isUndefined())
1554 continue;
Chris Lattneradca6082010-04-05 22:14:48 +00001555
1556 // If the input to SCCP is actually branch on undef, fix the undef to
1557 // false.
1558 if (isa<UndefValue>(BI->getCondition())) {
1559 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1560 markEdgeExecutable(BB, TI->getSuccessor(1));
1561 return true;
1562 }
1563
1564 // Otherwise, it is a branch on a symbolic value which is currently
1565 // considered to be undef. Handle this by forcing the input value to the
1566 // branch to false.
1567 markForcedConstant(BI->getCondition(),
1568 ConstantInt::getFalse(TI->getContext()));
1569 return true;
1570 }
1571
1572 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner6df5cec2009-11-02 02:30:06 +00001573 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfecb8822008-05-23 01:01:31 +00001574 continue;
Chris Lattneraf170962006-10-22 05:59:17 +00001575 if (!getValueState(SI->getCondition()).isUndefined())
1576 continue;
Chris Lattneradca6082010-04-05 22:14:48 +00001577
1578 // If the input to SCCP is actually switch on undef, fix the undef to
1579 // the first constant.
1580 if (isa<UndefValue>(SI->getCondition())) {
1581 SI->setCondition(SI->getCaseValue(1));
1582 markEdgeExecutable(BB, TI->getSuccessor(1));
1583 return true;
1584 }
1585
1586 markForcedConstant(SI->getCondition(), SI->getCaseValue(1));
1587 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001588 }
Chris Lattneraf170962006-10-22 05:59:17 +00001589 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001590
Chris Lattneraf170962006-10-22 05:59:17 +00001591 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001592}
1593
Chris Lattner074be1f2004-11-15 04:44:20 +00001594
1595namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001596 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001597 //
Chris Lattner1890f942004-11-15 07:15:04 +00001598 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001599 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001600 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001601 struct SCCP : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +00001602 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001603 SCCP() : FunctionPass(ID) {
1604 initializeSCCPPass(*PassRegistry::getPassRegistry());
1605 }
Devang Patel09f162c2007-05-01 21:15:47 +00001606
Chris Lattner1890f942004-11-15 07:15:04 +00001607 // runOnFunction - Run the Sparse Conditional Constant Propagation
1608 // algorithm, and return true if the function was modified.
1609 //
1610 bool runOnFunction(Function &F);
Chris Lattner1890f942004-11-15 07:15:04 +00001611 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001612} // end anonymous namespace
1613
Dan Gohmand78c4002008-05-13 00:00:25 +00001614char SCCP::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +00001615INITIALIZE_PASS(SCCP, "sccp",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001616 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner074be1f2004-11-15 04:44:20 +00001617
Chris Lattnera3c39d32009-11-02 02:33:50 +00001618// createSCCPPass - This is the public interface to this file.
Chris Lattner074be1f2004-11-15 04:44:20 +00001619FunctionPass *llvm::createSCCPPass() {
1620 return new SCCP();
1621}
1622
Chris Lattnere405ed92009-11-02 02:47:51 +00001623static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greene389fc3b2010-01-05 01:27:15 +00001624 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001625 ++NumDeadBlocks;
1626
1627 // Delete the instructions backwards, as it has a reduced likelihood of
1628 // having to update as many def-use and use-def chains.
1629 while (!isa<TerminatorInst>(BB->begin())) {
1630 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1631
1632 if (!I->use_empty())
1633 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1634 BB->getInstList().erase(I);
1635 ++NumInstRemoved;
1636 }
1637}
Chris Lattner074be1f2004-11-15 04:44:20 +00001638
Chris Lattner074be1f2004-11-15 04:44:20 +00001639// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1640// and return true if the function was modified.
1641//
1642bool SCCP::runOnFunction(Function &F) {
David Greene389fc3b2010-01-05 01:27:15 +00001643 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001644 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner074be1f2004-11-15 04:44:20 +00001645
1646 // Mark the first block of the function as being executable.
1647 Solver.MarkBlockExecutable(F.begin());
1648
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001649 // Mark all arguments to the function as being overdefined.
Chris Lattner28d921d2007-04-14 23:32:02 +00001650 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner156b8c72009-11-03 23:40:48 +00001651 Solver.markAnythingOverdefined(AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001652
Chris Lattner074be1f2004-11-15 04:44:20 +00001653 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001654 bool ResolvedUndefs = true;
1655 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001656 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001657 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001658 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001659 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001660
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001661 bool MadeChanges = false;
1662
1663 // If we decided that there are basic blocks that are dead in this function,
1664 // delete their contents now. Note that we cannot actually delete the blocks,
1665 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001666
Chris Lattnere405ed92009-11-02 02:47:51 +00001667 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattneradd44f32008-08-23 23:39:31 +00001668 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnere405ed92009-11-02 02:47:51 +00001669 DeleteInstructionInBlock(BB);
1670 MadeChanges = true;
1671 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001672 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001673
1674 // Iterate over all of the instructions in a function, replacing them with
1675 // constants if we have found them to be of constant values.
1676 //
1677 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1678 Instruction *Inst = BI++;
1679 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1680 continue;
1681
Chris Lattner156b8c72009-11-03 23:40:48 +00001682 // TODO: Reconstruct structs from their elements.
Duncan Sands19d0b472010-02-16 11:11:14 +00001683 if (Inst->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001684 continue;
1685
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001686 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1687 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001688 continue;
1689
1690 Constant *Const = IV.isConstant()
1691 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene389fc3b2010-01-05 01:27:15 +00001692 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnere405ed92009-11-02 02:47:51 +00001693
1694 // Replaces all of the uses of a variable with uses of the constant.
1695 Inst->replaceAllUsesWith(Const);
1696
1697 // Delete the instruction.
1698 Inst->eraseFromParent();
1699
1700 // Hey, we just changed something!
1701 MadeChanges = true;
1702 ++NumInstRemoved;
1703 }
1704 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001705
1706 return MadeChanges;
1707}
Chris Lattnerb4394642004-12-10 08:02:06 +00001708
1709namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001710 //===--------------------------------------------------------------------===//
1711 //
1712 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1713 /// Constant Propagation.
1714 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001715 struct IPSCCP : public ModulePass {
Devang Patel8c78a0b2007-05-03 01:11:54 +00001716 static char ID;
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001717 IPSCCP() : ModulePass(ID) {
1718 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1719 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001720 bool runOnModule(Module &M);
1721 };
Chris Lattnerb4394642004-12-10 08:02:06 +00001722} // end anonymous namespace
1723
Dan Gohmand78c4002008-05-13 00:00:25 +00001724char IPSCCP::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +00001725INITIALIZE_PASS(IPSCCP, "ipsccp",
1726 "Interprocedural Sparse Conditional Constant Propagation",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001727 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +00001728
Chris Lattnera3c39d32009-11-02 02:33:50 +00001729// createIPSCCPPass - This is the public interface to this file.
Chris Lattnerb4394642004-12-10 08:02:06 +00001730ModulePass *llvm::createIPSCCPPass() {
1731 return new IPSCCP();
1732}
1733
1734
Gabor Greif9027ffb2010-03-24 10:29:52 +00001735static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001736 // Delete any dead constantexpr klingons.
1737 GV->removeDeadConstantUsers();
1738
Gabor Greifc78d7202010-03-25 23:06:16 +00001739 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif9027ffb2010-03-24 10:29:52 +00001740 UI != E; ++UI) {
1741 const User *U = *UI;
1742 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001743 if (SI->getOperand(0) == GV || SI->isVolatile())
1744 return true; // Storing addr of GV.
Gabor Greif9027ffb2010-03-24 10:29:52 +00001745 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001746 // Make sure we are calling the function, not passing the address.
Gabor Greif5d5db532010-04-01 08:21:08 +00001747 ImmutableCallSite CS(cast<Instruction>(U));
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00001748 if (!CS.isCallee(UI))
Nick Lewyckyd73806a2008-11-03 03:49:14 +00001749 return true;
Gabor Greif9027ffb2010-03-24 10:29:52 +00001750 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001751 if (LI->isVolatile())
1752 return true;
Gabor Greif9027ffb2010-03-24 10:29:52 +00001753 } else if (isa<BlockAddress>(U)) {
Chris Lattner1a8b80e2009-11-01 06:11:53 +00001754 // blockaddress doesn't take the address of the function, it takes addr
1755 // of label.
Chris Lattner91dbae62004-12-11 05:15:59 +00001756 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001757 return true;
1758 }
Gabor Greif9027ffb2010-03-24 10:29:52 +00001759 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001760 return false;
1761}
1762
1763bool IPSCCP::runOnModule(Module &M) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001764 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattnerb4394642004-12-10 08:02:06 +00001765
Chris Lattner363226d2010-08-12 22:25:23 +00001766 // AddressTakenFunctions - This set keeps track of the address-taken functions
1767 // that are in the input. As IPSCCP runs through and simplifies code,
1768 // functions that were address taken can end up losing their
1769 // address-taken-ness. Because of this, we keep track of their addresses from
1770 // the first pass so we can use them for the later simplification pass.
1771 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1772
Chris Lattnerb4394642004-12-10 08:02:06 +00001773 // Loop over all functions, marking arguments to those with their addresses
1774 // taken or that are external as overdefined.
1775 //
Chris Lattner47837c52009-11-02 06:34:04 +00001776 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1777 if (F->isDeclaration())
1778 continue;
1779
Chris Lattnerfb141812009-11-03 03:42:51 +00001780 // If this is a strong or ODR definition of this function, then we can
1781 // propagate information about its result into callsites of it.
Chris Lattner156b8c72009-11-03 23:40:48 +00001782 if (!F->mayBeOverridden())
Chris Lattnerb4394642004-12-10 08:02:06 +00001783 Solver.AddTrackedFunction(F);
Chris Lattnerfb141812009-11-03 03:42:51 +00001784
1785 // If this function only has direct calls that we can see, we can track its
1786 // arguments and return value aggressively, and can assume it is not called
1787 // unless we see evidence to the contrary.
Chris Lattner363226d2010-08-12 22:25:23 +00001788 if (F->hasLocalLinkage()) {
1789 if (AddressIsTaken(F))
1790 AddressTakenFunctions.insert(F);
1791 else {
1792 Solver.AddArgumentTrackedFunction(F);
1793 continue;
1794 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001795 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001796
1797 // Assume the function is called.
1798 Solver.MarkBlockExecutable(F->begin());
1799
1800 // Assume nothing about the incoming arguments.
1801 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1802 AI != E; ++AI)
Chris Lattner156b8c72009-11-03 23:40:48 +00001803 Solver.markAnythingOverdefined(AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001804 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001805
Chris Lattner91dbae62004-12-11 05:15:59 +00001806 // Loop over global variables. We inform the solver about any internal global
1807 // variables that do not have their 'addresses taken'. If they don't have
1808 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001809 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1810 G != E; ++G)
Rafael Espindola6de96a12009-01-15 20:18:42 +00001811 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattner91dbae62004-12-11 05:15:59 +00001812 Solver.TrackValueOfGlobalVariable(G);
1813
Chris Lattnerb4394642004-12-10 08:02:06 +00001814 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001815 bool ResolvedUndefs = true;
1816 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001817 Solver.Solve();
1818
David Greene389fc3b2010-01-05 01:27:15 +00001819 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001820 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001821 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001822 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001823 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001824
1825 bool MadeChanges = false;
1826
1827 // Iterate over all of the instructions in the module, replacing them with
1828 // constants if we have found them to be of constant values.
1829 //
Chris Lattner65938fc2008-08-23 23:36:38 +00001830 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001831
Chris Lattnerb4394642004-12-10 08:02:06 +00001832 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere82b0872009-11-02 03:25:55 +00001833 if (Solver.isBlockExecutable(F->begin())) {
1834 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1835 AI != E; ++AI) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001836 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Chris Lattnere82b0872009-11-02 03:25:55 +00001837
Chris Lattner156b8c72009-11-03 23:40:48 +00001838 // TODO: Could use getStructLatticeValueFor to find out if the entire
1839 // result is a constant and replace it entirely if so.
1840
Chris Lattnere82b0872009-11-02 03:25:55 +00001841 LatticeVal IV = Solver.getLatticeValueFor(AI);
1842 if (IV.isOverdefined()) continue;
1843
1844 Constant *CST = IV.isConstant() ?
1845 IV.getConstant() : UndefValue::get(AI->getType());
David Greene389fc3b2010-01-05 01:27:15 +00001846 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Chris Lattnere82b0872009-11-02 03:25:55 +00001847
1848 // Replaces all of the uses of a variable with uses of the
1849 // constant.
1850 AI->replaceAllUsesWith(CST);
1851 ++IPNumArgsElimed;
1852 }
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001853 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001854
Chris Lattnere405ed92009-11-02 02:47:51 +00001855 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattneradd44f32008-08-23 23:39:31 +00001856 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnere405ed92009-11-02 02:47:51 +00001857 DeleteInstructionInBlock(BB);
1858 MadeChanges = true;
Chris Lattner7285f432004-12-10 20:41:50 +00001859
Chris Lattnerbae4b642004-12-10 22:29:08 +00001860 TerminatorInst *TI = BB->getTerminator();
Chris Lattnerbae4b642004-12-10 22:29:08 +00001861 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1862 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmanc731c972007-10-03 19:26:29 +00001863 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattnerbae4b642004-12-10 22:29:08 +00001864 TI->getSuccessor(i)->removePredecessor(BB);
1865 }
Chris Lattner99e12952004-12-11 02:53:57 +00001866 if (!TI->use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001867 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnere405ed92009-11-02 02:47:51 +00001868 TI->eraseFromParent();
Chris Lattnerbae4b642004-12-10 22:29:08 +00001869
Chris Lattner8525ebe2004-12-11 05:32:19 +00001870 if (&*BB != &F->front())
1871 BlocksToErase.push_back(BB);
1872 else
Owen Anderson55f1c092009-08-13 21:58:54 +00001873 new UnreachableInst(M.getContext(), BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001874 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001875 }
Chris Lattnere405ed92009-11-02 02:47:51 +00001876
1877 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1878 Instruction *Inst = BI++;
Duncan Sands19d0b472010-02-16 11:11:14 +00001879 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001880 continue;
1881
Chris Lattner156b8c72009-11-03 23:40:48 +00001882 // TODO: Could use getStructLatticeValueFor to find out if the entire
1883 // result is a constant and replace it entirely if so.
1884
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001885 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1886 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001887 continue;
1888
1889 Constant *Const = IV.isConstant()
1890 ? IV.getConstant() : UndefValue::get(Inst->getType());
David Greene389fc3b2010-01-05 01:27:15 +00001891 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
Chris Lattnere405ed92009-11-02 02:47:51 +00001892
1893 // Replaces all of the uses of a variable with uses of the
1894 // constant.
1895 Inst->replaceAllUsesWith(Const);
1896
1897 // Delete the instruction.
1898 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1899 Inst->eraseFromParent();
1900
1901 // Hey, we just changed something!
1902 MadeChanges = true;
1903 ++IPNumInstRemoved;
1904 }
1905 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001906
1907 // Now that all instructions in the function are constant folded, erase dead
1908 // blocks, because we can now use ConstantFoldTerminator to get rid of
1909 // in-edges.
1910 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1911 // If there are any PHI nodes in this successor, drop entries for BB now.
1912 BasicBlock *DeadBB = BlocksToErase[i];
Dan Gohmand15302a2009-11-20 20:19:14 +00001913 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1914 UI != UE; ) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001915 // Grab the user and then increment the iterator early, as the user
1916 // will be deleted. Step past all adjacent uses from the same user.
1917 Instruction *I = dyn_cast<Instruction>(*UI);
1918 do { ++UI; } while (UI != UE && *UI == I);
1919
Dan Gohmand15302a2009-11-20 20:19:14 +00001920 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001921 if (!I) continue;
1922
Chris Lattnerbae4b642004-12-10 22:29:08 +00001923 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001924 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001925 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001926 // if this is a branch or switch on undef. Fold it manually as a
1927 // branch to the first successor.
Devang Patel45f1ae02008-11-21 01:52:59 +00001928#ifndef NDEBUG
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001929 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1930 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1931 "Branch should be foldable!");
1932 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1933 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1934 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001935 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001936 }
Devang Patel45f1ae02008-11-21 01:52:59 +00001937#endif
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001938
1939 // Make this an uncond branch to the first successor.
1940 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greife9ecc682008-04-06 20:25:17 +00001941 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001942
1943 // Remove entries in successor phi nodes to remove edges.
1944 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1945 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1946
1947 // Remove the old terminator.
1948 TI->eraseFromParent();
1949 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001950 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001951
Chris Lattnerbae4b642004-12-10 22:29:08 +00001952 // Finally, delete the basic block.
1953 F->getBasicBlockList().erase(DeadBB);
1954 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001955 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001956 }
Chris Lattner99e12952004-12-11 02:53:57 +00001957
1958 // If we inferred constant or undef return values for a function, we replaced
1959 // all call uses with the inferred value. This means we don't need to bother
1960 // actually returning anything from the function. Replace all return
1961 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001962 //
1963 // Do this in two stages: first identify the functions we should process, then
1964 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001965 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001966 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001967 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001968 SmallVector<ReturnInst*, 8> ReturnsToZap;
1969
Devang Patele418de32008-03-11 17:32:05 +00001970 // TODO: Process multiple value ret instructions also.
Devang Patela7a20752008-03-11 05:46:42 +00001971 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattner067d6072007-02-02 20:38:30 +00001972 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattnerfb141812009-11-03 03:42:51 +00001973 E = RV.end(); I != E; ++I) {
1974 Function *F = I->first;
1975 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1976 continue;
1977
1978 // We can only do this if we know that nothing else can call the function.
Chris Lattner363226d2010-08-12 22:25:23 +00001979 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattnerfb141812009-11-03 03:42:51 +00001980 continue;
1981
1982 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1983 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1984 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001985 ReturnsToZap.push_back(RI);
1986 }
1987
1988 // Zap all returns which we've identified as zap to change.
1989 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1990 Function *F = ReturnsToZap[i]->getParent()->getParent();
1991 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001992 }
1993
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001994 // If we inferred constant or undef values for globals variables, we can delete
Chris Lattner91dbae62004-12-11 05:15:59 +00001995 // the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001996 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1997 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001998 E = TG.end(); I != E; ++I) {
1999 GlobalVariable *GV = I->first;
2000 assert(!I->second.isOverdefined() &&
2001 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00002002 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00002003 while (!GV->use_empty()) {
2004 StoreInst *SI = cast<StoreInst>(GV->use_back());
2005 SI->eraseFromParent();
2006 }
2007 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00002008 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00002009 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002010
Chris Lattnerb4394642004-12-10 08:02:06 +00002011 return MadeChanges;
2012}