blob: dd9f7651a5deb7cf527fae43e5d26ec8e76c51b1 [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
Chris Lattner138a1242001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattneref36dfd2004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000022#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000023#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000024#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000025#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000026#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000027#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000029#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000030#include "llvm/Transforms/Utils/Local.h"
Chris Lattner5638dc62009-11-02 06:06:14 +000031#include "llvm/Target/TargetData.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000032#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000035#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000036#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000038#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000039#include "llvm/ADT/PointerIntPair.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000040#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000043#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000044#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumInstRemoved, "Number of instructions removed");
48STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
49
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000050STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000051STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
Chris Lattner0dbfc052002-04-29 21:26:08 +000054namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000055/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Chris Lattner3e8b6632009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000059 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000075 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner79272202009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Chris Lattner138a1242001-06-27 23:38:11 +000085public:
Chris Lattner38871e42009-11-02 03:03:42 +000086 LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000087
Chris Lattner38871e42009-11-02 03:03:42 +000088 bool isUndefined() const { return getLatticeValue() == undefined; }
89 bool isConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000090 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
Chris Lattner38871e42009-11-02 03:03:42 +000092 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner79272202009-11-02 02:20:32 +000093
Chris Lattner38871e42009-11-02 03:03:42 +000094 Constant *getConstant() const {
Chris Lattner79272202009-11-02 02:20:32 +000095 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
97 }
98
99 /// markOverdefined - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000100 bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000106 }
107
Chris Lattner79272202009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattner38871e42009-11-02 03:03:42 +0000109 bool markConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000110 if (isConstant()) {
111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000113 }
Chris Lattner79272202009-11-02 02:20:32 +0000114
115 if (isUndefined()) {
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
118 Val.setPointer(V);
119 } else {
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
124
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
129 }
130 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000131 }
132
Chris Lattner36c99522009-11-02 03:21:36 +0000133 /// getConstantInt - If this is a constant with a ConstantInt value, return it
134 /// otherwise return null.
135 ConstantInt *getConstantInt() const {
136 if (isConstant())
137 return dyn_cast<ConstantInt>(getConstant());
138 return 0;
139 }
140
Chris Lattner38871e42009-11-02 03:03:42 +0000141 void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000142 assert(isUndefined() && "Can't force a defined value!");
143 Val.setInt(forcedconstant);
144 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000145 }
Chris Lattner138a1242001-06-27 23:38:11 +0000146};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000147} // end anonymous namespace.
148
149
150namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000151
Chris Lattner138a1242001-06-27 23:38:11 +0000152//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000153//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000154/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
155/// Constant Propagation.
156///
157class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner5638dc62009-11-02 06:06:14 +0000158 const TargetData *TD;
Chris Lattnercf712de2008-08-23 23:36:38 +0000159 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner2a0433b2009-11-02 05:55:40 +0000160 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000161
Chris Lattnerdd336d12004-12-11 05:15:59 +0000162 /// GlobalValue - If we are tracking any values for the contents of a global
163 /// variable, we keep a mapping from the constant accessor to the element of
164 /// the global, to the currently known value. If the value becomes
165 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000166 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000167
Devang Patel7c490d42008-03-11 05:46:42 +0000168 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000169 /// value out of a function, it will have an entry in this map, indicating
170 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000171 DenseMap<Function*, LatticeVal> TrackedRetVals;
172
173 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
174 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000175 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000176
Chris Lattner38871e42009-11-02 03:03:42 +0000177 /// The reason for two worklists is that overdefined is the lowest state
178 /// on the lattice, and moving things to overdefined as fast as possible
179 /// makes SCCP converge much faster.
180 ///
181 /// By having a separate worklist, we accomplish this because everything
182 /// possibly overdefined will become overdefined at the soonest possible
183 /// point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000184 SmallVector<Value*, 64> OverdefinedInstWorkList;
185 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000186
187
Chris Lattnercf712de2008-08-23 23:36:38 +0000188 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000189
Chris Lattner1daee8b2004-01-12 03:57:30 +0000190 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
191 /// overdefined, despite the fact that the PHI node is overdefined.
192 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
193
Chris Lattner16b18fd2003-10-08 16:55:34 +0000194 /// KnownFeasibleEdges - Entries in this set are edges which have already had
195 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000196 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
197 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000198public:
Chris Lattner5638dc62009-11-02 06:06:14 +0000199 SCCPSolver(const TargetData *td) : TD(td) {}
Chris Lattner138a1242001-06-27 23:38:11 +0000200
Chris Lattner82bec2c2004-11-15 04:44:20 +0000201 /// MarkBlockExecutable - This method can be used by clients to mark all of
202 /// the blocks that are known to be intrinsically live in the processed unit.
203 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000204 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000205 BBExecutable.insert(BB); // Basic block is executable!
206 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000207 }
208
Chris Lattnerdd336d12004-12-11 05:15:59 +0000209 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000210 /// inform the SCCPSolver that it should track loads and stores to the
211 /// specified global variable if it can. This is only legal to call if
212 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000213 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
214 const Type *ElTy = GV->getType()->getElementType();
215 if (ElTy->isFirstClassType()) {
216 LatticeVal &IV = TrackedGlobals[GV];
217 if (!isa<UndefValue>(GV->getInitializer()))
218 IV.markConstant(GV->getInitializer());
219 }
220 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000221
222 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
223 /// and out of the specified function (which cannot have its address taken),
224 /// this method must be called.
225 void AddTrackedFunction(Function *F) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000226 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000227 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000228 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
229 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000230 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
231 LatticeVal()));
232 } else
233 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000234 }
235
Chris Lattner82bec2c2004-11-15 04:44:20 +0000236 /// Solve - Solve for constants and executable blocks.
237 ///
238 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000239
Chris Lattner3bad2532006-12-20 06:21:33 +0000240 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000241 /// that branches on undef values cannot reach any of their successors.
242 /// However, this is not a safe assumption. After we solve dataflow, this
243 /// method should be use to handle this. If this returns true, the solver
244 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000245 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000246
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000247 bool isBlockExecutable(BasicBlock *BB) const {
248 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000249 }
250
Chris Lattner8db50122009-11-02 02:54:24 +0000251 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000252 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattner8db50122009-11-02 02:54:24 +0000253 assert(I != ValueState.end() && "V is not in valuemap!");
254 return I->second;
Chris Lattner82bec2c2004-11-15 04:44:20 +0000255 }
256
Devang Patel7c490d42008-03-11 05:46:42 +0000257 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000258 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000259 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
260 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000261 }
262
Chris Lattnerdd336d12004-12-11 05:15:59 +0000263 /// getTrackedGlobals - Get and return the set of inferred initializers for
264 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000265 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000266 return TrackedGlobals;
267 }
268
Chris Lattner36c99522009-11-02 03:21:36 +0000269 void markOverdefined(Value *V) {
Chris Lattner57939df2007-03-04 04:50:21 +0000270 markOverdefined(ValueState[V], V);
271 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000272
Chris Lattner138a1242001-06-27 23:38:11 +0000273private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000274 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000275 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000276 // the users of the instruction are updated later.
277 //
Chris Lattner38871e42009-11-02 03:03:42 +0000278 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
279 if (!IV.markConstant(C)) return;
280 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
281 InstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000282 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000283
Chris Lattner38871e42009-11-02 03:03:42 +0000284 void markConstant(Value *V, Constant *C) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000285 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000286 }
287
Chris Lattner2a0433b2009-11-02 05:55:40 +0000288 void markForcedConstant(Value *V, Constant *C) {
289 ValueState[V].markForcedConstant(C);
290 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
291 InstWorkList.push_back(V);
292 }
293
294
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000295 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000296 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000297 // work list so that the users of the instruction are updated later.
Chris Lattner38871e42009-11-02 03:03:42 +0000298 void markOverdefined(LatticeVal &IV, Value *V) {
299 if (!IV.markOverdefined()) return;
300
301 DEBUG(errs() << "markOverdefined: ";
302 if (Function *F = dyn_cast<Function>(V))
303 errs() << "Function '" << F->getName() << "'\n";
304 else
305 errs() << *V << '\n');
306 // Only instructions go on the work list
307 OverdefinedInstWorkList.push_back(V);
Chris Lattner3d405b02003-10-08 16:21:03 +0000308 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000309
Chris Lattner2a0433b2009-11-02 05:55:40 +0000310 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattner59acc7d2004-12-10 08:02:06 +0000311 if (IV.isOverdefined() || MergeWithV.isUndefined())
312 return; // Noop.
313 if (MergeWithV.isOverdefined())
314 markOverdefined(IV, V);
315 else if (IV.isUndefined())
316 markConstant(IV, V, MergeWithV.getConstant());
317 else if (IV.getConstant() != MergeWithV.getConstant())
318 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000319 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000320
Chris Lattner2a0433b2009-11-02 05:55:40 +0000321 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner36c99522009-11-02 03:21:36 +0000322 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000323 }
324
Chris Lattner138a1242001-06-27 23:38:11 +0000325
Chris Lattner2a0433b2009-11-02 05:55:40 +0000326 /// getValueState - Return the LatticeVal object that corresponds to the
327 /// value. This function handles the case when the value hasn't been seen yet
328 /// by properly seeding constants etc.
Chris Lattner38871e42009-11-02 03:03:42 +0000329 LatticeVal &getValueState(Value *V) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000330 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000331 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000332
Chris Lattner36c99522009-11-02 03:21:36 +0000333 LatticeVal &LV = ValueState[V];
334
Chris Lattner3bad2532006-12-20 06:21:33 +0000335 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner36c99522009-11-02 03:21:36 +0000336 // Undef values remain undefined.
337 if (!isa<UndefValue>(V))
Chris Lattnerb59673e2007-02-02 20:38:30 +0000338 LV.markConstant(C); // Constants are constant
Chris Lattner2a88bb72002-08-30 23:39:00 +0000339 }
Chris Lattner36c99522009-11-02 03:21:36 +0000340
Chris Lattner2f096252009-11-02 02:33:50 +0000341 // All others are underdefined by default.
Chris Lattner36c99522009-11-02 03:21:36 +0000342 return LV;
Chris Lattner138a1242001-06-27 23:38:11 +0000343 }
344
Chris Lattner2a0433b2009-11-02 05:55:40 +0000345 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
346 /// work list if it is not already executable.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000347 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
348 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
349 return; // This edge is already known to be executable!
350
351 if (BBExecutable.count(Dest)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000352 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
353 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000354
355 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000356 // feasible that wasn't before. Revisit the PHI nodes in the block
357 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000358 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
359 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000360
361 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000362 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000363 }
Chris Lattner138a1242001-06-27 23:38:11 +0000364 }
365
Chris Lattner82bec2c2004-11-15 04:44:20 +0000366 // getFeasibleSuccessors - Return a vector of booleans to indicate which
367 // successors are reachable from a given terminator instruction.
368 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000369 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000370
371 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000372 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000373 //
374 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
375
376 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000377 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000378 // information, we need to update the specified user of this instruction.
379 //
380 void OperandChangedState(User *U) {
381 // Only instructions use other variable values!
382 Instruction &I = cast<Instruction>(*U);
383 if (BBExecutable.count(I.getParent())) // Inst is executable?
384 visit(I);
385 }
386
387private:
388 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000389
Chris Lattner2f096252009-11-02 02:33:50 +0000390 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000391 // operand made a transition, or the instruction is newly executable. Change
392 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000393 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000394
395 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000396 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000397 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000398
Chris Lattnerb8047602002-08-14 17:53:45 +0000399 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000400 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000401 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000402 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000403 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000404 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000405 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000406 void visitExtractValueInst(ExtractValueInst &EVI);
407 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000408
Chris Lattner2f096252009-11-02 02:33:50 +0000409 // Instructions that cannot be folded away.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000410 void visitStoreInst (StoreInst &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000411 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000412 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000413 void visitCallInst (CallInst &I) {
414 if (isFreeCall(&I))
415 return;
Chris Lattner32c0d222009-09-27 21:35:11 +0000416 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000417 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000418 void visitInvokeInst (InvokeInst &II) {
419 visitCallSite(CallSite::get(&II));
420 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000421 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000422 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000423 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000424 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000425 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000426 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
427 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000428
Chris Lattner7e708292002-06-25 16:13:24 +0000429 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000430 // If a new instruction is added to LLVM that we don't handle.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000431 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000432 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000433 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000434};
Chris Lattnerf6293092002-07-23 18:06:35 +0000435
Duncan Sandse2abf122007-07-20 08:56:21 +0000436} // end anonymous namespace
437
438
Chris Lattnerb9a66342002-05-02 21:44:00 +0000439// getFeasibleSuccessors - Return a vector of booleans to indicate which
440// successors are reachable from a given terminator instruction.
441//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000442void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000443 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000444 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000445 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000446 if (BI->isUnconditional()) {
447 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000448 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000449 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000450
Chris Lattner2a0433b2009-11-02 05:55:40 +0000451 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000452 ConstantInt *CI = BCValue.getConstantInt();
453 if (CI == 0) {
Chris Lattnerea0db072009-11-02 02:30:06 +0000454 // Overdefined condition variables, and branches on unfoldable constant
455 // conditions, mean the branch could go either way.
Chris Lattner36c99522009-11-02 03:21:36 +0000456 if (!BCValue.isUndefined())
457 Succs[0] = Succs[1] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000458 return;
459 }
460
461 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000462 Succs[CI->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000463 return;
464 }
465
Chris Lattner36c99522009-11-02 03:21:36 +0000466 if (isa<InvokeInst>(TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000467 // Invoke instructions successors are always executable.
468 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000469 return;
470 }
471
472 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000473 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000474 ConstantInt *CI = SCValue.getConstantInt();
475
476 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerb9a66342002-05-02 21:44:00 +0000477 // All destinations are executable!
Chris Lattner36c99522009-11-02 03:21:36 +0000478 if (!SCValue.isUndefined())
479 Succs.assign(TI.getNumSuccessors(), true);
480 return;
481 }
482
483 Succs[SI->findCaseValue(CI)] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000484 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000485 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000486
487 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
488 if (isa<IndirectBrInst>(&TI)) {
489 // Just mark all destinations executable!
490 Succs.assign(TI.getNumSuccessors(), true);
491 return;
492 }
493
494#ifndef NDEBUG
495 errs() << "Unknown terminator instruction: " << TI << '\n';
496#endif
497 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000498}
499
500
Chris Lattner59f0ce22002-05-02 21:18:01 +0000501// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000502// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000503//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000504bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000505 assert(BBExecutable.count(To) && "Dest should always be alive!");
506
507 // Make sure the source basic block is executable!!
508 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000509
Chris Lattner2f096252009-11-02 02:33:50 +0000510 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000511 TerminatorInst *TI = From->getTerminator();
512 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
513 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000514 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000515
Chris Lattner2a0433b2009-11-02 05:55:40 +0000516 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000517
Chris Lattnerea0db072009-11-02 02:30:06 +0000518 // Overdefined condition variables mean the branch could go either way,
519 // undef conditions mean that neither edge is feasible yet.
Chris Lattner36c99522009-11-02 03:21:36 +0000520 ConstantInt *CI = BCValue.getConstantInt();
521 if (CI == 0)
522 return !BCValue.isUndefined();
Chris Lattnerea0db072009-11-02 02:30:06 +0000523
Chris Lattnerea0db072009-11-02 02:30:06 +0000524 // Constant condition variables mean the branch can only go a single way.
Chris Lattner36c99522009-11-02 03:21:36 +0000525 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000526 }
527
528 // Invoke instructions successors are always executable.
529 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000530 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000531
532 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000533 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner36c99522009-11-02 03:21:36 +0000534 ConstantInt *CI = SCValue.getConstantInt();
535
536 if (CI == 0)
537 return !SCValue.isUndefined();
Chris Lattner84831642004-01-12 17:40:36 +0000538
Chris Lattner36c99522009-11-02 03:21:36 +0000539 // Make sure to skip the "default value" which isn't a value
540 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
541 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
542 return SI->getSuccessor(i) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000543
Chris Lattner36c99522009-11-02 03:21:36 +0000544 // If the constant value is not equal to any of the branches, we must
545 // execute default branch.
546 return SI->getDefaultDest() == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000547 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000548
549 // Just mark all destinations executable!
550 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
551 if (isa<IndirectBrInst>(&TI))
552 return true;
553
554#ifndef NDEBUG
555 errs() << "Unknown terminator instruction: " << *TI << '\n';
556#endif
557 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000558}
Chris Lattner138a1242001-06-27 23:38:11 +0000559
Chris Lattner2f096252009-11-02 02:33:50 +0000560// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000561// operand made a transition, or the instruction is newly executable. Change
562// the value type of I to reflect these changes if appropriate. This method
563// makes sure to do the following actions:
564//
565// 1. If a phi node merges two constants in, and has conflicting value coming
566// from different branches, or if the PHI node merges in an overdefined
567// value, then the PHI node becomes overdefined.
568// 2. If a phi node merges only constants in, and they all agree on value, the
569// PHI node becomes a constant value equal to that.
570// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
571// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
572// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
573// 6. If a conditional branch has a value that is constant, make the selected
574// destination executable
575// 7. If a conditional branch has a value that is overdefined, make all
576// successors executable.
577//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000578void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000579 if (getValueState(&PN).isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000580 // There may be instructions using this PHI node that are not overdefined
581 // themselves. If so, make sure that they know that the PHI node operand
582 // changed.
583 std::multimap<PHINode*, Instruction*>::iterator I, E;
584 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000585 if (I == E)
586 return;
587
588 SmallVector<Instruction*, 16> Users;
589 for (; I != E; ++I)
590 Users.push_back(I->second);
591 while (!Users.empty())
592 visit(Users.pop_back_val());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000593 return; // Quick exit
594 }
Chris Lattner138a1242001-06-27 23:38:11 +0000595
Chris Lattnera2f652d2004-03-16 19:49:59 +0000596 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
597 // and slow us down a lot. Just mark them overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000598 if (PN.getNumIncomingValues() > 64)
Chris Lattner2a0433b2009-11-02 05:55:40 +0000599 return markOverdefined(&PN);
Chris Lattnera2f652d2004-03-16 19:49:59 +0000600
Chris Lattner2a632552002-04-18 15:13:15 +0000601 // Look at all of the executable operands of the PHI node. If any of them
602 // are overdefined, the PHI becomes overdefined as well. If they are all
603 // constant, and they agree with each other, the PHI becomes the identical
604 // constant. If they are constant and don't agree, the PHI is overdefined.
605 // If there are no executable operands, the PHI remains undefined.
606 //
Chris Lattner9de28282003-04-25 02:50:03 +0000607 Constant *OperandVal = 0;
608 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000609 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000610 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000611
Chris Lattner38871e42009-11-02 03:03:42 +0000612 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
613 continue;
614
615 if (IV.isOverdefined()) // PHI node becomes overdefined!
616 return markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000617
Chris Lattner38871e42009-11-02 03:03:42 +0000618 if (OperandVal == 0) { // Grab the first value.
619 OperandVal = IV.getConstant();
620 continue;
Chris Lattner138a1242001-06-27 23:38:11 +0000621 }
Chris Lattner38871e42009-11-02 03:03:42 +0000622
623 // There is already a reachable operand. If we conflict with it,
624 // then the PHI node becomes overdefined. If we agree with it, we
625 // can continue on.
626
627 // Check to see if there are two different constants merging, if so, the PHI
628 // node is overdefined.
629 if (IV.getConstant() != OperandVal)
630 return markOverdefined(&PN);
Chris Lattner138a1242001-06-27 23:38:11 +0000631 }
632
Chris Lattner2a632552002-04-18 15:13:15 +0000633 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000634 // arguments that agree with each other(and OperandVal is the constant) or
635 // OperandVal is null because there are no defined incoming arguments. If
636 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000637 //
Chris Lattner9de28282003-04-25 02:50:03 +0000638 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000639 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000640}
641
Chris Lattner59acc7d2004-12-10 08:02:06 +0000642void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000643 if (I.getNumOperands() == 0) return; // ret void
Chris Lattner59acc7d2004-12-10 08:02:06 +0000644
Chris Lattner59acc7d2004-12-10 08:02:06 +0000645 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000646 // If we are tracking the return value of this function, merge it in.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000647 if (!F->hasLocalLinkage())
Devang Patel7c490d42008-03-11 05:46:42 +0000648 return;
649
Chris Lattner2a0433b2009-11-02 05:55:40 +0000650 if (!TrackedRetVals.empty()) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000651 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000652 TrackedRetVals.find(F);
653 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000654 !TFRVI->second.isOverdefined()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000655 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Patel7c490d42008-03-11 05:46:42 +0000656 return;
657 }
658 }
659
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000660 // Handle functions that return multiple values.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000661 if (0 && !TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000662 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000663 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000664 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
665 if (It == TrackedMultipleRetVals.end()) break;
666 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000667 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000668 } else if (!TrackedMultipleRetVals.empty() &&
Chris Lattner2a0433b2009-11-02 05:55:40 +0000669 /*I.getNumOperands() == 1 &&*/
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000670 isa<StructType>(I.getOperand(0)->getType())) {
671 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
672 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000673 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000674 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
675 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000676 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000677 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000678 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000679 }
680}
681
Chris Lattner82bec2c2004-11-15 04:44:20 +0000682void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000683 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000684 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000685
Chris Lattner16b18fd2003-10-08 16:55:34 +0000686 BasicBlock *BB = TI.getParent();
687
Chris Lattner2f096252009-11-02 02:33:50 +0000688 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000689 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000690 if (SuccFeasible[i])
691 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000692}
693
Chris Lattner82bec2c2004-11-15 04:44:20 +0000694void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000695 LatticeVal OpSt = getValueState(I.getOperand(0));
696 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000697 markOverdefined(&I);
Chris Lattner2a0433b2009-11-02 05:55:40 +0000698 else if (OpSt.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000699 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner2a0433b2009-11-02 05:55:40 +0000700 OpSt.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000701}
702
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000703void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000704 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000705
Dan Gohman60ea2682008-06-20 16:41:17 +0000706 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000707 if (isa<UndefValue>(Aggr))
708 return;
709
710 // Currently only handle single-index extractvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000711 if (EVI.getNumIndices() != 1)
712 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000713
714 Function *F = 0;
715 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
716 F = CI->getCalledFunction();
717 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
718 F = II->getCalledFunction();
719
720 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
721 // result back!
Chris Lattner38871e42009-11-02 03:03:42 +0000722 if (F == 0 || TrackedMultipleRetVals.empty())
723 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000724
Chris Lattnercf712de2008-08-23 23:36:38 +0000725 // See if we are tracking the result of the callee. If not tracking this
726 // function (for example, it is a declaration) just move to overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +0000727 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
728 return markOverdefined(&EVI);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000729
730 // Otherwise, the value will be merged in here as a result of CallSite
731 // handling.
732}
733
734void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000735 Value *Aggr = IVI.getAggregateOperand();
736 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000737
Dan Gohman60ea2682008-06-20 16:41:17 +0000738 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000739 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000740 return;
741
742 // Currently only handle single-index insertvalues.
Chris Lattner38871e42009-11-02 03:03:42 +0000743 if (IVI.getNumIndices() != 1)
744 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000745
746 // Currently only handle insertvalue instructions that are in a single-use
747 // chain that builds up a return value.
748 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattner38871e42009-11-02 03:03:42 +0000749 if (!TmpIVI->hasOneUse())
750 return markOverdefined(&IVI);
751
Dan Gohmandfaceb42008-06-20 16:39:44 +0000752 const Value *V = *TmpIVI->use_begin();
753 if (isa<ReturnInst>(V))
754 break;
755 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattner38871e42009-11-02 03:03:42 +0000756 if (!TmpIVI)
757 return markOverdefined(&IVI);
Dan Gohmandfaceb42008-06-20 16:39:44 +0000758 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000759
760 // See if we are tracking the result of the callee.
761 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000762 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000763 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
764
765 // Merge in the inserted member value.
766 if (It != TrackedMultipleRetVals.end())
767 mergeInValue(It->second, F, getValueState(Val));
768
Dan Gohman60ea2682008-06-20 16:41:17 +0000769 // Mark the aggregate result of the IVI overdefined; any tracking that we do
770 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000771 markOverdefined(&IVI);
772}
773
Chris Lattner82bec2c2004-11-15 04:44:20 +0000774void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000775 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000776 if (CondValue.isUndefined())
777 return;
Chris Lattner36c99522009-11-02 03:21:36 +0000778
779 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000780 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
781 mergeInValue(&I, getValueState(OpVal));
Chris Lattner36c99522009-11-02 03:21:36 +0000782 return;
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000783 }
784
785 // Otherwise, the condition is overdefined or a constant we can't evaluate.
786 // See if we can produce something better than overdefined based on the T/F
787 // value.
Chris Lattner2a0433b2009-11-02 05:55:40 +0000788 LatticeVal TVal = getValueState(I.getTrueValue());
789 LatticeVal FVal = getValueState(I.getFalseValue());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000790
791 // select ?, C, C -> C.
792 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner38871e42009-11-02 03:03:42 +0000793 TVal.getConstant() == FVal.getConstant())
794 return markConstant(&I, FVal.getConstant());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000795
Chris Lattner2a0433b2009-11-02 05:55:40 +0000796 if (TVal.isUndefined()) // select ?, undef, X -> X.
797 return mergeInValue(&I, FVal);
798 if (FVal.isUndefined()) // select ?, X, undef -> X.
799 return mergeInValue(&I, TVal);
800 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000801}
802
Chris Lattner2a0433b2009-11-02 05:55:40 +0000803// Handle Binary Operators.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000804void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000805 LatticeVal V1State = getValueState(I.getOperand(0));
806 LatticeVal V2State = getValueState(I.getOperand(1));
807
Chris Lattneref36dfd2004-11-15 05:03:30 +0000808 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000809 if (IV.isOverdefined()) return;
810
Chris Lattner2a0433b2009-11-02 05:55:40 +0000811 if (V1State.isConstant() && V2State.isConstant())
812 return markConstant(IV, &I,
813 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
814 V2State.getConstant()));
815
816 // If something is undef, wait for it to resolve.
817 if (!V1State.isOverdefined() && !V2State.isOverdefined())
818 return;
819
820 // Otherwise, one of our operands is overdefined. Try to produce something
821 // better than overdefined with some tricks.
822
823 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
824 // operand is overdefined.
825 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
826 LatticeVal *NonOverdefVal = 0;
827 if (!V1State.isOverdefined())
828 NonOverdefVal = &V1State;
829 else if (!V2State.isOverdefined())
830 NonOverdefVal = &V2State;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000831
Chris Lattner2a0433b2009-11-02 05:55:40 +0000832 if (NonOverdefVal) {
833 if (NonOverdefVal->isUndefined()) {
834 // Could annihilate value.
835 if (I.getOpcode() == Instruction::And)
836 markConstant(IV, &I, Constant::getNullValue(I.getType()));
837 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
838 markConstant(IV, &I, Constant::getAllOnesValue(PT));
839 else
840 markConstant(IV, &I,
841 Constant::getAllOnesValue(I.getType()));
842 return;
Chris Lattnera177c672004-12-11 23:15:19 +0000843 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000844
845 if (I.getOpcode() == Instruction::And) {
846 // X and 0 = 0
847 if (NonOverdefVal->getConstant()->isNullValue())
848 return markConstant(IV, &I, NonOverdefVal->getConstant());
849 } else {
850 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
851 if (CI->isAllOnesValue()) // X or -1 = -1
852 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnera177c672004-12-11 23:15:19 +0000853 }
854 }
Chris Lattner2a0433b2009-11-02 05:55:40 +0000855 }
Chris Lattnera177c672004-12-11 23:15:19 +0000856
857
Chris Lattner2a0433b2009-11-02 05:55:40 +0000858 // If both operands are PHI nodes, it is possible that this instruction has
859 // a constant value, despite the fact that the PHI node doesn't. Check for
860 // this condition now.
861 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
862 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
863 if (PN1->getParent() == PN2->getParent()) {
864 // Since the two PHI nodes are in the same basic block, they must have
865 // entries for the same predecessors. Walk the predecessor list, and
866 // if all of the incoming values are constants, and the result of
867 // evaluating this expression with all incoming value pairs is the
868 // same, then this expression is a constant even though the PHI node
869 // is not a constant!
870 LatticeVal Result;
871 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
872 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
873 BasicBlock *InBlock = PN1->getIncomingBlock(i);
874 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000875
Chris Lattner2a0433b2009-11-02 05:55:40 +0000876 if (In1.isOverdefined() || In2.isOverdefined()) {
877 Result.markOverdefined();
878 break; // Cannot fold this operation over the PHI nodes!
879 }
880
881 if (In1.isConstant() && In2.isConstant()) {
882 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
883 In2.getConstant());
884 if (Result.isUndefined())
885 Result.markConstant(V);
886 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000887 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000888 break;
Chris Lattner38871e42009-11-02 03:03:42 +0000889 }
Chris Lattner1daee8b2004-01-12 03:57:30 +0000890 }
891 }
892
Chris Lattner2a0433b2009-11-02 05:55:40 +0000893 // If we found a constant value here, then we know the instruction is
894 // constant despite the fact that the PHI nodes are overdefined.
895 if (Result.isConstant()) {
896 markConstant(IV, &I, Result.getConstant());
897 // Remember that this instruction is virtually using the PHI node
898 // operands.
899 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
900 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
901 return;
902 }
903
904 if (Result.isUndefined())
905 return;
906
907 // Okay, this really is overdefined now. Since we might have
908 // speculatively thought that this was not overdefined before, and
909 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
910 // make sure to clean out any entries that we put there, for
911 // efficiency.
912 UsersOfOverdefinedPHIs.erase(PN1);
913 UsersOfOverdefinedPHIs.erase(PN2);
914 }
915
916 markOverdefined(&I);
Chris Lattner2a632552002-04-18 15:13:15 +0000917}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000918
Chris Lattner2f096252009-11-02 02:33:50 +0000919// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000920void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +0000921 LatticeVal V1State = getValueState(I.getOperand(0));
922 LatticeVal V2State = getValueState(I.getOperand(1));
923
Reid Spencere4d87aa2006-12-23 06:05:41 +0000924 LatticeVal &IV = ValueState[&I];
925 if (IV.isOverdefined()) return;
926
Chris Lattner2a0433b2009-11-02 05:55:40 +0000927 if (V1State.isConstant() && V2State.isConstant())
928 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
929 V1State.getConstant(),
930 V2State.getConstant()));
931
932 // If operands are still undefined, wait for it to resolve.
933 if (!V1State.isOverdefined() && !V2State.isOverdefined())
934 return;
935
936 // If something is overdefined, use some tricks to avoid ending up and over
937 // defined if we can.
938
939 // If both operands are PHI nodes, it is possible that this instruction has
940 // a constant value, despite the fact that the PHI node doesn't. Check for
941 // this condition now.
942 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
943 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
944 if (PN1->getParent() == PN2->getParent()) {
945 // Since the two PHI nodes are in the same basic block, they must have
946 // entries for the same predecessors. Walk the predecessor list, and
947 // if all of the incoming values are constants, and the result of
948 // evaluating this expression with all incoming value pairs is the
949 // same, then this expression is a constant even though the PHI node
950 // is not a constant!
951 LatticeVal Result;
952 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
953 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
954 BasicBlock *InBlock = PN1->getIncomingBlock(i);
955 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000956
Chris Lattner2a0433b2009-11-02 05:55:40 +0000957 if (In1.isOverdefined() || In2.isOverdefined()) {
958 Result.markOverdefined();
959 break; // Cannot fold this operation over the PHI nodes!
960 }
961
962 if (In1.isConstant() && In2.isConstant()) {
963 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
964 In1.getConstant(),
965 In2.getConstant());
966 if (Result.isUndefined())
967 Result.markConstant(V);
968 else if (Result.isConstant() && Result.getConstant() != V) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000969 Result.markOverdefined();
Chris Lattner2a0433b2009-11-02 05:55:40 +0000970 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +0000971 }
972 }
Reid Spencere4d87aa2006-12-23 06:05:41 +0000973 }
974
Chris Lattner2a0433b2009-11-02 05:55:40 +0000975 // If we found a constant value here, then we know the instruction is
976 // constant despite the fact that the PHI nodes are overdefined.
977 if (Result.isConstant()) {
978 markConstant(&I, Result.getConstant());
979 // Remember that this instruction is virtually using the PHI node
980 // operands.
981 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
982 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
983 return;
984 }
985
986 if (Result.isUndefined())
987 return;
988
989 // Okay, this really is overdefined now. Since we might have
990 // speculatively thought that this was not overdefined before, and
991 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
992 // make sure to clean out any entries that we put there, for
993 // efficiency.
994 UsersOfOverdefinedPHIs.erase(PN1);
995 UsersOfOverdefinedPHIs.erase(PN2);
996 }
997
998 markOverdefined(&I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000999}
1000
Robert Bocchino56107e22006-01-10 19:05:05 +00001001void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001002 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001003 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001004
1005#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001006 LatticeVal &ValState = getValueState(I.getOperand(0));
1007 LatticeVal &IdxState = getValueState(I.getOperand(1));
1008
1009 if (ValState.isOverdefined() || IdxState.isOverdefined())
1010 markOverdefined(&I);
1011 else if(ValState.isConstant() && IdxState.isConstant())
1012 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1013 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001014#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001015}
1016
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001017void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001018 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001019 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001020#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001021 LatticeVal &ValState = getValueState(I.getOperand(0));
1022 LatticeVal &EltState = getValueState(I.getOperand(1));
1023 LatticeVal &IdxState = getValueState(I.getOperand(2));
1024
1025 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1026 IdxState.isOverdefined())
1027 markOverdefined(&I);
1028 else if(ValState.isConstant() && EltState.isConstant() &&
1029 IdxState.isConstant())
1030 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1031 EltState.getConstant(),
1032 IdxState.getConstant()));
1033 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001034 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001035 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1036 EltState.getConstant(),
1037 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001038#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001039}
1040
Chris Lattner543abdf2006-04-08 01:19:12 +00001041void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001042 // FIXME : SCCP does not handle vectors properly.
Chris Lattner38871e42009-11-02 03:03:42 +00001043 return markOverdefined(&I);
Devang Patel67a821d2006-12-04 23:54:59 +00001044#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001045 LatticeVal &V1State = getValueState(I.getOperand(0));
1046 LatticeVal &V2State = getValueState(I.getOperand(1));
1047 LatticeVal &MaskState = getValueState(I.getOperand(2));
1048
1049 if (MaskState.isUndefined() ||
1050 (V1State.isUndefined() && V2State.isUndefined()))
1051 return; // Undefined output if mask or both inputs undefined.
1052
1053 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1054 MaskState.isOverdefined()) {
1055 markOverdefined(&I);
1056 } else {
1057 // A mix of constant/undef inputs.
1058 Constant *V1 = V1State.isConstant() ?
1059 V1State.getConstant() : UndefValue::get(I.getType());
1060 Constant *V2 = V2State.isConstant() ?
1061 V2State.getConstant() : UndefValue::get(I.getType());
1062 Constant *Mask = MaskState.isConstant() ?
1063 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1064 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1065 }
Devang Patel67a821d2006-12-04 23:54:59 +00001066#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001067}
1068
Chris Lattner2f096252009-11-02 02:33:50 +00001069// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001070// can turn this into a getelementptr ConstantExpr.
1071//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001072void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001073 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001074 if (IV.isOverdefined()) return;
1075
Chris Lattnere777ff22007-02-02 20:51:48 +00001076 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001077 Operands.reserve(I.getNumOperands());
1078
1079 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001080 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001081 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001082 return; // Operands are not resolved yet.
1083
Chris Lattner38871e42009-11-02 03:03:42 +00001084 if (State.isOverdefined())
1085 return markOverdefined(IV, &I);
1086
Chris Lattner2a88bb72002-08-30 23:39:00 +00001087 assert(State.isConstant() && "Unknown state!");
1088 Operands.push_back(State.getConstant());
1089 }
1090
1091 Constant *Ptr = Operands[0];
Chris Lattner2a0433b2009-11-02 05:55:40 +00001092 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1093 Operands.size()-1));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001094}
Brian Gaeked0fde302003-11-11 22:41:34 +00001095
Chris Lattner2a0433b2009-11-02 05:55:40 +00001096void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001097 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1098 return;
Chris Lattner2a0433b2009-11-02 05:55:40 +00001099
Chris Lattnerdd336d12004-12-11 05:15:59 +00001100 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001101 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001102 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1103
Chris Lattner2a0433b2009-11-02 05:55:40 +00001104 // Get the value we are storing into the global, then merge it.
1105 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattnerdd336d12004-12-11 05:15:59 +00001106 if (I->second.isOverdefined())
1107 TrackedGlobals.erase(I); // No need to keep tracking this!
1108}
1109
1110
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001111// Handle load instructions. If the operand is a constant pointer to a constant
1112// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001113void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001114 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner5638dc62009-11-02 06:06:14 +00001115 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner2a0433b2009-11-02 05:55:40 +00001116
Chris Lattneref36dfd2004-11-15 05:03:30 +00001117 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001118 if (IV.isOverdefined()) return;
1119
Chris Lattner2a0433b2009-11-02 05:55:40 +00001120 if (!PtrVal.isConstant() || I.isVolatile())
1121 return markOverdefined(IV, &I);
1122
Chris Lattner5638dc62009-11-02 06:06:14 +00001123 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanfd939082005-04-21 23:48:37 +00001124
Chris Lattner2a0433b2009-11-02 05:55:40 +00001125 // load null -> null
1126 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1127 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1128
1129 // Transform load (constant global) into the value loaded.
1130 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001131 if (!TrackedGlobals.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001132 // If we are tracking this global, merge in the known value for it.
1133 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1134 TrackedGlobals.find(GV);
1135 if (It != TrackedGlobals.end()) {
1136 mergeInValue(IV, &I, It->second);
1137 return;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001138 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001139 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001140 }
1141
Chris Lattner5638dc62009-11-02 06:06:14 +00001142 // Transform load from a constant into a constant if possible.
1143 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1144 return markConstant(IV, &I, C);
Chris Lattner2a0433b2009-11-02 05:55:40 +00001145
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001146 // Otherwise we cannot say for certain what value this load will produce.
1147 // Bail out.
1148 markOverdefined(IV, &I);
1149}
Chris Lattner58b7b082004-04-13 19:43:54 +00001150
Chris Lattner59acc7d2004-12-10 08:02:06 +00001151void SCCPSolver::visitCallSite(CallSite CS) {
1152 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001153 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001154
1155 // The common case is that we aren't tracking the callee, either because we
1156 // are not doing interprocedural analysis or the callee is indirect, or is
1157 // external. Handle these cases first.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001158 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001159CallOverdefined:
1160 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001161 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001162
1163 // Otherwise, if we have a single return value case, and if the function is
1164 // a declaration, maybe we can constant fold it.
1165 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1166 canConstantFoldCallTo(F)) {
1167
1168 SmallVector<Constant*, 8> Operands;
1169 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1170 AI != E; ++AI) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001171 LatticeVal State = getValueState(*AI);
Chris Lattner38871e42009-11-02 03:03:42 +00001172
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001173 if (State.isUndefined())
1174 return; // Operands are not resolved yet.
Chris Lattner38871e42009-11-02 03:03:42 +00001175 if (State.isOverdefined())
1176 return markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001177 assert(State.isConstant() && "Unknown state!");
1178 Operands.push_back(State.getConstant());
1179 }
1180
1181 // If we can constant fold this, mark the result of the call as a
1182 // constant.
Chris Lattner38871e42009-11-02 03:03:42 +00001183 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1184 return markConstant(I, C);
Chris Lattner58b7b082004-04-13 19:43:54 +00001185 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001186
1187 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner38871e42009-11-02 03:03:42 +00001188 return markOverdefined(I);
Chris Lattner58b7b082004-04-13 19:43:54 +00001189 }
1190
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001191 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001192 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1193 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001194 // If so, propagate the return value of the callee into this call result.
1195 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001196 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001197 // Check to see if we're tracking this callee, if not, handle it in the
1198 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001199 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1200 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001201 if (TMRVI == TrackedMultipleRetVals.end())
1202 goto CallOverdefined;
Torok Edwin2b6183d2009-10-20 15:15:09 +00001203
1204 // Need to mark as overdefined, otherwise it stays undefined which
1205 // creates extractvalue undef, <idx>
1206 markOverdefined(I);
Chris Lattner38871e42009-11-02 03:03:42 +00001207
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001208 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001209 // into this call site. We do this by walking all the uses. Single-index
1210 // ExtractValueInst uses can be tracked; anything more complicated is
1211 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001212 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1213 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001214 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1215 if (EVI->getNumIndices() == 1) {
1216 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001217 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001218 continue;
1219 }
1220 }
1221 // The aggregate value is used in a way not handled here. Assume nothing.
1222 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001223 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001224 } else {
1225 // Otherwise we're not tracking this callee, so handle it in the
1226 // common path above.
1227 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001228 }
1229
1230 // Finally, if this is the first call to the function hit, mark its entry
1231 // block executable.
1232 if (!BBExecutable.count(F->begin()))
1233 MarkBlockExecutable(F->begin());
1234
1235 // Propagate information from this call site into the callee.
1236 CallSite::arg_iterator CAI = CS.arg_begin();
1237 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1238 AI != E; ++AI, ++CAI) {
Torok Edwinc3384992009-09-24 18:33:42 +00001239 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001240 markOverdefined(AI);
Torok Edwin30a94e32009-09-24 09:47:18 +00001241 continue;
1242 }
Chris Lattner2a0433b2009-11-02 05:55:40 +00001243
1244 mergeInValue(AI, getValueState(*CAI));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001245 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001246}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001247
Chris Lattner82bec2c2004-11-15 04:44:20 +00001248void SCCPSolver::Solve() {
1249 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001250 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001251 !OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001252 // Process the overdefined instruction's work list first, which drives other
1253 // things to overdefined more quickly.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001254 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001255 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001256
Dan Gohman87325772009-08-17 15:25:05 +00001257 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001258
Chris Lattner82bec2c2004-11-15 04:44:20 +00001259 // "I" got into the work list because it either made the transition from
1260 // bottom to constant
1261 //
1262 // Anything on this worklist that is overdefined need not be visited
1263 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001264 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001265 //
1266 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1267 UI != E; ++UI)
1268 OperandChangedState(*UI);
1269 }
Chris Lattner2f096252009-11-02 02:33:50 +00001270
1271 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001272 while (!InstWorkList.empty()) {
Chris Lattner2a0433b2009-11-02 05:55:40 +00001273 Value *I = InstWorkList.pop_back_val();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001274
Dan Gohman87325772009-08-17 15:25:05 +00001275 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001276
Chris Lattner2a0433b2009-11-02 05:55:40 +00001277 // "I" got into the work list because it made the transition from undef to
1278 // constant.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001279 //
1280 // Anything on this worklist that is overdefined need not be visited
1281 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001282 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001283 //
1284 if (!getValueState(I).isOverdefined())
1285 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1286 UI != E; ++UI)
1287 OperandChangedState(*UI);
1288 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001289
Chris Lattner2f096252009-11-02 02:33:50 +00001290 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001291 while (!BBWorkList.empty()) {
1292 BasicBlock *BB = BBWorkList.back();
1293 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001294
Dan Gohman87325772009-08-17 15:25:05 +00001295 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001296
Chris Lattner82bec2c2004-11-15 04:44:20 +00001297 // Notify all instructions in this basic block that they are newly
1298 // executable.
1299 visit(BB);
1300 }
1301 }
1302}
1303
Chris Lattner3bad2532006-12-20 06:21:33 +00001304/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001305/// that branches on undef values cannot reach any of their successors.
1306/// However, this is not a safe assumption. After we solve dataflow, this
1307/// method should be use to handle this. If this returns true, the solver
1308/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001309///
1310/// This method handles this by finding an unresolved branch and marking it one
1311/// of the edges from the block as being feasible, even though the condition
1312/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1313/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001314/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001315/// constraints on the condition of the branch, as that would impact other users
1316/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001317///
1318/// This scan also checks for values that use undefs, whose results are actually
1319/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1320/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1321/// even if X isn't defined.
1322bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001323 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1324 if (!BBExecutable.count(BB))
1325 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001326
1327 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1328 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001329 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001330
1331 LatticeVal &LV = getValueState(I);
1332 if (!LV.isUndefined()) continue;
1333
1334 // Get the lattice values of the first two operands for use below.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001335 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner3bad2532006-12-20 06:21:33 +00001336 LatticeVal Op1LV;
1337 if (I->getNumOperands() == 2) {
1338 // If this is a two-operand instruction, and if both operands are
1339 // undefs, the result stays undef.
1340 Op1LV = getValueState(I->getOperand(1));
1341 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1342 continue;
1343 }
1344
1345 // If this is an instructions whose result is defined even if the input is
1346 // not fully defined, propagate the information.
1347 const Type *ITy = I->getType();
1348 switch (I->getOpcode()) {
1349 default: break; // Leave the instruction as an undef.
1350 case Instruction::ZExt:
1351 // After a zero extend, we know the top part is zero. SExt doesn't have
1352 // to be handled here, because we don't know whether the top part is 1's
1353 // or 0's.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001354 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001355 return true;
1356 case Instruction::Mul:
1357 case Instruction::And:
1358 // undef * X -> 0. X could be zero.
1359 // undef & X -> 0. X could be zero.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001360 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001361 return true;
1362
1363 case Instruction::Or:
1364 // undef | X -> -1. X could be -1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001365 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001366 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001367
1368 case Instruction::SDiv:
1369 case Instruction::UDiv:
1370 case Instruction::SRem:
1371 case Instruction::URem:
1372 // X / undef -> undef. No change.
1373 // X % undef -> undef. No change.
1374 if (Op1LV.isUndefined()) break;
1375
1376 // undef / X -> 0. X could be maxint.
1377 // undef % X -> 0. X could be 1.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001378 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001379 return true;
1380
1381 case Instruction::AShr:
1382 // undef >>s X -> undef. No change.
1383 if (Op0LV.isUndefined()) break;
1384
1385 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1386 if (Op0LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001387 markForcedConstant(I, Op0LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001388 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001389 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001390 return true;
1391 case Instruction::LShr:
1392 case Instruction::Shl:
1393 // undef >> X -> undef. No change.
1394 // undef << X -> undef. No change.
1395 if (Op0LV.isUndefined()) break;
1396
1397 // X >> undef -> 0. X could be 0.
1398 // X << undef -> 0. X could be 0.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001399 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001400 return true;
1401 case Instruction::Select:
1402 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1403 if (Op0LV.isUndefined()) {
1404 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1405 Op1LV = getValueState(I->getOperand(2));
1406 } else if (Op1LV.isUndefined()) {
1407 // c ? undef : undef -> undef. No change.
1408 Op1LV = getValueState(I->getOperand(2));
1409 if (Op1LV.isUndefined())
1410 break;
1411 // Otherwise, c ? undef : x -> x.
1412 } else {
1413 // Leave Op1LV as Operand(1)'s LatticeValue.
1414 }
1415
1416 if (Op1LV.isConstant())
Chris Lattner2a0433b2009-11-02 05:55:40 +00001417 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner3bad2532006-12-20 06:21:33 +00001418 else
Chris Lattner2a0433b2009-11-02 05:55:40 +00001419 markOverdefined(I);
Chris Lattner3bad2532006-12-20 06:21:33 +00001420 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001421 case Instruction::Call:
1422 // If a call has an undef result, it is because it is constant foldable
1423 // but one of the inputs was undef. Just force the result to
1424 // overdefined.
Chris Lattner2a0433b2009-11-02 05:55:40 +00001425 markOverdefined(I);
Chris Lattner60301602008-05-24 03:59:33 +00001426 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001427 }
1428 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001429
1430 TerminatorInst *TI = BB->getTerminator();
1431 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1432 if (!BI->isConditional()) continue;
1433 if (!getValueState(BI->getCondition()).isUndefined())
1434 continue;
1435 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001436 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001437 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001438 if (!getValueState(SI->getCondition()).isUndefined())
1439 continue;
1440 } else {
1441 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001442 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001443
Chris Lattner05bb7892008-01-28 00:32:30 +00001444 // If the edge to the second successor isn't thought to be feasible yet,
1445 // mark it so now. We pick the second one so that this goes to some
1446 // enumerated value in a switch instead of going to the default destination.
1447 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001448 continue;
1449
1450 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1451 // and return. This will make other blocks reachable, which will allow new
1452 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001453 markEdgeExecutable(BB, TI->getSuccessor(1));
1454
1455 // This must be a conditional branch of switch on undef. At this point,
1456 // force the old terminator to branch to the first successor. This is
1457 // required because we are now influencing the dataflow of the function with
1458 // the assumption that this edge is taken. If we leave the branch condition
1459 // as undef, then further analysis could think the undef went another way
1460 // leading to an inconsistent set of conclusions.
1461 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001462 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001463 } else {
1464 SwitchInst *SI = cast<SwitchInst>(TI);
1465 SI->setCondition(SI->getCaseValue(1));
1466 }
1467
Chris Lattnerd2d86702006-10-22 05:59:17 +00001468 return true;
1469 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001470
Chris Lattnerd2d86702006-10-22 05:59:17 +00001471 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001472}
1473
Chris Lattner82bec2c2004-11-15 04:44:20 +00001474
1475namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001476 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001477 //
Chris Lattner14051812004-11-15 07:15:04 +00001478 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001479 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001480 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001481 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001482 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001483 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001484
Chris Lattner14051812004-11-15 07:15:04 +00001485 // runOnFunction - Run the Sparse Conditional Constant Propagation
1486 // algorithm, and return true if the function was modified.
1487 //
1488 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001489
Chris Lattner14051812004-11-15 07:15:04 +00001490 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1491 AU.setPreservesCFG();
1492 }
1493 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001494} // end anonymous namespace
1495
Dan Gohman844731a2008-05-13 00:00:25 +00001496char SCCP::ID = 0;
1497static RegisterPass<SCCP>
1498X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001499
Chris Lattner2f096252009-11-02 02:33:50 +00001500// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001501FunctionPass *llvm::createSCCPPass() {
1502 return new SCCP();
1503}
1504
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001505static void DeleteInstructionInBlock(BasicBlock *BB) {
1506 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1507 ++NumDeadBlocks;
1508
1509 // Delete the instructions backwards, as it has a reduced likelihood of
1510 // having to update as many def-use and use-def chains.
1511 while (!isa<TerminatorInst>(BB->begin())) {
1512 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1513
1514 if (!I->use_empty())
1515 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1516 BB->getInstList().erase(I);
1517 ++NumInstRemoved;
1518 }
1519}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001520
Chris Lattner82bec2c2004-11-15 04:44:20 +00001521// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1522// and return true if the function was modified.
1523//
1524bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001525 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner5638dc62009-11-02 06:06:14 +00001526 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001527
1528 // Mark the first block of the function as being executable.
1529 Solver.MarkBlockExecutable(F.begin());
1530
Chris Lattner7e529e42004-11-15 05:45:33 +00001531 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001532 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001533 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001534
Chris Lattner82bec2c2004-11-15 04:44:20 +00001535 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001536 bool ResolvedUndefs = true;
1537 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001538 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001539 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001540 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001541 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001542
Chris Lattner7e529e42004-11-15 05:45:33 +00001543 bool MadeChanges = false;
1544
1545 // If we decided that there are basic blocks that are dead in this function,
1546 // delete their contents now. Note that we cannot actually delete the blocks,
1547 // as we cannot modify the CFG of the function.
Chris Lattner57939df2007-03-04 04:50:21 +00001548
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001549 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001550 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001551 DeleteInstructionInBlock(BB);
1552 MadeChanges = true;
1553 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001554 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001555
1556 // Iterate over all of the instructions in a function, replacing them with
1557 // constants if we have found them to be of constant values.
1558 //
1559 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1560 Instruction *Inst = BI++;
1561 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1562 continue;
1563
Chris Lattner8db50122009-11-02 02:54:24 +00001564 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1565 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001566 continue;
1567
1568 Constant *Const = IV.isConstant()
1569 ? IV.getConstant() : UndefValue::get(Inst->getType());
1570 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1571
1572 // Replaces all of the uses of a variable with uses of the constant.
1573 Inst->replaceAllUsesWith(Const);
1574
1575 // Delete the instruction.
1576 Inst->eraseFromParent();
1577
1578 // Hey, we just changed something!
1579 MadeChanges = true;
1580 ++NumInstRemoved;
1581 }
1582 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001583
1584 return MadeChanges;
1585}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001586
1587namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001588 //===--------------------------------------------------------------------===//
1589 //
1590 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1591 /// Constant Propagation.
1592 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001593 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001594 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001595 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001596 bool runOnModule(Module &M);
1597 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001598} // end anonymous namespace
1599
Dan Gohman844731a2008-05-13 00:00:25 +00001600char IPSCCP::ID = 0;
1601static RegisterPass<IPSCCP>
1602Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1603
Chris Lattner2f096252009-11-02 02:33:50 +00001604// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001605ModulePass *llvm::createIPSCCPPass() {
1606 return new IPSCCP();
1607}
1608
1609
1610static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001611 // Delete any dead constantexpr klingons.
1612 GV->removeDeadConstantUsers();
1613
Chris Lattner59acc7d2004-12-10 08:02:06 +00001614 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1615 UI != E; ++UI)
1616 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001617 if (SI->getOperand(0) == GV || SI->isVolatile())
1618 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001619 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1620 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001621 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001622 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001623 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1624 if (LI->isVolatile())
1625 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001626 } else if (isa<BlockAddress>(*UI)) {
1627 // blockaddress doesn't take the address of the function, it takes addr
1628 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001629 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001630 return true;
1631 }
1632 return false;
1633}
1634
1635bool IPSCCP::runOnModule(Module &M) {
Chris Lattner5638dc62009-11-02 06:06:14 +00001636 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Chris Lattner59acc7d2004-12-10 08:02:06 +00001637
1638 // Loop over all functions, marking arguments to those with their addresses
1639 // taken or that are external as overdefined.
1640 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001641 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001642 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001643 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001644 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001645 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1646 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001647 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001648 } else {
1649 Solver.AddTrackedFunction(F);
1650 }
1651
Chris Lattnerdd336d12004-12-11 05:15:59 +00001652 // Loop over global variables. We inform the solver about any internal global
1653 // variables that do not have their 'addresses taken'. If they don't have
1654 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001655 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1656 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001657 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001658 Solver.TrackValueOfGlobalVariable(G);
1659
Chris Lattner59acc7d2004-12-10 08:02:06 +00001660 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001661 bool ResolvedUndefs = true;
1662 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001663 Solver.Solve();
1664
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001665 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001666 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001667 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001668 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001669 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001670
1671 bool MadeChanges = false;
1672
1673 // Iterate over all of the instructions in the module, replacing them with
1674 // constants if we have found them to be of constant values.
1675 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001676 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner1c1f1122007-02-02 21:15:06 +00001677
Chris Lattner59acc7d2004-12-10 08:02:06 +00001678 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner89112b62009-11-02 03:25:55 +00001679 if (Solver.isBlockExecutable(F->begin())) {
1680 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1681 AI != E; ++AI) {
1682 if (AI->use_empty()) continue;
1683
1684 LatticeVal IV = Solver.getLatticeValueFor(AI);
1685 if (IV.isOverdefined()) continue;
1686
1687 Constant *CST = IV.isConstant() ?
1688 IV.getConstant() : UndefValue::get(AI->getType());
1689 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1690
1691 // Replaces all of the uses of a variable with uses of the
1692 // constant.
1693 AI->replaceAllUsesWith(CST);
1694 ++IPNumArgsElimed;
1695 }
Chris Lattner8db50122009-11-02 02:54:24 +00001696 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001697
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001698 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001699 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001700 DeleteInstructionInBlock(BB);
1701 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001702
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001703 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001704 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1705 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001706 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001707 TI->getSuccessor(i)->removePredecessor(BB);
1708 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001709 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001710 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001711 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001712
Chris Lattner864737b2004-12-11 05:32:19 +00001713 if (&*BB != &F->front())
1714 BlocksToErase.push_back(BB);
1715 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001716 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001717 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001718 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001719
1720 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1721 Instruction *Inst = BI++;
1722 if (Inst->getType()->isVoidTy())
1723 continue;
1724
Chris Lattner8db50122009-11-02 02:54:24 +00001725 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1726 if (IV.isOverdefined())
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001727 continue;
1728
1729 Constant *Const = IV.isConstant()
1730 ? IV.getConstant() : UndefValue::get(Inst->getType());
1731 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1732
1733 // Replaces all of the uses of a variable with uses of the
1734 // constant.
1735 Inst->replaceAllUsesWith(Const);
1736
1737 // Delete the instruction.
1738 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1739 Inst->eraseFromParent();
1740
1741 // Hey, we just changed something!
1742 MadeChanges = true;
1743 ++IPNumInstRemoved;
1744 }
1745 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001746
1747 // Now that all instructions in the function are constant folded, erase dead
1748 // blocks, because we can now use ConstantFoldTerminator to get rid of
1749 // in-edges.
1750 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1751 // If there are any PHI nodes in this successor, drop entries for BB now.
1752 BasicBlock *DeadBB = BlocksToErase[i];
1753 while (!DeadBB->use_empty()) {
1754 Instruction *I = cast<Instruction>(DeadBB->use_back());
1755 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001756 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001757 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001758 // if this is a branch or switch on undef. Fold it manually as a
1759 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001760#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001761 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1762 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1763 "Branch should be foldable!");
1764 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1765 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1766 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001767 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001768 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001769#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001770
1771 // Make this an uncond branch to the first successor.
1772 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001773 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001774
1775 // Remove entries in successor phi nodes to remove edges.
1776 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1777 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1778
1779 // Remove the old terminator.
1780 TI->eraseFromParent();
1781 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001782 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001783
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001784 // Finally, delete the basic block.
1785 F->getBasicBlockList().erase(DeadBB);
1786 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001787 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001788 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001789
1790 // If we inferred constant or undef return values for a function, we replaced
1791 // all call uses with the inferred value. This means we don't need to bother
1792 // actually returning anything from the function. Replace all return
1793 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001794 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001795 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001796 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001797 E = RV.end(); I != E; ++I)
1798 if (!I->second.isOverdefined() &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001799 !I->first->getReturnType()->isVoidTy()) {
Chris Lattner0417feb2004-12-11 02:53:57 +00001800 Function *F = I->first;
1801 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1802 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1803 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001804 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner0417feb2004-12-11 02:53:57 +00001805 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001806
1807 // If we infered constant or undef values for globals variables, we can delete
1808 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001809 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1810 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001811 E = TG.end(); I != E; ++I) {
1812 GlobalVariable *GV = I->first;
1813 assert(!I->second.isOverdefined() &&
1814 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001815 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001816 while (!GV->use_empty()) {
1817 StoreInst *SI = cast<StoreInst>(GV->use_back());
1818 SI->eraseFromParent();
1819 }
1820 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001821 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001822 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001823
Chris Lattner59acc7d2004-12-10 08:02:06 +00001824 return MadeChanges;
1825}