blob: 7421d4f349ba70afbb741c91e20c093cd94d4e35 [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 Lattner59acc7d2004-12-10 08:02:06 +000031#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000032#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner79272202009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000039#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000040#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000042#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000043#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumInstRemoved, "Number of instructions removed");
47STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
48
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000049STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
51STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
52
Chris Lattner0dbfc052002-04-29 21:26:08 +000053namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000054/// LatticeVal class - This class represents the different lattice values that
55/// an LLVM value may occupy. It is a simple class with value semantics.
56///
Chris Lattner3e8b6632009-09-02 06:11:42 +000057class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000058 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000059 /// undefined - This LLVM Value has no known value yet.
60 undefined,
61
62 /// constant - This LLVM Value has a specific constant value.
63 constant,
64
65 /// forcedconstant - This LLVM Value was thought to be undef until
66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
67 /// with another (different) constant, it goes to overdefined, instead of
68 /// asserting.
69 forcedconstant,
70
71 /// overdefined - This instruction is not known to be constant, and we know
72 /// it has a value.
73 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000074 };
75
76 /// Val: This stores the current lattice value along with the Constant* for
77 /// the constant if this is a 'constant' or 'forcedconstant' value.
78 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000079
Chris Lattner79272202009-11-02 02:20:32 +000080 LatticeValueTy getLatticeValue() const {
81 return Val.getInt();
82 }
83
Chris Lattner138a1242001-06-27 23:38:11 +000084public:
Chris Lattner79272202009-11-02 02:20:32 +000085 inline LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000086
Chris Lattner79272202009-11-02 02:20:32 +000087 inline bool isUndefined() const { return getLatticeValue() == undefined; }
88 inline bool isConstant() const {
89 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
90 }
91 inline bool isOverdefined() const { return getLatticeValue() == overdefined; }
92
93 inline Constant *getConstant() const {
94 assert(isConstant() && "Cannot get the constant of a non-constant!");
95 return Val.getPointer();
96 }
97
98 /// markOverdefined - Return true if this is a change in status.
Chris Lattner138a1242001-06-27 23:38:11 +000099 inline bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000100 if (isOverdefined())
101 return false;
102
103 Val.setInt(overdefined);
104 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000105 }
106
Chris Lattner79272202009-11-02 02:20:32 +0000107 /// markConstant - Return true if this is a change in status.
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000108 inline bool markConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000109 if (isConstant()) {
110 assert(getConstant() == V && "Marking constant with different value");
111 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000112 }
Chris Lattner79272202009-11-02 02:20:32 +0000113
114 if (isUndefined()) {
115 Val.setInt(constant);
116 assert(V && "Marking constant with NULL");
117 Val.setPointer(V);
118 } else {
119 assert(getLatticeValue() == forcedconstant &&
120 "Cannot move from overdefined to constant!");
121 // Stay at forcedconstant if the constant is the same.
122 if (V == getConstant()) return false;
123
124 // Otherwise, we go to overdefined. Assumptions made based on the
125 // forced value are possibly wrong. Assuming this is another constant
126 // could expose a contradiction.
127 Val.setInt(overdefined);
128 }
129 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000130 }
131
Chris Lattner3bad2532006-12-20 06:21:33 +0000132 inline void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000133 assert(isUndefined() && "Can't force a defined value!");
134 Val.setInt(forcedconstant);
135 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000136 }
Chris Lattner138a1242001-06-27 23:38:11 +0000137};
Chris Lattnercc4f60b2009-11-02 02:47:51 +0000138} // end anonymous namespace.
139
140
141namespace {
Chris Lattner138a1242001-06-27 23:38:11 +0000142
Chris Lattner138a1242001-06-27 23:38:11 +0000143//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000144//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000145/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
146/// Constant Propagation.
147///
148class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnercf712de2008-08-23 23:36:38 +0000149 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000150 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000151
Chris Lattnerdd336d12004-12-11 05:15:59 +0000152 /// GlobalValue - If we are tracking any values for the contents of a global
153 /// variable, we keep a mapping from the constant accessor to the element of
154 /// the global, to the currently known value. If the value becomes
155 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000156 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000157
Devang Patel7c490d42008-03-11 05:46:42 +0000158 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000159 /// value out of a function, it will have an entry in this map, indicating
160 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000161 DenseMap<Function*, LatticeVal> TrackedRetVals;
162
163 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
164 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000165 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000166
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000167 // The reason for two worklists is that overdefined is the lowest state
168 // on the lattice, and moving things to overdefined as fast as possible
169 // makes SCCP converge much faster.
170 // By having a separate worklist, we accomplish this because everything
171 // possibly overdefined will become overdefined at the soonest possible
172 // point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000173 SmallVector<Value*, 64> OverdefinedInstWorkList;
174 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000175
176
Chris Lattnercf712de2008-08-23 23:36:38 +0000177 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000178
Chris Lattner1daee8b2004-01-12 03:57:30 +0000179 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
180 /// overdefined, despite the fact that the PHI node is overdefined.
181 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
182
Chris Lattner16b18fd2003-10-08 16:55:34 +0000183 /// KnownFeasibleEdges - Entries in this set are edges which have already had
184 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000185 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
186 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000187public:
188
Chris Lattner82bec2c2004-11-15 04:44:20 +0000189 /// MarkBlockExecutable - This method can be used by clients to mark all of
190 /// the blocks that are known to be intrinsically live in the processed unit.
191 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000192 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000193 BBExecutable.insert(BB); // Basic block is executable!
194 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000195 }
196
Chris Lattnerdd336d12004-12-11 05:15:59 +0000197 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000198 /// inform the SCCPSolver that it should track loads and stores to the
199 /// specified global variable if it can. This is only legal to call if
200 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000201 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
202 const Type *ElTy = GV->getType()->getElementType();
203 if (ElTy->isFirstClassType()) {
204 LatticeVal &IV = TrackedGlobals[GV];
205 if (!isa<UndefValue>(GV->getInitializer()))
206 IV.markConstant(GV->getInitializer());
207 }
208 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000209
210 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
211 /// and out of the specified function (which cannot have its address taken),
212 /// this method must be called.
213 void AddTrackedFunction(Function *F) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000214 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000215 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000216 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
217 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000218 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
219 LatticeVal()));
220 } else
221 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000222 }
223
Chris Lattner82bec2c2004-11-15 04:44:20 +0000224 /// Solve - Solve for constants and executable blocks.
225 ///
226 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000227
Chris Lattner3bad2532006-12-20 06:21:33 +0000228 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000229 /// that branches on undef values cannot reach any of their successors.
230 /// However, this is not a safe assumption. After we solve dataflow, this
231 /// method should be use to handle this. If this returns true, the solver
232 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000233 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000234
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000235 bool isBlockExecutable(BasicBlock *BB) const {
236 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000237 }
238
239 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000240 /// LLVM values to LatticeVals.
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000241 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000242 return ValueState;
243 }
244
Devang Patel7c490d42008-03-11 05:46:42 +0000245 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000246 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000247 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
248 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000249 }
250
Chris Lattnerdd336d12004-12-11 05:15:59 +0000251 /// getTrackedGlobals - Get and return the set of inferred initializers for
252 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000253 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000254 return TrackedGlobals;
255 }
256
Chris Lattner57939df2007-03-04 04:50:21 +0000257 inline void markOverdefined(Value *V) {
258 markOverdefined(ValueState[V], V);
259 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000260
Chris Lattner138a1242001-06-27 23:38:11 +0000261private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000262 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000263 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000264 // the users of the instruction are updated later.
265 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000266 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000267 if (IV.markConstant(C)) {
Dan Gohman87325772009-08-17 15:25:05 +0000268 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner59acc7d2004-12-10 08:02:06 +0000269 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000270 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000271 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000272
273 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
274 IV.markForcedConstant(C);
Dan Gohman87325772009-08-17 15:25:05 +0000275 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner3bad2532006-12-20 06:21:33 +0000276 InstWorkList.push_back(V);
277 }
278
Chris Lattner59acc7d2004-12-10 08:02:06 +0000279 inline void markConstant(Value *V, Constant *C) {
280 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000281 }
282
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000283 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000284 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000285 // work list so that the users of the instruction are updated later.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000286 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000287 if (IV.markOverdefined()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000288 DEBUG(errs() << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000289 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000290 errs() << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000291 else
Dan Gohman87325772009-08-17 15:25:05 +0000292 errs() << *V << '\n');
Chris Lattner82bec2c2004-11-15 04:44:20 +0000293 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000294 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000295 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000296 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000297
298 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
299 if (IV.isOverdefined() || MergeWithV.isUndefined())
300 return; // Noop.
301 if (MergeWithV.isOverdefined())
302 markOverdefined(IV, V);
303 else if (IV.isUndefined())
304 markConstant(IV, V, MergeWithV.getConstant());
305 else if (IV.getConstant() != MergeWithV.getConstant())
306 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000307 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000308
309 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
310 return mergeInValue(ValueState[V], V, MergeWithV);
311 }
312
Chris Lattner138a1242001-06-27 23:38:11 +0000313
Chris Lattneref36dfd2004-11-15 05:03:30 +0000314 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000315 // This function is necessary because not all values should start out in the
Chris Lattner2f096252009-11-02 02:33:50 +0000316 // underdefined state. Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000317 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000318 // Instruction object, then use this accessor to get its value from the map.
319 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000320 inline LatticeVal &getValueState(Value *V) {
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000321 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000322 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000323
Chris Lattner3bad2532006-12-20 06:21:33 +0000324 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000325 if (isa<UndefValue>(V)) {
326 // Nothing to do, remain undefined.
327 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000328 LatticeVal &LV = ValueState[C];
329 LV.markConstant(C); // Constants are constant
330 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000331 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000332 }
Chris Lattner2f096252009-11-02 02:33:50 +0000333 // All others are underdefined by default.
Chris Lattner138a1242001-06-27 23:38:11 +0000334 return ValueState[V];
335 }
336
Misha Brukmanfd939082005-04-21 23:48:37 +0000337 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner2f096252009-11-02 02:33:50 +0000338 // work list if it is not already executable.
Misha Brukmanfd939082005-04-21 23:48:37 +0000339 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000340 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
341 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
342 return; // This edge is already known to be executable!
343
344 if (BBExecutable.count(Dest)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000345 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
346 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000347
348 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000349 // feasible that wasn't before. Revisit the PHI nodes in the block
350 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000351 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
352 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000353
354 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000355 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000356 }
Chris Lattner138a1242001-06-27 23:38:11 +0000357 }
358
Chris Lattner82bec2c2004-11-15 04:44:20 +0000359 // getFeasibleSuccessors - Return a vector of booleans to indicate which
360 // successors are reachable from a given terminator instruction.
361 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000362 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000363
364 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000365 // block to the 'To' basic block is currently feasible.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000366 //
367 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
368
369 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattner2f096252009-11-02 02:33:50 +0000370 // instruction that was just changed state somehow. Based on this
Chris Lattner82bec2c2004-11-15 04:44:20 +0000371 // information, we need to update the specified user of this instruction.
372 //
373 void OperandChangedState(User *U) {
374 // Only instructions use other variable values!
375 Instruction &I = cast<Instruction>(*U);
376 if (BBExecutable.count(I.getParent())) // Inst is executable?
377 visit(I);
378 }
379
380private:
381 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000382
Chris Lattner2f096252009-11-02 02:33:50 +0000383 // visit implementations - Something changed in this instruction. Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000384 // operand made a transition, or the instruction is newly executable. Change
385 // the value type of I to reflect these changes if appropriate.
Chris Lattner7e708292002-06-25 16:13:24 +0000386 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000387
388 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000389 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000390 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000391
Chris Lattnerb8047602002-08-14 17:53:45 +0000392 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000393 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000394 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000395 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000396 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000397 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000398 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000399 void visitExtractValueInst(ExtractValueInst &EVI);
400 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000401
Chris Lattner2f096252009-11-02 02:33:50 +0000402 // Instructions that cannot be folded away.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000403 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000404 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000405 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000406 void visitCallInst (CallInst &I) {
407 if (isFreeCall(&I))
408 return;
Chris Lattner32c0d222009-09-27 21:35:11 +0000409 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000410 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000411 void visitInvokeInst (InvokeInst &II) {
412 visitCallSite(CallSite::get(&II));
413 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000414 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000415 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000416 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000417 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000418 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000419 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
420 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000421
Chris Lattner7e708292002-06-25 16:13:24 +0000422 void visitInstruction(Instruction &I) {
Chris Lattner2f096252009-11-02 02:33:50 +0000423 // If a new instruction is added to LLVM that we don't handle.
Chris Lattnerbdff5482009-08-23 04:37:46 +0000424 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000425 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000426 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000427};
Chris Lattnerf6293092002-07-23 18:06:35 +0000428
Duncan Sandse2abf122007-07-20 08:56:21 +0000429} // end anonymous namespace
430
431
Chris Lattnerb9a66342002-05-02 21:44:00 +0000432// getFeasibleSuccessors - Return a vector of booleans to indicate which
433// successors are reachable from a given terminator instruction.
434//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000435void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000436 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000437 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000438 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000439 if (BI->isUnconditional()) {
440 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000441 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000442 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000443
444 LatticeVal &BCValue = getValueState(BI->getCondition());
445 if (BCValue.isOverdefined() ||
446 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
447 // Overdefined condition variables, and branches on unfoldable constant
448 // conditions, mean the branch could go either way.
449 Succs[0] = Succs[1] = true;
450 return;
451 }
452
453 // Constant condition variables mean the branch can only go a single way.
454 Succs[cast<ConstantInt>(BCValue.getConstant())->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000455 return;
456 }
457
458 if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000459 // Invoke instructions successors are always executable.
460 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000461 return;
462 }
463
464 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000465 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000466 if (SCValue.isOverdefined() || // Overdefined condition?
467 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000468 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000469 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner3a73c9e2008-05-10 23:56:54 +0000470 } else if (SCValue.isConstant())
471 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000472 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000473 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000474
475 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
476 if (isa<IndirectBrInst>(&TI)) {
477 // Just mark all destinations executable!
478 Succs.assign(TI.getNumSuccessors(), true);
479 return;
480 }
481
482#ifndef NDEBUG
483 errs() << "Unknown terminator instruction: " << TI << '\n';
484#endif
485 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000486}
487
488
Chris Lattner59f0ce22002-05-02 21:18:01 +0000489// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattner2f096252009-11-02 02:33:50 +0000490// block to the 'To' basic block is currently feasible.
Chris Lattner59f0ce22002-05-02 21:18:01 +0000491//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000492bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000493 assert(BBExecutable.count(To) && "Dest should always be alive!");
494
495 // Make sure the source basic block is executable!!
496 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000497
Chris Lattner2f096252009-11-02 02:33:50 +0000498 // Check to make sure this edge itself is actually feasible now.
Chris Lattner7d275f42003-10-08 15:47:41 +0000499 TerminatorInst *TI = From->getTerminator();
500 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
501 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000502 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000503
504 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000505
Chris Lattnerea0db072009-11-02 02:30:06 +0000506 // Overdefined condition variables mean the branch could go either way,
507 // undef conditions mean that neither edge is feasible yet.
508 if (!BCValue.isConstant())
509 return BCValue.isOverdefined();
510
511 // Not branching on an evaluatable constant?
512 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
513
514 // Constant condition variables mean the branch can only go a single way.
515 bool CondIsFalse = cast<ConstantInt>(BCValue.getConstant())->isZero();
516 return BI->getSuccessor(CondIsFalse) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000517 }
518
519 // Invoke instructions successors are always executable.
520 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000521 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000522
523 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000524 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000525 if (SCValue.isOverdefined()) { // Overdefined condition?
526 // All destinations are executable!
527 return true;
528 } else if (SCValue.isConstant()) {
529 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000530 if (!isa<ConstantInt>(CPV))
531 return true; // not a foldable constant?
532
Chris Lattner7d275f42003-10-08 15:47:41 +0000533 // Make sure to skip the "default value" which isn't a value
534 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
Chris Lattner2f096252009-11-02 02:33:50 +0000535 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch.
Chris Lattner7d275f42003-10-08 15:47:41 +0000536 return SI->getSuccessor(i) == To;
537
Chris Lattner2f096252009-11-02 02:33:50 +0000538 // If the constant value is not equal to any of the branches, we must
539 // execute default branch.
Chris Lattner7d275f42003-10-08 15:47:41 +0000540 return SI->getDefaultDest() == To;
541 }
542 return false;
Chris Lattner7d275f42003-10-08 15:47:41 +0000543 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000544
545 // Just mark all destinations executable!
546 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
547 if (isa<IndirectBrInst>(&TI))
548 return true;
549
550#ifndef NDEBUG
551 errs() << "Unknown terminator instruction: " << *TI << '\n';
552#endif
553 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000554}
Chris Lattner138a1242001-06-27 23:38:11 +0000555
Chris Lattner2f096252009-11-02 02:33:50 +0000556// visit Implementations - Something changed in this instruction, either an
Chris Lattner138a1242001-06-27 23:38:11 +0000557// operand made a transition, or the instruction is newly executable. Change
558// the value type of I to reflect these changes if appropriate. This method
559// makes sure to do the following actions:
560//
561// 1. If a phi node merges two constants in, and has conflicting value coming
562// from different branches, or if the PHI node merges in an overdefined
563// value, then the PHI node becomes overdefined.
564// 2. If a phi node merges only constants in, and they all agree on value, the
565// PHI node becomes a constant value equal to that.
566// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
567// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
568// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
569// 6. If a conditional branch has a value that is constant, make the selected
570// destination executable
571// 7. If a conditional branch has a value that is overdefined, make all
572// successors executable.
573//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000574void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000575 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000576 if (PNIV.isOverdefined()) {
577 // There may be instructions using this PHI node that are not overdefined
578 // themselves. If so, make sure that they know that the PHI node operand
579 // changed.
580 std::multimap<PHINode*, Instruction*>::iterator I, E;
581 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
582 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000583 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000584 for (; I != E; ++I) Users.push_back(I->second);
585 while (!Users.empty()) {
586 visit(Users.back());
587 Users.pop_back();
588 }
589 }
590 return; // Quick exit
591 }
Chris Lattner138a1242001-06-27 23:38:11 +0000592
Chris Lattnera2f652d2004-03-16 19:49:59 +0000593 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
594 // and slow us down a lot. Just mark them overdefined.
595 if (PN.getNumIncomingValues() > 64) {
596 markOverdefined(PNIV, &PN);
597 return;
598 }
599
Chris Lattner2a632552002-04-18 15:13:15 +0000600 // Look at all of the executable operands of the PHI node. If any of them
601 // are overdefined, the PHI becomes overdefined as well. If they are all
602 // constant, and they agree with each other, the PHI becomes the identical
603 // constant. If they are constant and don't agree, the PHI is overdefined.
604 // If there are no executable operands, the PHI remains undefined.
605 //
Chris Lattner9de28282003-04-25 02:50:03 +0000606 Constant *OperandVal = 0;
607 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000608 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000609 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000610
Chris Lattner7e708292002-06-25 16:13:24 +0000611 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000612 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnercf712de2008-08-23 23:36:38 +0000613 markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000614 return;
615 }
616
Chris Lattner2f096252009-11-02 02:33:50 +0000617 if (OperandVal == 0) { // Grab the first value.
Chris Lattner9de28282003-04-25 02:50:03 +0000618 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000619 } else { // Another value is being merged in!
620 // There is already a reachable operand. If we conflict with it,
621 // then the PHI node becomes overdefined. If we agree with it, we
622 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000623
Chris Lattner2f096252009-11-02 02:33:50 +0000624 // Check to see if there are two different constants merging.
Chris Lattner9de28282003-04-25 02:50:03 +0000625 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000626 // Yes there is. This means the PHI node is not constant.
627 // You must be overdefined poor PHI.
628 //
Chris Lattnercf712de2008-08-23 23:36:38 +0000629 markOverdefined(&PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000630 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000631 }
Chris Lattner138a1242001-06-27 23:38:11 +0000632 }
633 }
Chris Lattner138a1242001-06-27 23:38:11 +0000634 }
635
Chris Lattner2a632552002-04-18 15:13:15 +0000636 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000637 // arguments that agree with each other(and OperandVal is the constant) or
638 // OperandVal is null because there are no defined incoming arguments. If
639 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000640 //
Chris Lattner9de28282003-04-25 02:50:03 +0000641 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000642 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000643}
644
Chris Lattner59acc7d2004-12-10 08:02:06 +0000645void SCCPSolver::visitReturnInst(ReturnInst &I) {
646 if (I.getNumOperands() == 0) return; // Ret void
647
Chris Lattner59acc7d2004-12-10 08:02:06 +0000648 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000649 // If we are tracking the return value of this function, merge it in.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000650 if (!F->hasLocalLinkage())
Devang Patel7c490d42008-03-11 05:46:42 +0000651 return;
652
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000653 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000654 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000655 TrackedRetVals.find(F);
656 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000657 !TFRVI->second.isOverdefined()) {
658 LatticeVal &IV = getValueState(I.getOperand(0));
659 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000660 return;
661 }
662 }
663
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000664 // Handle functions that return multiple values.
665 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
666 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000667 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000668 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
669 if (It == TrackedMultipleRetVals.end()) break;
670 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000671 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000672 } else if (!TrackedMultipleRetVals.empty() &&
673 I.getNumOperands() == 1 &&
674 isa<StructType>(I.getOperand(0)->getType())) {
675 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
676 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000677 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000678 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
679 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000680 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000681 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000682 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000683 }
684}
685
Chris Lattner82bec2c2004-11-15 04:44:20 +0000686void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000687 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000688 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000689
Chris Lattner16b18fd2003-10-08 16:55:34 +0000690 BasicBlock *BB = TI.getParent();
691
Chris Lattner2f096252009-11-02 02:33:50 +0000692 // Mark all feasible successors executable.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000693 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000694 if (SuccFeasible[i])
695 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000696}
697
Chris Lattner82bec2c2004-11-15 04:44:20 +0000698void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000699 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000700 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000701 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000702 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000703 else if (VState.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000704 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Reid Spencer4da49122006-12-12 05:05:00 +0000705 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000706}
707
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000708void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000709 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000710
Dan Gohman60ea2682008-06-20 16:41:17 +0000711 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000712 if (isa<UndefValue>(Aggr))
713 return;
714
715 // Currently only handle single-index extractvalues.
716 if (EVI.getNumIndices() != 1) {
717 markOverdefined(&EVI);
718 return;
719 }
720
721 Function *F = 0;
722 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
723 F = CI->getCalledFunction();
724 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
725 F = II->getCalledFunction();
726
727 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
728 // result back!
729 if (F == 0 || TrackedMultipleRetVals.empty()) {
730 markOverdefined(&EVI);
731 return;
732 }
733
Chris Lattnercf712de2008-08-23 23:36:38 +0000734 // See if we are tracking the result of the callee. If not tracking this
735 // function (for example, it is a declaration) just move to overdefined.
736 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000737 markOverdefined(&EVI);
738 return;
739 }
740
741 // Otherwise, the value will be merged in here as a result of CallSite
742 // handling.
743}
744
745void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000746 Value *Aggr = IVI.getAggregateOperand();
747 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000748
Dan Gohman60ea2682008-06-20 16:41:17 +0000749 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000750 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000751 return;
752
753 // Currently only handle single-index insertvalues.
754 if (IVI.getNumIndices() != 1) {
755 markOverdefined(&IVI);
756 return;
757 }
Dan Gohmandfaceb42008-06-20 16:39:44 +0000758
759 // Currently only handle insertvalue instructions that are in a single-use
760 // chain that builds up a return value.
761 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
762 if (!TmpIVI->hasOneUse()) {
763 markOverdefined(&IVI);
764 return;
765 }
766 const Value *V = *TmpIVI->use_begin();
767 if (isa<ReturnInst>(V))
768 break;
769 TmpIVI = dyn_cast<InsertValueInst>(V);
770 if (!TmpIVI) {
771 markOverdefined(&IVI);
772 return;
773 }
774 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000775
776 // See if we are tracking the result of the callee.
777 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000778 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000779 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
780
781 // Merge in the inserted member value.
782 if (It != TrackedMultipleRetVals.end())
783 mergeInValue(It->second, F, getValueState(Val));
784
Dan Gohman60ea2682008-06-20 16:41:17 +0000785 // Mark the aggregate result of the IVI overdefined; any tracking that we do
786 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000787 markOverdefined(&IVI);
788}
789
Chris Lattner82bec2c2004-11-15 04:44:20 +0000790void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000791 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000792 if (CondValue.isUndefined())
793 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000794 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000795 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000796 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000797 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000798 return;
799 }
800 }
801
802 // Otherwise, the condition is overdefined or a constant we can't evaluate.
803 // See if we can produce something better than overdefined based on the T/F
804 // value.
805 LatticeVal &TVal = getValueState(I.getTrueValue());
806 LatticeVal &FVal = getValueState(I.getFalseValue());
807
808 // select ?, C, C -> C.
809 if (TVal.isConstant() && FVal.isConstant() &&
810 TVal.getConstant() == FVal.getConstant()) {
811 markConstant(&I, FVal.getConstant());
812 return;
813 }
814
815 if (TVal.isUndefined()) { // select ?, undef, X -> X.
816 mergeInValue(&I, FVal);
817 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
818 mergeInValue(&I, TVal);
819 } else {
820 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000821 }
822}
823
Chris Lattner2f096252009-11-02 02:33:50 +0000824// Handle BinaryOperators and Shift Instructions.
Chris Lattner82bec2c2004-11-15 04:44:20 +0000825void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000826 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000827 if (IV.isOverdefined()) return;
828
Chris Lattneref36dfd2004-11-15 05:03:30 +0000829 LatticeVal &V1State = getValueState(I.getOperand(0));
830 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000831
Chris Lattner2a632552002-04-18 15:13:15 +0000832 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000833 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
834 // operand is overdefined.
835 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
836 LatticeVal *NonOverdefVal = 0;
837 if (!V1State.isOverdefined()) {
838 NonOverdefVal = &V1State;
839 } else if (!V2State.isOverdefined()) {
840 NonOverdefVal = &V2State;
841 }
842
843 if (NonOverdefVal) {
844 if (NonOverdefVal->isUndefined()) {
845 // Could annihilate value.
846 if (I.getOpcode() == Instruction::And)
Owen Andersona7235ea2009-07-31 20:28:14 +0000847 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000848 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000849 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000850 else
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000851 markConstant(IV, &I,
Owen Andersona7235ea2009-07-31 20:28:14 +0000852 Constant::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000853 return;
854 } else {
855 if (I.getOpcode() == Instruction::And) {
856 if (NonOverdefVal->getConstant()->isNullValue()) {
857 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000858 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000859 }
860 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000861 if (ConstantInt *CI =
862 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000863 if (CI->isAllOnesValue()) {
864 markConstant(IV, &I, NonOverdefVal->getConstant());
865 return; // X or -1 = -1
866 }
867 }
868 }
869 }
870 }
871
872
Chris Lattner1daee8b2004-01-12 03:57:30 +0000873 // If both operands are PHI nodes, it is possible that this instruction has
874 // a constant value, despite the fact that the PHI node doesn't. Check for
875 // this condition now.
876 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
877 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
878 if (PN1->getParent() == PN2->getParent()) {
879 // Since the two PHI nodes are in the same basic block, they must have
880 // entries for the same predecessors. Walk the predecessor list, and
881 // if all of the incoming values are constants, and the result of
882 // evaluating this expression with all incoming value pairs is the
883 // same, then this expression is a constant even though the PHI node
884 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000885 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000886 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000887 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000888 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000889 LatticeVal &In2 =
890 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000891
892 if (In1.isOverdefined() || In2.isOverdefined()) {
893 Result.markOverdefined();
894 break; // Cannot fold this operation over the PHI nodes!
895 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000896 Constant *V =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000897 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000898 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000899 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000900 Result.markConstant(V);
901 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000902 Result.markOverdefined();
903 break;
904 }
905 }
906 }
907
908 // If we found a constant value here, then we know the instruction is
909 // constant despite the fact that the PHI nodes are overdefined.
910 if (Result.isConstant()) {
911 markConstant(IV, &I, Result.getConstant());
912 // Remember that this instruction is virtually using the PHI node
913 // operands.
914 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
915 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
916 return;
917 } else if (Result.isUndefined()) {
918 return;
919 }
920
921 // Okay, this really is overdefined now. Since we might have
922 // speculatively thought that this was not overdefined before, and
923 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
924 // make sure to clean out any entries that we put there, for
925 // efficiency.
926 std::multimap<PHINode*, Instruction*>::iterator It, E;
927 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
928 while (It != E) {
929 if (It->second == &I) {
930 UsersOfOverdefinedPHIs.erase(It++);
931 } else
932 ++It;
933 }
934 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
935 while (It != E) {
936 if (It->second == &I) {
937 UsersOfOverdefinedPHIs.erase(It++);
938 } else
939 ++It;
940 }
941 }
942
943 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000944 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000945 markConstant(IV, &I,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000946 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000947 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000948 }
949}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000950
Chris Lattner2f096252009-11-02 02:33:50 +0000951// Handle ICmpInst instruction.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000952void SCCPSolver::visitCmpInst(CmpInst &I) {
953 LatticeVal &IV = ValueState[&I];
954 if (IV.isOverdefined()) return;
955
956 LatticeVal &V1State = getValueState(I.getOperand(0));
957 LatticeVal &V2State = getValueState(I.getOperand(1));
958
959 if (V1State.isOverdefined() || V2State.isOverdefined()) {
960 // If both operands are PHI nodes, it is possible that this instruction has
961 // a constant value, despite the fact that the PHI node doesn't. Check for
962 // this condition now.
963 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
964 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
965 if (PN1->getParent() == PN2->getParent()) {
966 // Since the two PHI nodes are in the same basic block, they must have
967 // entries for the same predecessors. Walk the predecessor list, and
968 // if all of the incoming values are constants, and the result of
969 // evaluating this expression with all incoming value pairs is the
970 // same, then this expression is a constant even though the PHI node
971 // is not a constant!
972 LatticeVal Result;
973 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
974 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
975 BasicBlock *InBlock = PN1->getIncomingBlock(i);
976 LatticeVal &In2 =
977 getValueState(PN2->getIncomingValueForBlock(InBlock));
978
979 if (In1.isOverdefined() || In2.isOverdefined()) {
980 Result.markOverdefined();
981 break; // Cannot fold this operation over the PHI nodes!
982 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000983 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000984 In1.getConstant(),
985 In2.getConstant());
986 if (Result.isUndefined())
987 Result.markConstant(V);
988 else if (Result.isConstant() && Result.getConstant() != V) {
989 Result.markOverdefined();
990 break;
991 }
992 }
993 }
994
995 // If we found a constant value here, then we know the instruction is
996 // constant despite the fact that the PHI nodes are overdefined.
997 if (Result.isConstant()) {
998 markConstant(IV, &I, Result.getConstant());
999 // Remember that this instruction is virtually using the PHI node
1000 // operands.
1001 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1002 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1003 return;
1004 } else if (Result.isUndefined()) {
1005 return;
1006 }
1007
1008 // Okay, this really is overdefined now. Since we might have
1009 // speculatively thought that this was not overdefined before, and
1010 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1011 // make sure to clean out any entries that we put there, for
1012 // efficiency.
1013 std::multimap<PHINode*, Instruction*>::iterator It, E;
1014 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
1015 while (It != E) {
1016 if (It->second == &I) {
1017 UsersOfOverdefinedPHIs.erase(It++);
1018 } else
1019 ++It;
1020 }
1021 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1022 while (It != E) {
1023 if (It->second == &I) {
1024 UsersOfOverdefinedPHIs.erase(It++);
1025 } else
1026 ++It;
1027 }
1028 }
1029
1030 markOverdefined(IV, &I);
1031 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001032 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001033 V1State.getConstant(),
1034 V2State.getConstant()));
1035 }
1036}
1037
Robert Bocchino56107e22006-01-10 19:05:05 +00001038void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001039 // FIXME : SCCP does not handle vectors properly.
1040 markOverdefined(&I);
1041 return;
1042
1043#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001044 LatticeVal &ValState = getValueState(I.getOperand(0));
1045 LatticeVal &IdxState = getValueState(I.getOperand(1));
1046
1047 if (ValState.isOverdefined() || IdxState.isOverdefined())
1048 markOverdefined(&I);
1049 else if(ValState.isConstant() && IdxState.isConstant())
1050 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1051 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001052#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001053}
1054
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001055void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001056 // FIXME : SCCP does not handle vectors properly.
1057 markOverdefined(&I);
1058 return;
1059#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001060 LatticeVal &ValState = getValueState(I.getOperand(0));
1061 LatticeVal &EltState = getValueState(I.getOperand(1));
1062 LatticeVal &IdxState = getValueState(I.getOperand(2));
1063
1064 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1065 IdxState.isOverdefined())
1066 markOverdefined(&I);
1067 else if(ValState.isConstant() && EltState.isConstant() &&
1068 IdxState.isConstant())
1069 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1070 EltState.getConstant(),
1071 IdxState.getConstant()));
1072 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001073 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001074 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1075 EltState.getConstant(),
1076 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001077#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001078}
1079
Chris Lattner543abdf2006-04-08 01:19:12 +00001080void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001081 // FIXME : SCCP does not handle vectors properly.
1082 markOverdefined(&I);
1083 return;
1084#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001085 LatticeVal &V1State = getValueState(I.getOperand(0));
1086 LatticeVal &V2State = getValueState(I.getOperand(1));
1087 LatticeVal &MaskState = getValueState(I.getOperand(2));
1088
1089 if (MaskState.isUndefined() ||
1090 (V1State.isUndefined() && V2State.isUndefined()))
1091 return; // Undefined output if mask or both inputs undefined.
1092
1093 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1094 MaskState.isOverdefined()) {
1095 markOverdefined(&I);
1096 } else {
1097 // A mix of constant/undef inputs.
1098 Constant *V1 = V1State.isConstant() ?
1099 V1State.getConstant() : UndefValue::get(I.getType());
1100 Constant *V2 = V2State.isConstant() ?
1101 V2State.getConstant() : UndefValue::get(I.getType());
1102 Constant *Mask = MaskState.isConstant() ?
1103 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1104 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1105 }
Devang Patel67a821d2006-12-04 23:54:59 +00001106#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001107}
1108
Chris Lattner2f096252009-11-02 02:33:50 +00001109// Handle getelementptr instructions. If all operands are constants then we
Chris Lattner2a88bb72002-08-30 23:39:00 +00001110// can turn this into a getelementptr ConstantExpr.
1111//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001112void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001113 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001114 if (IV.isOverdefined()) return;
1115
Chris Lattnere777ff22007-02-02 20:51:48 +00001116 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001117 Operands.reserve(I.getNumOperands());
1118
1119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001120 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001121 if (State.isUndefined())
Chris Lattner2f096252009-11-02 02:33:50 +00001122 return; // Operands are not resolved yet.
1123
1124 if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001125 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001126 return;
1127 }
1128 assert(State.isConstant() && "Unknown state!");
1129 Operands.push_back(State.getConstant());
1130 }
1131
1132 Constant *Ptr = Operands[0];
Chris Lattner2f096252009-11-02 02:33:50 +00001133 Operands.erase(Operands.begin()); // Erase the pointer from idx list.
Chris Lattner2a88bb72002-08-30 23:39:00 +00001134
Owen Andersonbaf3c402009-07-29 18:55:55 +00001135 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Chris Lattnere777ff22007-02-02 20:51:48 +00001136 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001137}
Brian Gaeked0fde302003-11-11 22:41:34 +00001138
Chris Lattnerdd336d12004-12-11 05:15:59 +00001139void SCCPSolver::visitStoreInst(Instruction &SI) {
1140 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1141 return;
1142 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001143 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001144 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1145
1146 // Get the value we are storing into the global.
1147 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1148
1149 mergeInValue(I->second, GV, PtrVal);
1150 if (I->second.isOverdefined())
1151 TrackedGlobals.erase(I); // No need to keep tracking this!
1152}
1153
1154
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001155// Handle load instructions. If the operand is a constant pointer to a constant
1156// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001157void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001158 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001159 if (IV.isOverdefined()) return;
1160
Chris Lattneref36dfd2004-11-15 05:03:30 +00001161 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001162 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1163 if (PtrVal.isConstant() && !I.isVolatile()) {
1164 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001165 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +00001166 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001167 // load null -> null
Owen Andersona7235ea2009-07-31 20:28:14 +00001168 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerc76d8032004-03-07 22:16:24 +00001169 return;
1170 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001171
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001172 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001173 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1174 if (GV->isConstant()) {
Duncan Sands64da9402009-03-21 21:27:31 +00001175 if (GV->hasDefinitiveInitializer()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001176 markConstant(IV, &I, GV->getInitializer());
1177 return;
1178 }
1179 } else if (!TrackedGlobals.empty()) {
1180 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001181 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001182 TrackedGlobals.find(GV);
1183 if (It != TrackedGlobals.end()) {
1184 mergeInValue(IV, &I, It->second);
1185 return;
1186 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001187 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001188 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001189
1190 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1191 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1192 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001193 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +00001194 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Jeff Cohen9d809302005-04-23 21:38:35 +00001195 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +00001196 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001197 markConstant(IV, &I, V);
1198 return;
1199 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001200 }
1201
1202 // Otherwise we cannot say for certain what value this load will produce.
1203 // Bail out.
1204 markOverdefined(IV, &I);
1205}
Chris Lattner58b7b082004-04-13 19:43:54 +00001206
Chris Lattner59acc7d2004-12-10 08:02:06 +00001207void SCCPSolver::visitCallSite(CallSite CS) {
1208 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001209 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001210
1211 // The common case is that we aren't tracking the callee, either because we
1212 // are not doing interprocedural analysis or the callee is indirect, or is
1213 // external. Handle these cases first.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001214 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001215CallOverdefined:
1216 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001217 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001218
1219 // Otherwise, if we have a single return value case, and if the function is
1220 // a declaration, maybe we can constant fold it.
1221 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1222 canConstantFoldCallTo(F)) {
1223
1224 SmallVector<Constant*, 8> Operands;
1225 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1226 AI != E; ++AI) {
1227 LatticeVal &State = getValueState(*AI);
1228 if (State.isUndefined())
1229 return; // Operands are not resolved yet.
1230 else if (State.isOverdefined()) {
1231 markOverdefined(I);
1232 return;
1233 }
1234 assert(State.isConstant() && "Unknown state!");
1235 Operands.push_back(State.getConstant());
1236 }
1237
1238 // If we can constant fold this, mark the result of the call as a
1239 // constant.
Nick Lewyckye3f1fb12009-05-28 04:08:10 +00001240 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001241 markConstant(I, C);
1242 return;
1243 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001244 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001245
1246 // Otherwise, we don't know anything about this call, mark it overdefined.
1247 markOverdefined(I);
1248 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001249 }
1250
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001251 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001252 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1253 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001254 // If so, propagate the return value of the callee into this call result.
1255 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001256 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001257 // Check to see if we're tracking this callee, if not, handle it in the
1258 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001259 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1260 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001261 if (TMRVI == TrackedMultipleRetVals.end())
1262 goto CallOverdefined;
Torok Edwin2b6183d2009-10-20 15:15:09 +00001263
1264 // Need to mark as overdefined, otherwise it stays undefined which
1265 // creates extractvalue undef, <idx>
1266 markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001267 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001268 // into this call site. We do this by walking all the uses. Single-index
1269 // ExtractValueInst uses can be tracked; anything more complicated is
1270 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001271 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1272 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001273 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1274 if (EVI->getNumIndices() == 1) {
1275 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001276 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001277 continue;
1278 }
1279 }
1280 // The aggregate value is used in a way not handled here. Assume nothing.
1281 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001282 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001283 } else {
1284 // Otherwise we're not tracking this callee, so handle it in the
1285 // common path above.
1286 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001287 }
1288
1289 // Finally, if this is the first call to the function hit, mark its entry
1290 // block executable.
1291 if (!BBExecutable.count(F->begin()))
1292 MarkBlockExecutable(F->begin());
1293
1294 // Propagate information from this call site into the callee.
1295 CallSite::arg_iterator CAI = CS.arg_begin();
1296 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1297 AI != E; ++AI, ++CAI) {
1298 LatticeVal &IV = ValueState[AI];
Torok Edwinc3384992009-09-24 18:33:42 +00001299 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Torok Edwin30a94e32009-09-24 09:47:18 +00001300 IV.markOverdefined();
1301 continue;
1302 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001303 if (!IV.isOverdefined())
1304 mergeInValue(IV, AI, getValueState(*CAI));
1305 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001306}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001307
Chris Lattner82bec2c2004-11-15 04:44:20 +00001308void SCCPSolver::Solve() {
1309 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001310 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001311 !OverdefinedInstWorkList.empty()) {
Chris Lattner2f096252009-11-02 02:33:50 +00001312 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001313 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001314 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001315 OverdefinedInstWorkList.pop_back();
1316
Dan Gohman87325772009-08-17 15:25:05 +00001317 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001318
Chris Lattner82bec2c2004-11-15 04:44:20 +00001319 // "I" got into the work list because it either made the transition from
1320 // bottom to constant
1321 //
1322 // Anything on this worklist that is overdefined need not be visited
1323 // since all of its users will have already been marked as overdefined
Chris Lattner2f096252009-11-02 02:33:50 +00001324 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001325 //
1326 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1327 UI != E; ++UI)
1328 OperandChangedState(*UI);
1329 }
Chris Lattner2f096252009-11-02 02:33:50 +00001330
1331 // Process the instruction work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001332 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001333 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001334 InstWorkList.pop_back();
1335
Dan Gohman87325772009-08-17 15:25:05 +00001336 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001337
Chris Lattner82bec2c2004-11-15 04:44:20 +00001338 // "I" got into the work list because it either made the transition from
1339 // bottom to constant
1340 //
1341 // Anything on this worklist that is overdefined need not be visited
1342 // since all of its users will have already been marked as overdefined.
Chris Lattner2f096252009-11-02 02:33:50 +00001343 // Update all of the users of this instruction's value.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001344 //
1345 if (!getValueState(I).isOverdefined())
1346 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1347 UI != E; ++UI)
1348 OperandChangedState(*UI);
1349 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001350
Chris Lattner2f096252009-11-02 02:33:50 +00001351 // Process the basic block work list.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001352 while (!BBWorkList.empty()) {
1353 BasicBlock *BB = BBWorkList.back();
1354 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001355
Dan Gohman87325772009-08-17 15:25:05 +00001356 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001357
Chris Lattner82bec2c2004-11-15 04:44:20 +00001358 // Notify all instructions in this basic block that they are newly
1359 // executable.
1360 visit(BB);
1361 }
1362 }
1363}
1364
Chris Lattner3bad2532006-12-20 06:21:33 +00001365/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001366/// that branches on undef values cannot reach any of their successors.
1367/// However, this is not a safe assumption. After we solve dataflow, this
1368/// method should be use to handle this. If this returns true, the solver
1369/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001370///
1371/// This method handles this by finding an unresolved branch and marking it one
1372/// of the edges from the block as being feasible, even though the condition
1373/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1374/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001375/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001376/// constraints on the condition of the branch, as that would impact other users
1377/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001378///
1379/// This scan also checks for values that use undefs, whose results are actually
1380/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1381/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1382/// even if X isn't defined.
1383bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001384 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1385 if (!BBExecutable.count(BB))
1386 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001387
1388 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1389 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001390 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001391
1392 LatticeVal &LV = getValueState(I);
1393 if (!LV.isUndefined()) continue;
1394
1395 // Get the lattice values of the first two operands for use below.
1396 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1397 LatticeVal Op1LV;
1398 if (I->getNumOperands() == 2) {
1399 // If this is a two-operand instruction, and if both operands are
1400 // undefs, the result stays undef.
1401 Op1LV = getValueState(I->getOperand(1));
1402 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1403 continue;
1404 }
1405
1406 // If this is an instructions whose result is defined even if the input is
1407 // not fully defined, propagate the information.
1408 const Type *ITy = I->getType();
1409 switch (I->getOpcode()) {
1410 default: break; // Leave the instruction as an undef.
1411 case Instruction::ZExt:
1412 // After a zero extend, we know the top part is zero. SExt doesn't have
1413 // to be handled here, because we don't know whether the top part is 1's
1414 // or 0's.
1415 assert(Op0LV.isUndefined());
Owen Andersona7235ea2009-07-31 20:28:14 +00001416 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001417 return true;
1418 case Instruction::Mul:
1419 case Instruction::And:
1420 // undef * X -> 0. X could be zero.
1421 // undef & X -> 0. X could be zero.
Owen Andersona7235ea2009-07-31 20:28:14 +00001422 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001423 return true;
1424
1425 case Instruction::Or:
1426 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001427 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001428 markForcedConstant(LV, I,
Owen Andersona7235ea2009-07-31 20:28:14 +00001429 Constant::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001430 else
Owen Andersona7235ea2009-07-31 20:28:14 +00001431 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001432 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001433
1434 case Instruction::SDiv:
1435 case Instruction::UDiv:
1436 case Instruction::SRem:
1437 case Instruction::URem:
1438 // X / undef -> undef. No change.
1439 // X % undef -> undef. No change.
1440 if (Op1LV.isUndefined()) break;
1441
1442 // undef / X -> 0. X could be maxint.
1443 // undef % X -> 0. X could be 1.
Owen Andersona7235ea2009-07-31 20:28:14 +00001444 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001445 return true;
1446
1447 case Instruction::AShr:
1448 // undef >>s X -> undef. No change.
1449 if (Op0LV.isUndefined()) break;
1450
1451 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1452 if (Op0LV.isConstant())
1453 markForcedConstant(LV, I, Op0LV.getConstant());
1454 else
1455 markOverdefined(LV, I);
1456 return true;
1457 case Instruction::LShr:
1458 case Instruction::Shl:
1459 // undef >> X -> undef. No change.
1460 // undef << X -> undef. No change.
1461 if (Op0LV.isUndefined()) break;
1462
1463 // X >> undef -> 0. X could be 0.
1464 // X << undef -> 0. X could be 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001465 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001466 return true;
1467 case Instruction::Select:
1468 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1469 if (Op0LV.isUndefined()) {
1470 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1471 Op1LV = getValueState(I->getOperand(2));
1472 } else if (Op1LV.isUndefined()) {
1473 // c ? undef : undef -> undef. No change.
1474 Op1LV = getValueState(I->getOperand(2));
1475 if (Op1LV.isUndefined())
1476 break;
1477 // Otherwise, c ? undef : x -> x.
1478 } else {
1479 // Leave Op1LV as Operand(1)'s LatticeValue.
1480 }
1481
1482 if (Op1LV.isConstant())
1483 markForcedConstant(LV, I, Op1LV.getConstant());
1484 else
1485 markOverdefined(LV, I);
1486 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001487 case Instruction::Call:
1488 // If a call has an undef result, it is because it is constant foldable
1489 // but one of the inputs was undef. Just force the result to
1490 // overdefined.
1491 markOverdefined(LV, I);
1492 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001493 }
1494 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001495
1496 TerminatorInst *TI = BB->getTerminator();
1497 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1498 if (!BI->isConditional()) continue;
1499 if (!getValueState(BI->getCondition()).isUndefined())
1500 continue;
1501 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001502 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001503 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001504 if (!getValueState(SI->getCondition()).isUndefined())
1505 continue;
1506 } else {
1507 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001508 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001509
Chris Lattner05bb7892008-01-28 00:32:30 +00001510 // If the edge to the second successor isn't thought to be feasible yet,
1511 // mark it so now. We pick the second one so that this goes to some
1512 // enumerated value in a switch instead of going to the default destination.
1513 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001514 continue;
1515
1516 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1517 // and return. This will make other blocks reachable, which will allow new
1518 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001519 markEdgeExecutable(BB, TI->getSuccessor(1));
1520
1521 // This must be a conditional branch of switch on undef. At this point,
1522 // force the old terminator to branch to the first successor. This is
1523 // required because we are now influencing the dataflow of the function with
1524 // the assumption that this edge is taken. If we leave the branch condition
1525 // as undef, then further analysis could think the undef went another way
1526 // leading to an inconsistent set of conclusions.
1527 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001528 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001529 } else {
1530 SwitchInst *SI = cast<SwitchInst>(TI);
1531 SI->setCondition(SI->getCaseValue(1));
1532 }
1533
Chris Lattnerd2d86702006-10-22 05:59:17 +00001534 return true;
1535 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001536
Chris Lattnerd2d86702006-10-22 05:59:17 +00001537 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001538}
1539
Chris Lattner82bec2c2004-11-15 04:44:20 +00001540
1541namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001542 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001543 //
Chris Lattner14051812004-11-15 07:15:04 +00001544 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001545 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001546 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001547 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001548 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001549 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001550
Chris Lattner14051812004-11-15 07:15:04 +00001551 // runOnFunction - Run the Sparse Conditional Constant Propagation
1552 // algorithm, and return true if the function was modified.
1553 //
1554 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001555
Chris Lattner14051812004-11-15 07:15:04 +00001556 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1557 AU.setPreservesCFG();
1558 }
1559 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001560} // end anonymous namespace
1561
Dan Gohman844731a2008-05-13 00:00:25 +00001562char SCCP::ID = 0;
1563static RegisterPass<SCCP>
1564X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001565
Chris Lattner2f096252009-11-02 02:33:50 +00001566// createSCCPPass - This is the public interface to this file.
Chris Lattner82bec2c2004-11-15 04:44:20 +00001567FunctionPass *llvm::createSCCPPass() {
1568 return new SCCP();
1569}
1570
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001571static void DeleteInstructionInBlock(BasicBlock *BB) {
1572 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1573 ++NumDeadBlocks;
1574
1575 // Delete the instructions backwards, as it has a reduced likelihood of
1576 // having to update as many def-use and use-def chains.
1577 while (!isa<TerminatorInst>(BB->begin())) {
1578 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1579
1580 if (!I->use_empty())
1581 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1582 BB->getInstList().erase(I);
1583 ++NumInstRemoved;
1584 }
1585}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001586
Chris Lattner82bec2c2004-11-15 04:44:20 +00001587// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1588// and return true if the function was modified.
1589//
1590bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001591 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001592 SCCPSolver Solver;
1593
1594 // Mark the first block of the function as being executable.
1595 Solver.MarkBlockExecutable(F.begin());
1596
Chris Lattner7e529e42004-11-15 05:45:33 +00001597 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001598 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001599 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001600
Chris Lattner82bec2c2004-11-15 04:44:20 +00001601 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001602 bool ResolvedUndefs = true;
1603 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001604 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001605 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001606 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001607 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001608
Chris Lattner7e529e42004-11-15 05:45:33 +00001609 bool MadeChanges = false;
1610
1611 // If we decided that there are basic blocks that are dead in this function,
1612 // delete their contents now. Note that we cannot actually delete the blocks,
1613 // as we cannot modify the CFG of the function.
1614 //
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001615 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner57939df2007-03-04 04:50:21 +00001616
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001617 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001618 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001619 DeleteInstructionInBlock(BB);
1620 MadeChanges = true;
1621 continue;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001622 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001623
1624 // Iterate over all of the instructions in a function, replacing them with
1625 // constants if we have found them to be of constant values.
1626 //
1627 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1628 Instruction *Inst = BI++;
1629 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1630 continue;
1631
1632 LatticeVal &IV = Values[Inst];
1633 if (!IV.isConstant() && !IV.isUndefined())
1634 continue;
1635
1636 Constant *Const = IV.isConstant()
1637 ? IV.getConstant() : UndefValue::get(Inst->getType());
1638 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1639
1640 // Replaces all of the uses of a variable with uses of the constant.
1641 Inst->replaceAllUsesWith(Const);
1642
1643 // Delete the instruction.
1644 Inst->eraseFromParent();
1645
1646 // Hey, we just changed something!
1647 MadeChanges = true;
1648 ++NumInstRemoved;
1649 }
1650 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001651
1652 return MadeChanges;
1653}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001654
1655namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001656 //===--------------------------------------------------------------------===//
1657 //
1658 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1659 /// Constant Propagation.
1660 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001661 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001662 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001663 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001664 bool runOnModule(Module &M);
1665 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001666} // end anonymous namespace
1667
Dan Gohman844731a2008-05-13 00:00:25 +00001668char IPSCCP::ID = 0;
1669static RegisterPass<IPSCCP>
1670Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1671
Chris Lattner2f096252009-11-02 02:33:50 +00001672// createIPSCCPPass - This is the public interface to this file.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001673ModulePass *llvm::createIPSCCPPass() {
1674 return new IPSCCP();
1675}
1676
1677
1678static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001679 // Delete any dead constantexpr klingons.
1680 GV->removeDeadConstantUsers();
1681
Chris Lattner59acc7d2004-12-10 08:02:06 +00001682 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1683 UI != E; ++UI)
1684 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001685 if (SI->getOperand(0) == GV || SI->isVolatile())
1686 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001687 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1688 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001689 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001690 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001691 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1692 if (LI->isVolatile())
1693 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001694 } else if (isa<BlockAddress>(*UI)) {
1695 // blockaddress doesn't take the address of the function, it takes addr
1696 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001697 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001698 return true;
1699 }
1700 return false;
1701}
1702
1703bool IPSCCP::runOnModule(Module &M) {
1704 SCCPSolver Solver;
1705
1706 // Loop over all functions, marking arguments to those with their addresses
1707 // taken or that are external as overdefined.
1708 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001709 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001710 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001711 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001712 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001713 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1714 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001715 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001716 } else {
1717 Solver.AddTrackedFunction(F);
1718 }
1719
Chris Lattnerdd336d12004-12-11 05:15:59 +00001720 // Loop over global variables. We inform the solver about any internal global
1721 // variables that do not have their 'addresses taken'. If they don't have
1722 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001723 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1724 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001725 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001726 Solver.TrackValueOfGlobalVariable(G);
1727
Chris Lattner59acc7d2004-12-10 08:02:06 +00001728 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001729 bool ResolvedUndefs = true;
1730 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001731 Solver.Solve();
1732
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001733 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001734 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001735 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001736 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001737 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001738
1739 bool MadeChanges = false;
1740
1741 // Iterate over all of the instructions in the module, replacing them with
1742 // constants if we have found them to be of constant values.
1743 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001744 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001745 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001746
Chris Lattner59acc7d2004-12-10 08:02:06 +00001747 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001748 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1749 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001750 if (!AI->use_empty()) {
1751 LatticeVal &IV = Values[AI];
1752 if (IV.isConstant() || IV.isUndefined()) {
1753 Constant *CST = IV.isConstant() ?
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001754 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001755 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Misha Brukmanfd939082005-04-21 23:48:37 +00001756
Chris Lattner59acc7d2004-12-10 08:02:06 +00001757 // Replaces all of the uses of a variable with uses of the
1758 // constant.
1759 AI->replaceAllUsesWith(CST);
1760 ++IPNumArgsElimed;
1761 }
1762 }
1763
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001764 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001765 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001766 DeleteInstructionInBlock(BB);
1767 MadeChanges = true;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001768
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001769 TerminatorInst *TI = BB->getTerminator();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001770 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1771 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001772 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001773 TI->getSuccessor(i)->removePredecessor(BB);
1774 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001775 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001776 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001777 TI->eraseFromParent();
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001778
Chris Lattner864737b2004-12-11 05:32:19 +00001779 if (&*BB != &F->front())
1780 BlocksToErase.push_back(BB);
1781 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001782 new UnreachableInst(M.getContext(), BB);
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001783 continue;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001784 }
Chris Lattnercc4f60b2009-11-02 02:47:51 +00001785
1786 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1787 Instruction *Inst = BI++;
1788 if (Inst->getType()->isVoidTy())
1789 continue;
1790
1791 LatticeVal &IV = Values[Inst];
1792 if (!IV.isConstant() && !IV.isUndefined())
1793 continue;
1794
1795 Constant *Const = IV.isConstant()
1796 ? IV.getConstant() : UndefValue::get(Inst->getType());
1797 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1798
1799 // Replaces all of the uses of a variable with uses of the
1800 // constant.
1801 Inst->replaceAllUsesWith(Const);
1802
1803 // Delete the instruction.
1804 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1805 Inst->eraseFromParent();
1806
1807 // Hey, we just changed something!
1808 MadeChanges = true;
1809 ++IPNumInstRemoved;
1810 }
1811 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001812
1813 // Now that all instructions in the function are constant folded, erase dead
1814 // blocks, because we can now use ConstantFoldTerminator to get rid of
1815 // in-edges.
1816 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1817 // If there are any PHI nodes in this successor, drop entries for BB now.
1818 BasicBlock *DeadBB = BlocksToErase[i];
1819 while (!DeadBB->use_empty()) {
1820 Instruction *I = cast<Instruction>(DeadBB->use_back());
1821 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001822 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001823 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001824 // if this is a branch or switch on undef. Fold it manually as a
1825 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001826#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001827 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1828 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1829 "Branch should be foldable!");
1830 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1831 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1832 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001833 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001834 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001835#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001836
1837 // Make this an uncond branch to the first successor.
1838 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001839 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001840
1841 // Remove entries in successor phi nodes to remove edges.
1842 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1843 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1844
1845 // Remove the old terminator.
1846 TI->eraseFromParent();
1847 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001848 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001849
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001850 // Finally, delete the basic block.
1851 F->getBasicBlockList().erase(DeadBB);
1852 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001853 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001854 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001855
1856 // If we inferred constant or undef return values for a function, we replaced
1857 // all call uses with the inferred value. This means we don't need to bother
1858 // actually returning anything from the function. Replace all return
1859 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001860 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001861 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001862 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001863 E = RV.end(); I != E; ++I)
1864 if (!I->second.isOverdefined() &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001865 !I->first->getReturnType()->isVoidTy()) {
Chris Lattner0417feb2004-12-11 02:53:57 +00001866 Function *F = I->first;
1867 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1868 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1869 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001870 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner0417feb2004-12-11 02:53:57 +00001871 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001872
1873 // If we infered constant or undef values for globals variables, we can delete
1874 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001875 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1876 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001877 E = TG.end(); I != E; ++I) {
1878 GlobalVariable *GV = I->first;
1879 assert(!I->second.isOverdefined() &&
1880 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001881 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001882 while (!GV->use_empty()) {
1883 StoreInst *SI = cast<StoreInst>(GV->use_back());
1884 SI->eraseFromParent();
1885 }
1886 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001887 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001888 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001889
Chris Lattner59acc7d2004-12-10 08:02:06 +00001890 return MadeChanges;
1891}