blob: ed4f7d0da87e5ab76c12dfe62ea455cb11278a1e [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(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
51STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
52STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
53
Chris Lattner0dbfc052002-04-29 21:26:08 +000054namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000055/// LatticeVal class - This class represents the different lattice values that
56/// an LLVM value may occupy. It is a simple class with value semantics.
57///
Chris Lattner3e8b6632009-09-02 06:11:42 +000058class LatticeVal {
Chris Lattner79272202009-11-02 02:20:32 +000059 enum LatticeValueTy {
Chris Lattner3bad2532006-12-20 06:21:33 +000060 /// undefined - This LLVM Value has no known value yet.
61 undefined,
62
63 /// constant - This LLVM Value has a specific constant value.
64 constant,
65
66 /// forcedconstant - This LLVM Value was thought to be undef until
67 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
68 /// with another (different) constant, it goes to overdefined, instead of
69 /// asserting.
70 forcedconstant,
71
72 /// overdefined - This instruction is not known to be constant, and we know
73 /// it has a value.
74 overdefined
Chris Lattner79272202009-11-02 02:20:32 +000075 };
76
77 /// Val: This stores the current lattice value along with the Constant* for
78 /// the constant if this is a 'constant' or 'forcedconstant' value.
79 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Chris Lattner3bad2532006-12-20 06:21:33 +000080
Chris Lattner79272202009-11-02 02:20:32 +000081 LatticeValueTy getLatticeValue() const {
82 return Val.getInt();
83 }
84
Chris Lattner138a1242001-06-27 23:38:11 +000085public:
Chris Lattner79272202009-11-02 02:20:32 +000086 inline LatticeVal() : Val(0, undefined) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000087
Chris Lattner79272202009-11-02 02:20:32 +000088 inline bool isUndefined() const { return getLatticeValue() == undefined; }
89 inline bool isConstant() const {
90 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
91 }
92 inline bool isOverdefined() const { return getLatticeValue() == overdefined; }
93
94 inline Constant *getConstant() const {
95 assert(isConstant() && "Cannot get the constant of a non-constant!");
96 return Val.getPointer();
97 }
98
99 /// markOverdefined - Return true if this is a change in status.
Chris Lattner138a1242001-06-27 23:38:11 +0000100 inline bool markOverdefined() {
Chris Lattner79272202009-11-02 02:20:32 +0000101 if (isOverdefined())
102 return false;
103
104 Val.setInt(overdefined);
105 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000106 }
107
Chris Lattner79272202009-11-02 02:20:32 +0000108 /// markConstant - Return true if this is a change in status.
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000109 inline bool markConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000110 if (isConstant()) {
111 assert(getConstant() == V && "Marking constant with different value");
112 return false;
Chris Lattner138a1242001-06-27 23:38:11 +0000113 }
Chris Lattner79272202009-11-02 02:20:32 +0000114
115 if (isUndefined()) {
116 Val.setInt(constant);
117 assert(V && "Marking constant with NULL");
118 Val.setPointer(V);
119 } else {
120 assert(getLatticeValue() == forcedconstant &&
121 "Cannot move from overdefined to constant!");
122 // Stay at forcedconstant if the constant is the same.
123 if (V == getConstant()) return false;
124
125 // Otherwise, we go to overdefined. Assumptions made based on the
126 // forced value are possibly wrong. Assuming this is another constant
127 // could expose a contradiction.
128 Val.setInt(overdefined);
129 }
130 return true;
Chris Lattner138a1242001-06-27 23:38:11 +0000131 }
132
Chris Lattner3bad2532006-12-20 06:21:33 +0000133 inline void markForcedConstant(Constant *V) {
Chris Lattner79272202009-11-02 02:20:32 +0000134 assert(isUndefined() && "Can't force a defined value!");
135 Val.setInt(forcedconstant);
136 Val.setPointer(V);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000137 }
Chris Lattner138a1242001-06-27 23:38:11 +0000138};
139
Chris Lattner138a1242001-06-27 23:38:11 +0000140//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000141//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000142/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
143/// Constant Propagation.
144///
145class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnercf712de2008-08-23 23:36:38 +0000146 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000147 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000148
Chris Lattnerdd336d12004-12-11 05:15:59 +0000149 /// GlobalValue - If we are tracking any values for the contents of a global
150 /// variable, we keep a mapping from the constant accessor to the element of
151 /// the global, to the currently known value. If the value becomes
152 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000153 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000154
Devang Patel7c490d42008-03-11 05:46:42 +0000155 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000156 /// value out of a function, it will have an entry in this map, indicating
157 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000158 DenseMap<Function*, LatticeVal> TrackedRetVals;
159
160 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
161 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000162 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000163
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000164 // The reason for two worklists is that overdefined is the lowest state
165 // on the lattice, and moving things to overdefined as fast as possible
166 // makes SCCP converge much faster.
167 // By having a separate worklist, we accomplish this because everything
168 // possibly overdefined will become overdefined at the soonest possible
169 // point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000170 SmallVector<Value*, 64> OverdefinedInstWorkList;
171 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000172
173
Chris Lattnercf712de2008-08-23 23:36:38 +0000174 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000175
Chris Lattner1daee8b2004-01-12 03:57:30 +0000176 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
177 /// overdefined, despite the fact that the PHI node is overdefined.
178 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
179
Chris Lattner16b18fd2003-10-08 16:55:34 +0000180 /// KnownFeasibleEdges - Entries in this set are edges which have already had
181 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000182 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
183 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000184public:
185
Chris Lattner82bec2c2004-11-15 04:44:20 +0000186 /// MarkBlockExecutable - This method can be used by clients to mark all of
187 /// the blocks that are known to be intrinsically live in the processed unit.
188 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000189 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000190 BBExecutable.insert(BB); // Basic block is executable!
191 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000192 }
193
Chris Lattnerdd336d12004-12-11 05:15:59 +0000194 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000195 /// inform the SCCPSolver that it should track loads and stores to the
196 /// specified global variable if it can. This is only legal to call if
197 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000198 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
199 const Type *ElTy = GV->getType()->getElementType();
200 if (ElTy->isFirstClassType()) {
201 LatticeVal &IV = TrackedGlobals[GV];
202 if (!isa<UndefValue>(GV->getInitializer()))
203 IV.markConstant(GV->getInitializer());
204 }
205 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000206
207 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
208 /// and out of the specified function (which cannot have its address taken),
209 /// this method must be called.
210 void AddTrackedFunction(Function *F) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000211 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000212 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000213 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000215 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
216 LatticeVal()));
217 } else
218 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000219 }
220
Chris Lattner82bec2c2004-11-15 04:44:20 +0000221 /// Solve - Solve for constants and executable blocks.
222 ///
223 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000224
Chris Lattner3bad2532006-12-20 06:21:33 +0000225 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000226 /// that branches on undef values cannot reach any of their successors.
227 /// However, this is not a safe assumption. After we solve dataflow, this
228 /// method should be use to handle this. If this returns true, the solver
229 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000230 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000231
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000232 bool isBlockExecutable(BasicBlock *BB) const {
233 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000234 }
235
236 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000237 /// LLVM values to LatticeVals.
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000238 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000239 return ValueState;
240 }
241
Devang Patel7c490d42008-03-11 05:46:42 +0000242 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000243 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000244 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
245 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000246 }
247
Chris Lattnerdd336d12004-12-11 05:15:59 +0000248 /// getTrackedGlobals - Get and return the set of inferred initializers for
249 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000250 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000251 return TrackedGlobals;
252 }
253
Chris Lattner57939df2007-03-04 04:50:21 +0000254 inline void markOverdefined(Value *V) {
255 markOverdefined(ValueState[V], V);
256 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000257
Chris Lattner138a1242001-06-27 23:38:11 +0000258private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000259 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000260 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000261 // the users of the instruction are updated later.
262 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000263 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000264 if (IV.markConstant(C)) {
Dan Gohman87325772009-08-17 15:25:05 +0000265 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner59acc7d2004-12-10 08:02:06 +0000266 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000267 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000268 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000269
270 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
271 IV.markForcedConstant(C);
Dan Gohman87325772009-08-17 15:25:05 +0000272 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner3bad2532006-12-20 06:21:33 +0000273 InstWorkList.push_back(V);
274 }
275
Chris Lattner59acc7d2004-12-10 08:02:06 +0000276 inline void markConstant(Value *V, Constant *C) {
277 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000278 }
279
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000280 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000281 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000282 // work list so that the users of the instruction are updated later.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000283 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000284 if (IV.markOverdefined()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000285 DEBUG(errs() << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000286 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000287 errs() << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000288 else
Dan Gohman87325772009-08-17 15:25:05 +0000289 errs() << *V << '\n');
Chris Lattner82bec2c2004-11-15 04:44:20 +0000290 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000291 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000292 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000293 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000294
295 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
296 if (IV.isOverdefined() || MergeWithV.isUndefined())
297 return; // Noop.
298 if (MergeWithV.isOverdefined())
299 markOverdefined(IV, V);
300 else if (IV.isUndefined())
301 markConstant(IV, V, MergeWithV.getConstant());
302 else if (IV.getConstant() != MergeWithV.getConstant())
303 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000304 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000305
306 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
307 return mergeInValue(ValueState[V], V, MergeWithV);
308 }
309
Chris Lattner138a1242001-06-27 23:38:11 +0000310
Chris Lattneref36dfd2004-11-15 05:03:30 +0000311 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000312 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000313 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000314 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000315 // Instruction object, then use this accessor to get its value from the map.
316 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000317 inline LatticeVal &getValueState(Value *V) {
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000318 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000319 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000320
Chris Lattner3bad2532006-12-20 06:21:33 +0000321 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000322 if (isa<UndefValue>(V)) {
323 // Nothing to do, remain undefined.
324 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000325 LatticeVal &LV = ValueState[C];
326 LV.markConstant(C); // Constants are constant
327 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000328 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000329 }
Chris Lattner138a1242001-06-27 23:38:11 +0000330 // All others are underdefined by default...
331 return ValueState[V];
332 }
333
Misha Brukmanfd939082005-04-21 23:48:37 +0000334 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000335 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000336 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000337 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
338 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
339 return; // This edge is already known to be executable!
340
341 if (BBExecutable.count(Dest)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000342 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
343 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000344
345 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000346 // feasible that wasn't before. Revisit the PHI nodes in the block
347 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000348 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
349 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000350
351 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000352 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000353 }
Chris Lattner138a1242001-06-27 23:38:11 +0000354 }
355
Chris Lattner82bec2c2004-11-15 04:44:20 +0000356 // getFeasibleSuccessors - Return a vector of booleans to indicate which
357 // successors are reachable from a given terminator instruction.
358 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000359 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000360
361 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
362 // block to the 'To' basic block is currently feasible...
363 //
364 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
365
366 // OperandChangedState - This method is invoked on all of the users of an
367 // instruction that was just changed state somehow.... Based on this
368 // information, we need to update the specified user of this instruction.
369 //
370 void OperandChangedState(User *U) {
371 // Only instructions use other variable values!
372 Instruction &I = cast<Instruction>(*U);
373 if (BBExecutable.count(I.getParent())) // Inst is executable?
374 visit(I);
375 }
376
377private:
378 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000379
Misha Brukmanfd939082005-04-21 23:48:37 +0000380 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000381 // operand made a transition, or the instruction is newly executable. Change
382 // the value type of I to reflect these changes if appropriate.
383 //
Chris Lattner7e708292002-06-25 16:13:24 +0000384 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000385
386 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000387 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000388 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000389
Chris Lattnerb8047602002-08-14 17:53:45 +0000390 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000391 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000392 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000393 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000394 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000395 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000396 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000397 void visitExtractValueInst(ExtractValueInst &EVI);
398 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000399
400 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000401 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000402 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000403 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez66284e02009-10-24 04:23:03 +0000404 void visitCallInst (CallInst &I) {
405 if (isFreeCall(&I))
406 return;
Chris Lattner32c0d222009-09-27 21:35:11 +0000407 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000408 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000409 void visitInvokeInst (InvokeInst &II) {
410 visitCallSite(CallSite::get(&II));
411 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000412 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000413 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000414 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000415 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandez7b929da2009-10-23 21:09:37 +0000416 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000417 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
418 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000419
Chris Lattner7e708292002-06-25 16:13:24 +0000420 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000421 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnerbdff5482009-08-23 04:37:46 +0000422 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000423 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000424 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000425};
Chris Lattnerf6293092002-07-23 18:06:35 +0000426
Duncan Sandse2abf122007-07-20 08:56:21 +0000427} // end anonymous namespace
428
429
Chris Lattnerb9a66342002-05-02 21:44:00 +0000430// getFeasibleSuccessors - Return a vector of booleans to indicate which
431// successors are reachable from a given terminator instruction.
432//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000433void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000434 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000435 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000436 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000437 if (BI->isUnconditional()) {
438 Succs[0] = true;
Chris Lattnerea0db072009-11-02 02:30:06 +0000439 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000440 }
Chris Lattnerea0db072009-11-02 02:30:06 +0000441
442 LatticeVal &BCValue = getValueState(BI->getCondition());
443 if (BCValue.isOverdefined() ||
444 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
445 // Overdefined condition variables, and branches on unfoldable constant
446 // conditions, mean the branch could go either way.
447 Succs[0] = Succs[1] = true;
448 return;
449 }
450
451 // Constant condition variables mean the branch can only go a single way.
452 Succs[cast<ConstantInt>(BCValue.getConstant())->isZero()] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000453 return;
454 }
455
456 if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000457 // Invoke instructions successors are always executable.
458 Succs[0] = Succs[1] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000459 return;
460 }
461
462 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000463 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000464 if (SCValue.isOverdefined() || // Overdefined condition?
465 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000466 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000467 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner3a73c9e2008-05-10 23:56:54 +0000468 } else if (SCValue.isConstant())
469 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000470 return;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000471 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000472
473 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
474 if (isa<IndirectBrInst>(&TI)) {
475 // Just mark all destinations executable!
476 Succs.assign(TI.getNumSuccessors(), true);
477 return;
478 }
479
480#ifndef NDEBUG
481 errs() << "Unknown terminator instruction: " << TI << '\n';
482#endif
483 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000484}
485
486
Chris Lattner59f0ce22002-05-02 21:18:01 +0000487// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
488// block to the 'To' basic block is currently feasible...
489//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000490bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000491 assert(BBExecutable.count(To) && "Dest should always be alive!");
492
493 // Make sure the source basic block is executable!!
494 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000495
Chris Lattnerb9a66342002-05-02 21:44:00 +0000496 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000497 TerminatorInst *TI = From->getTerminator();
498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
499 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000500 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000501
502 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000503
Chris Lattnerea0db072009-11-02 02:30:06 +0000504 // Overdefined condition variables mean the branch could go either way,
505 // undef conditions mean that neither edge is feasible yet.
506 if (!BCValue.isConstant())
507 return BCValue.isOverdefined();
508
509 // Not branching on an evaluatable constant?
510 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
511
512 // Constant condition variables mean the branch can only go a single way.
513 bool CondIsFalse = cast<ConstantInt>(BCValue.getConstant())->isZero();
514 return BI->getSuccessor(CondIsFalse) == To;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000515 }
516
517 // Invoke instructions successors are always executable.
518 if (isa<InvokeInst>(TI))
Chris Lattner7d275f42003-10-08 15:47:41 +0000519 return true;
Chris Lattner4c0236f2009-10-29 01:21:20 +0000520
521 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000522 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000523 if (SCValue.isOverdefined()) { // Overdefined condition?
524 // All destinations are executable!
525 return true;
526 } else if (SCValue.isConstant()) {
527 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000528 if (!isa<ConstantInt>(CPV))
529 return true; // not a foldable constant?
530
Chris Lattner7d275f42003-10-08 15:47:41 +0000531 // Make sure to skip the "default value" which isn't a value
532 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
533 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
534 return SI->getSuccessor(i) == To;
535
536 // Constant value not equal to any of the branches... must execute
537 // default branch then...
538 return SI->getDefaultDest() == To;
539 }
540 return false;
Chris Lattner7d275f42003-10-08 15:47:41 +0000541 }
Chris Lattner4c0236f2009-10-29 01:21:20 +0000542
543 // Just mark all destinations executable!
544 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
545 if (isa<IndirectBrInst>(&TI))
546 return true;
547
548#ifndef NDEBUG
549 errs() << "Unknown terminator instruction: " << *TI << '\n';
550#endif
551 llvm_unreachable(0);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000552}
Chris Lattner138a1242001-06-27 23:38:11 +0000553
Chris Lattner2a632552002-04-18 15:13:15 +0000554// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000555// operand made a transition, or the instruction is newly executable. Change
556// the value type of I to reflect these changes if appropriate. This method
557// makes sure to do the following actions:
558//
559// 1. If a phi node merges two constants in, and has conflicting value coming
560// from different branches, or if the PHI node merges in an overdefined
561// value, then the PHI node becomes overdefined.
562// 2. If a phi node merges only constants in, and they all agree on value, the
563// PHI node becomes a constant value equal to that.
564// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
565// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
566// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
567// 6. If a conditional branch has a value that is constant, make the selected
568// destination executable
569// 7. If a conditional branch has a value that is overdefined, make all
570// successors executable.
571//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000572void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000573 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000574 if (PNIV.isOverdefined()) {
575 // There may be instructions using this PHI node that are not overdefined
576 // themselves. If so, make sure that they know that the PHI node operand
577 // changed.
578 std::multimap<PHINode*, Instruction*>::iterator I, E;
579 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
580 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000581 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000582 for (; I != E; ++I) Users.push_back(I->second);
583 while (!Users.empty()) {
584 visit(Users.back());
585 Users.pop_back();
586 }
587 }
588 return; // Quick exit
589 }
Chris Lattner138a1242001-06-27 23:38:11 +0000590
Chris Lattnera2f652d2004-03-16 19:49:59 +0000591 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
592 // and slow us down a lot. Just mark them overdefined.
593 if (PN.getNumIncomingValues() > 64) {
594 markOverdefined(PNIV, &PN);
595 return;
596 }
597
Chris Lattner2a632552002-04-18 15:13:15 +0000598 // Look at all of the executable operands of the PHI node. If any of them
599 // are overdefined, the PHI becomes overdefined as well. If they are all
600 // constant, and they agree with each other, the PHI becomes the identical
601 // constant. If they are constant and don't agree, the PHI is overdefined.
602 // If there are no executable operands, the PHI remains undefined.
603 //
Chris Lattner9de28282003-04-25 02:50:03 +0000604 Constant *OperandVal = 0;
605 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000606 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000607 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000608
Chris Lattner7e708292002-06-25 16:13:24 +0000609 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000610 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnercf712de2008-08-23 23:36:38 +0000611 markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000612 return;
613 }
614
Chris Lattner9de28282003-04-25 02:50:03 +0000615 if (OperandVal == 0) { // Grab the first value...
616 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000617 } else { // Another value is being merged in!
618 // There is already a reachable operand. If we conflict with it,
619 // then the PHI node becomes overdefined. If we agree with it, we
620 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000621
Chris Lattner2a632552002-04-18 15:13:15 +0000622 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000623 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000624 // Yes there is. This means the PHI node is not constant.
625 // You must be overdefined poor PHI.
626 //
Chris Lattnercf712de2008-08-23 23:36:38 +0000627 markOverdefined(&PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000628 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000629 }
Chris Lattner138a1242001-06-27 23:38:11 +0000630 }
631 }
Chris Lattner138a1242001-06-27 23:38:11 +0000632 }
633
Chris Lattner2a632552002-04-18 15:13:15 +0000634 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000635 // arguments that agree with each other(and OperandVal is the constant) or
636 // OperandVal is null because there are no defined incoming arguments. If
637 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000638 //
Chris Lattner9de28282003-04-25 02:50:03 +0000639 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000640 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000641}
642
Chris Lattner59acc7d2004-12-10 08:02:06 +0000643void SCCPSolver::visitReturnInst(ReturnInst &I) {
644 if (I.getNumOperands() == 0) return; // Ret void
645
Chris Lattner59acc7d2004-12-10 08:02:06 +0000646 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000647 // If we are tracking the return value of this function, merge it in.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000648 if (!F->hasLocalLinkage())
Devang Patel7c490d42008-03-11 05:46:42 +0000649 return;
650
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000651 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000652 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000653 TrackedRetVals.find(F);
654 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000655 !TFRVI->second.isOverdefined()) {
656 LatticeVal &IV = getValueState(I.getOperand(0));
657 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000658 return;
659 }
660 }
661
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000662 // Handle functions that return multiple values.
663 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
664 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000665 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000666 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
667 if (It == TrackedMultipleRetVals.end()) break;
668 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000669 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000670 } else if (!TrackedMultipleRetVals.empty() &&
671 I.getNumOperands() == 1 &&
672 isa<StructType>(I.getOperand(0)->getType())) {
673 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
674 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000675 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000676 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
677 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000678 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000679 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000680 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000681 }
682}
683
Chris Lattner82bec2c2004-11-15 04:44:20 +0000684void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000685 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000686 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000687
Chris Lattner16b18fd2003-10-08 16:55:34 +0000688 BasicBlock *BB = TI.getParent();
689
Chris Lattnerb9a66342002-05-02 21:44:00 +0000690 // Mark all feasible successors executable...
691 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000692 if (SuccFeasible[i])
693 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000694}
695
Chris Lattner82bec2c2004-11-15 04:44:20 +0000696void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000697 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000698 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000699 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000700 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000701 else if (VState.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000702 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Reid Spencer4da49122006-12-12 05:05:00 +0000703 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000704}
705
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000706void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000707 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000708
Dan Gohman60ea2682008-06-20 16:41:17 +0000709 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000710 if (isa<UndefValue>(Aggr))
711 return;
712
713 // Currently only handle single-index extractvalues.
714 if (EVI.getNumIndices() != 1) {
715 markOverdefined(&EVI);
716 return;
717 }
718
719 Function *F = 0;
720 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
721 F = CI->getCalledFunction();
722 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
723 F = II->getCalledFunction();
724
725 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
726 // result back!
727 if (F == 0 || TrackedMultipleRetVals.empty()) {
728 markOverdefined(&EVI);
729 return;
730 }
731
Chris Lattnercf712de2008-08-23 23:36:38 +0000732 // See if we are tracking the result of the callee. If not tracking this
733 // function (for example, it is a declaration) just move to overdefined.
734 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000735 markOverdefined(&EVI);
736 return;
737 }
738
739 // Otherwise, the value will be merged in here as a result of CallSite
740 // handling.
741}
742
743void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000744 Value *Aggr = IVI.getAggregateOperand();
745 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000746
Dan Gohman60ea2682008-06-20 16:41:17 +0000747 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000748 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000749 return;
750
751 // Currently only handle single-index insertvalues.
752 if (IVI.getNumIndices() != 1) {
753 markOverdefined(&IVI);
754 return;
755 }
Dan Gohmandfaceb42008-06-20 16:39:44 +0000756
757 // Currently only handle insertvalue instructions that are in a single-use
758 // chain that builds up a return value.
759 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
760 if (!TmpIVI->hasOneUse()) {
761 markOverdefined(&IVI);
762 return;
763 }
764 const Value *V = *TmpIVI->use_begin();
765 if (isa<ReturnInst>(V))
766 break;
767 TmpIVI = dyn_cast<InsertValueInst>(V);
768 if (!TmpIVI) {
769 markOverdefined(&IVI);
770 return;
771 }
772 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000773
774 // See if we are tracking the result of the callee.
775 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000776 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000777 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
778
779 // Merge in the inserted member value.
780 if (It != TrackedMultipleRetVals.end())
781 mergeInValue(It->second, F, getValueState(Val));
782
Dan Gohman60ea2682008-06-20 16:41:17 +0000783 // Mark the aggregate result of the IVI overdefined; any tracking that we do
784 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000785 markOverdefined(&IVI);
786}
787
Chris Lattner82bec2c2004-11-15 04:44:20 +0000788void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000789 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000790 if (CondValue.isUndefined())
791 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000792 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000793 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000794 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000795 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000796 return;
797 }
798 }
799
800 // Otherwise, the condition is overdefined or a constant we can't evaluate.
801 // See if we can produce something better than overdefined based on the T/F
802 // value.
803 LatticeVal &TVal = getValueState(I.getTrueValue());
804 LatticeVal &FVal = getValueState(I.getFalseValue());
805
806 // select ?, C, C -> C.
807 if (TVal.isConstant() && FVal.isConstant() &&
808 TVal.getConstant() == FVal.getConstant()) {
809 markConstant(&I, FVal.getConstant());
810 return;
811 }
812
813 if (TVal.isUndefined()) { // select ?, undef, X -> X.
814 mergeInValue(&I, FVal);
815 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
816 mergeInValue(&I, TVal);
817 } else {
818 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000819 }
820}
821
Chris Lattner2a632552002-04-18 15:13:15 +0000822// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000823void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000824 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000825 if (IV.isOverdefined()) return;
826
Chris Lattneref36dfd2004-11-15 05:03:30 +0000827 LatticeVal &V1State = getValueState(I.getOperand(0));
828 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000829
Chris Lattner2a632552002-04-18 15:13:15 +0000830 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000831 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
832 // operand is overdefined.
833 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
834 LatticeVal *NonOverdefVal = 0;
835 if (!V1State.isOverdefined()) {
836 NonOverdefVal = &V1State;
837 } else if (!V2State.isOverdefined()) {
838 NonOverdefVal = &V2State;
839 }
840
841 if (NonOverdefVal) {
842 if (NonOverdefVal->isUndefined()) {
843 // Could annihilate value.
844 if (I.getOpcode() == Instruction::And)
Owen Andersona7235ea2009-07-31 20:28:14 +0000845 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000846 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000847 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000848 else
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000849 markConstant(IV, &I,
Owen Andersona7235ea2009-07-31 20:28:14 +0000850 Constant::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000851 return;
852 } else {
853 if (I.getOpcode() == Instruction::And) {
854 if (NonOverdefVal->getConstant()->isNullValue()) {
855 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000856 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000857 }
858 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000859 if (ConstantInt *CI =
860 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000861 if (CI->isAllOnesValue()) {
862 markConstant(IV, &I, NonOverdefVal->getConstant());
863 return; // X or -1 = -1
864 }
865 }
866 }
867 }
868 }
869
870
Chris Lattner1daee8b2004-01-12 03:57:30 +0000871 // If both operands are PHI nodes, it is possible that this instruction has
872 // a constant value, despite the fact that the PHI node doesn't. Check for
873 // this condition now.
874 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
875 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
876 if (PN1->getParent() == PN2->getParent()) {
877 // Since the two PHI nodes are in the same basic block, they must have
878 // entries for the same predecessors. Walk the predecessor list, and
879 // if all of the incoming values are constants, and the result of
880 // evaluating this expression with all incoming value pairs is the
881 // same, then this expression is a constant even though the PHI node
882 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000883 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000884 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000885 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000886 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000887 LatticeVal &In2 =
888 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000889
890 if (In1.isOverdefined() || In2.isOverdefined()) {
891 Result.markOverdefined();
892 break; // Cannot fold this operation over the PHI nodes!
893 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000894 Constant *V =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000895 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000896 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000897 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000898 Result.markConstant(V);
899 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000900 Result.markOverdefined();
901 break;
902 }
903 }
904 }
905
906 // If we found a constant value here, then we know the instruction is
907 // constant despite the fact that the PHI nodes are overdefined.
908 if (Result.isConstant()) {
909 markConstant(IV, &I, Result.getConstant());
910 // Remember that this instruction is virtually using the PHI node
911 // operands.
912 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
913 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
914 return;
915 } else if (Result.isUndefined()) {
916 return;
917 }
918
919 // Okay, this really is overdefined now. Since we might have
920 // speculatively thought that this was not overdefined before, and
921 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
922 // make sure to clean out any entries that we put there, for
923 // efficiency.
924 std::multimap<PHINode*, Instruction*>::iterator It, E;
925 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
926 while (It != E) {
927 if (It->second == &I) {
928 UsersOfOverdefinedPHIs.erase(It++);
929 } else
930 ++It;
931 }
932 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
933 while (It != E) {
934 if (It->second == &I) {
935 UsersOfOverdefinedPHIs.erase(It++);
936 } else
937 ++It;
938 }
939 }
940
941 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000942 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000943 markConstant(IV, &I,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000944 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000945 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000946 }
947}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000948
Reid Spencere4d87aa2006-12-23 06:05:41 +0000949// Handle ICmpInst instruction...
950void SCCPSolver::visitCmpInst(CmpInst &I) {
951 LatticeVal &IV = ValueState[&I];
952 if (IV.isOverdefined()) return;
953
954 LatticeVal &V1State = getValueState(I.getOperand(0));
955 LatticeVal &V2State = getValueState(I.getOperand(1));
956
957 if (V1State.isOverdefined() || V2State.isOverdefined()) {
958 // If both operands are PHI nodes, it is possible that this instruction has
959 // a constant value, despite the fact that the PHI node doesn't. Check for
960 // this condition now.
961 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
962 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
963 if (PN1->getParent() == PN2->getParent()) {
964 // Since the two PHI nodes are in the same basic block, they must have
965 // entries for the same predecessors. Walk the predecessor list, and
966 // if all of the incoming values are constants, and the result of
967 // evaluating this expression with all incoming value pairs is the
968 // same, then this expression is a constant even though the PHI node
969 // is not a constant!
970 LatticeVal Result;
971 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
972 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
973 BasicBlock *InBlock = PN1->getIncomingBlock(i);
974 LatticeVal &In2 =
975 getValueState(PN2->getIncomingValueForBlock(InBlock));
976
977 if (In1.isOverdefined() || In2.isOverdefined()) {
978 Result.markOverdefined();
979 break; // Cannot fold this operation over the PHI nodes!
980 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000981 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000982 In1.getConstant(),
983 In2.getConstant());
984 if (Result.isUndefined())
985 Result.markConstant(V);
986 else if (Result.isConstant() && Result.getConstant() != V) {
987 Result.markOverdefined();
988 break;
989 }
990 }
991 }
992
993 // If we found a constant value here, then we know the instruction is
994 // constant despite the fact that the PHI nodes are overdefined.
995 if (Result.isConstant()) {
996 markConstant(IV, &I, Result.getConstant());
997 // Remember that this instruction is virtually using the PHI node
998 // operands.
999 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1000 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1001 return;
1002 } else if (Result.isUndefined()) {
1003 return;
1004 }
1005
1006 // Okay, this really is overdefined now. Since we might have
1007 // speculatively thought that this was not overdefined before, and
1008 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1009 // make sure to clean out any entries that we put there, for
1010 // efficiency.
1011 std::multimap<PHINode*, Instruction*>::iterator It, E;
1012 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
1013 while (It != E) {
1014 if (It->second == &I) {
1015 UsersOfOverdefinedPHIs.erase(It++);
1016 } else
1017 ++It;
1018 }
1019 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1020 while (It != E) {
1021 if (It->second == &I) {
1022 UsersOfOverdefinedPHIs.erase(It++);
1023 } else
1024 ++It;
1025 }
1026 }
1027
1028 markOverdefined(IV, &I);
1029 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001030 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001031 V1State.getConstant(),
1032 V2State.getConstant()));
1033 }
1034}
1035
Robert Bocchino56107e22006-01-10 19:05:05 +00001036void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001037 // FIXME : SCCP does not handle vectors properly.
1038 markOverdefined(&I);
1039 return;
1040
1041#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001042 LatticeVal &ValState = getValueState(I.getOperand(0));
1043 LatticeVal &IdxState = getValueState(I.getOperand(1));
1044
1045 if (ValState.isOverdefined() || IdxState.isOverdefined())
1046 markOverdefined(&I);
1047 else if(ValState.isConstant() && IdxState.isConstant())
1048 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1049 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001050#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001051}
1052
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001053void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001054 // FIXME : SCCP does not handle vectors properly.
1055 markOverdefined(&I);
1056 return;
1057#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001058 LatticeVal &ValState = getValueState(I.getOperand(0));
1059 LatticeVal &EltState = getValueState(I.getOperand(1));
1060 LatticeVal &IdxState = getValueState(I.getOperand(2));
1061
1062 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1063 IdxState.isOverdefined())
1064 markOverdefined(&I);
1065 else if(ValState.isConstant() && EltState.isConstant() &&
1066 IdxState.isConstant())
1067 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1068 EltState.getConstant(),
1069 IdxState.getConstant()));
1070 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001071 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001072 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1073 EltState.getConstant(),
1074 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001075#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001076}
1077
Chris Lattner543abdf2006-04-08 01:19:12 +00001078void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001079 // FIXME : SCCP does not handle vectors properly.
1080 markOverdefined(&I);
1081 return;
1082#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001083 LatticeVal &V1State = getValueState(I.getOperand(0));
1084 LatticeVal &V2State = getValueState(I.getOperand(1));
1085 LatticeVal &MaskState = getValueState(I.getOperand(2));
1086
1087 if (MaskState.isUndefined() ||
1088 (V1State.isUndefined() && V2State.isUndefined()))
1089 return; // Undefined output if mask or both inputs undefined.
1090
1091 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1092 MaskState.isOverdefined()) {
1093 markOverdefined(&I);
1094 } else {
1095 // A mix of constant/undef inputs.
1096 Constant *V1 = V1State.isConstant() ?
1097 V1State.getConstant() : UndefValue::get(I.getType());
1098 Constant *V2 = V2State.isConstant() ?
1099 V2State.getConstant() : UndefValue::get(I.getType());
1100 Constant *Mask = MaskState.isConstant() ?
1101 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1102 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1103 }
Devang Patel67a821d2006-12-04 23:54:59 +00001104#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001105}
1106
Chris Lattner2a88bb72002-08-30 23:39:00 +00001107// Handle getelementptr instructions... if all operands are constants then we
1108// can turn this into a getelementptr ConstantExpr.
1109//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001110void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001111 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001112 if (IV.isOverdefined()) return;
1113
Chris Lattnere777ff22007-02-02 20:51:48 +00001114 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001115 Operands.reserve(I.getNumOperands());
1116
1117 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001118 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001119 if (State.isUndefined())
1120 return; // Operands are not resolved yet...
1121 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001122 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001123 return;
1124 }
1125 assert(State.isConstant() && "Unknown state!");
1126 Operands.push_back(State.getConstant());
1127 }
1128
1129 Constant *Ptr = Operands[0];
1130 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1131
Owen Andersonbaf3c402009-07-29 18:55:55 +00001132 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Chris Lattnere777ff22007-02-02 20:51:48 +00001133 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001134}
Brian Gaeked0fde302003-11-11 22:41:34 +00001135
Chris Lattnerdd336d12004-12-11 05:15:59 +00001136void SCCPSolver::visitStoreInst(Instruction &SI) {
1137 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1138 return;
1139 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001140 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001141 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1142
1143 // Get the value we are storing into the global.
1144 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1145
1146 mergeInValue(I->second, GV, PtrVal);
1147 if (I->second.isOverdefined())
1148 TrackedGlobals.erase(I); // No need to keep tracking this!
1149}
1150
1151
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001152// Handle load instructions. If the operand is a constant pointer to a constant
1153// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001154void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001155 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001156 if (IV.isOverdefined()) return;
1157
Chris Lattneref36dfd2004-11-15 05:03:30 +00001158 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001159 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1160 if (PtrVal.isConstant() && !I.isVolatile()) {
1161 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001162 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +00001163 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001164 // load null -> null
Owen Andersona7235ea2009-07-31 20:28:14 +00001165 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerc76d8032004-03-07 22:16:24 +00001166 return;
1167 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001168
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001169 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001170 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1171 if (GV->isConstant()) {
Duncan Sands64da9402009-03-21 21:27:31 +00001172 if (GV->hasDefinitiveInitializer()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001173 markConstant(IV, &I, GV->getInitializer());
1174 return;
1175 }
1176 } else if (!TrackedGlobals.empty()) {
1177 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001178 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001179 TrackedGlobals.find(GV);
1180 if (It != TrackedGlobals.end()) {
1181 mergeInValue(IV, &I, It->second);
1182 return;
1183 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001184 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001185 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001186
1187 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1189 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001190 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +00001191 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Jeff Cohen9d809302005-04-23 21:38:35 +00001192 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +00001193 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001194 markConstant(IV, &I, V);
1195 return;
1196 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001197 }
1198
1199 // Otherwise we cannot say for certain what value this load will produce.
1200 // Bail out.
1201 markOverdefined(IV, &I);
1202}
Chris Lattner58b7b082004-04-13 19:43:54 +00001203
Chris Lattner59acc7d2004-12-10 08:02:06 +00001204void SCCPSolver::visitCallSite(CallSite CS) {
1205 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001206 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001207
1208 // The common case is that we aren't tracking the callee, either because we
1209 // are not doing interprocedural analysis or the callee is indirect, or is
1210 // external. Handle these cases first.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001211 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001212CallOverdefined:
1213 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001214 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001215
1216 // Otherwise, if we have a single return value case, and if the function is
1217 // a declaration, maybe we can constant fold it.
1218 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1219 canConstantFoldCallTo(F)) {
1220
1221 SmallVector<Constant*, 8> Operands;
1222 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1223 AI != E; ++AI) {
1224 LatticeVal &State = getValueState(*AI);
1225 if (State.isUndefined())
1226 return; // Operands are not resolved yet.
1227 else if (State.isOverdefined()) {
1228 markOverdefined(I);
1229 return;
1230 }
1231 assert(State.isConstant() && "Unknown state!");
1232 Operands.push_back(State.getConstant());
1233 }
1234
1235 // If we can constant fold this, mark the result of the call as a
1236 // constant.
Nick Lewyckye3f1fb12009-05-28 04:08:10 +00001237 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001238 markConstant(I, C);
1239 return;
1240 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001241 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001242
1243 // Otherwise, we don't know anything about this call, mark it overdefined.
1244 markOverdefined(I);
1245 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001246 }
1247
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001248 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001249 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1250 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001251 // If so, propagate the return value of the callee into this call result.
1252 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001253 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001254 // Check to see if we're tracking this callee, if not, handle it in the
1255 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001256 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1257 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001258 if (TMRVI == TrackedMultipleRetVals.end())
1259 goto CallOverdefined;
Torok Edwin2b6183d2009-10-20 15:15:09 +00001260
1261 // Need to mark as overdefined, otherwise it stays undefined which
1262 // creates extractvalue undef, <idx>
1263 markOverdefined(I);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001264 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001265 // into this call site. We do this by walking all the uses. Single-index
1266 // ExtractValueInst uses can be tracked; anything more complicated is
1267 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001268 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1269 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001270 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1271 if (EVI->getNumIndices() == 1) {
1272 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001273 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001274 continue;
1275 }
1276 }
1277 // The aggregate value is used in a way not handled here. Assume nothing.
1278 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001279 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001280 } else {
1281 // Otherwise we're not tracking this callee, so handle it in the
1282 // common path above.
1283 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001284 }
1285
1286 // Finally, if this is the first call to the function hit, mark its entry
1287 // block executable.
1288 if (!BBExecutable.count(F->begin()))
1289 MarkBlockExecutable(F->begin());
1290
1291 // Propagate information from this call site into the callee.
1292 CallSite::arg_iterator CAI = CS.arg_begin();
1293 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1294 AI != E; ++AI, ++CAI) {
1295 LatticeVal &IV = ValueState[AI];
Torok Edwinc3384992009-09-24 18:33:42 +00001296 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Torok Edwin30a94e32009-09-24 09:47:18 +00001297 IV.markOverdefined();
1298 continue;
1299 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001300 if (!IV.isOverdefined())
1301 mergeInValue(IV, AI, getValueState(*CAI));
1302 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001303}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001304
Chris Lattner82bec2c2004-11-15 04:44:20 +00001305void SCCPSolver::Solve() {
1306 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001307 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001308 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001309 // Process the instruction work list...
1310 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001311 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001312 OverdefinedInstWorkList.pop_back();
1313
Dan Gohman87325772009-08-17 15:25:05 +00001314 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001315
Chris Lattner82bec2c2004-11-15 04:44:20 +00001316 // "I" got into the work list because it either made the transition from
1317 // bottom to constant
1318 //
1319 // Anything on this worklist that is overdefined need not be visited
1320 // since all of its users will have already been marked as overdefined
1321 // Update all of the users of this instruction's value...
1322 //
1323 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1324 UI != E; ++UI)
1325 OperandChangedState(*UI);
1326 }
1327 // Process the instruction work list...
1328 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001329 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001330 InstWorkList.pop_back();
1331
Dan Gohman87325772009-08-17 15:25:05 +00001332 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001333
Chris Lattner82bec2c2004-11-15 04:44:20 +00001334 // "I" got into the work list because it either made the transition from
1335 // bottom to constant
1336 //
1337 // Anything on this worklist that is overdefined need not be visited
1338 // since all of its users will have already been marked as overdefined.
1339 // Update all of the users of this instruction's value...
1340 //
1341 if (!getValueState(I).isOverdefined())
1342 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1343 UI != E; ++UI)
1344 OperandChangedState(*UI);
1345 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001346
Chris Lattner82bec2c2004-11-15 04:44:20 +00001347 // Process the basic block work list...
1348 while (!BBWorkList.empty()) {
1349 BasicBlock *BB = BBWorkList.back();
1350 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001351
Dan Gohman87325772009-08-17 15:25:05 +00001352 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001353
Chris Lattner82bec2c2004-11-15 04:44:20 +00001354 // Notify all instructions in this basic block that they are newly
1355 // executable.
1356 visit(BB);
1357 }
1358 }
1359}
1360
Chris Lattner3bad2532006-12-20 06:21:33 +00001361/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001362/// that branches on undef values cannot reach any of their successors.
1363/// However, this is not a safe assumption. After we solve dataflow, this
1364/// method should be use to handle this. If this returns true, the solver
1365/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001366///
1367/// This method handles this by finding an unresolved branch and marking it one
1368/// of the edges from the block as being feasible, even though the condition
1369/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1370/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001371/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001372/// constraints on the condition of the branch, as that would impact other users
1373/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001374///
1375/// This scan also checks for values that use undefs, whose results are actually
1376/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1377/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1378/// even if X isn't defined.
1379bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001380 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1381 if (!BBExecutable.count(BB))
1382 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001383
1384 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1385 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001386 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001387
1388 LatticeVal &LV = getValueState(I);
1389 if (!LV.isUndefined()) continue;
1390
1391 // Get the lattice values of the first two operands for use below.
1392 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1393 LatticeVal Op1LV;
1394 if (I->getNumOperands() == 2) {
1395 // If this is a two-operand instruction, and if both operands are
1396 // undefs, the result stays undef.
1397 Op1LV = getValueState(I->getOperand(1));
1398 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1399 continue;
1400 }
1401
1402 // If this is an instructions whose result is defined even if the input is
1403 // not fully defined, propagate the information.
1404 const Type *ITy = I->getType();
1405 switch (I->getOpcode()) {
1406 default: break; // Leave the instruction as an undef.
1407 case Instruction::ZExt:
1408 // After a zero extend, we know the top part is zero. SExt doesn't have
1409 // to be handled here, because we don't know whether the top part is 1's
1410 // or 0's.
1411 assert(Op0LV.isUndefined());
Owen Andersona7235ea2009-07-31 20:28:14 +00001412 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001413 return true;
1414 case Instruction::Mul:
1415 case Instruction::And:
1416 // undef * X -> 0. X could be zero.
1417 // undef & X -> 0. X could be zero.
Owen Andersona7235ea2009-07-31 20:28:14 +00001418 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001419 return true;
1420
1421 case Instruction::Or:
1422 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001423 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001424 markForcedConstant(LV, I,
Owen Andersona7235ea2009-07-31 20:28:14 +00001425 Constant::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001426 else
Owen Andersona7235ea2009-07-31 20:28:14 +00001427 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001428 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001429
1430 case Instruction::SDiv:
1431 case Instruction::UDiv:
1432 case Instruction::SRem:
1433 case Instruction::URem:
1434 // X / undef -> undef. No change.
1435 // X % undef -> undef. No change.
1436 if (Op1LV.isUndefined()) break;
1437
1438 // undef / X -> 0. X could be maxint.
1439 // undef % X -> 0. X could be 1.
Owen Andersona7235ea2009-07-31 20:28:14 +00001440 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001441 return true;
1442
1443 case Instruction::AShr:
1444 // undef >>s X -> undef. No change.
1445 if (Op0LV.isUndefined()) break;
1446
1447 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1448 if (Op0LV.isConstant())
1449 markForcedConstant(LV, I, Op0LV.getConstant());
1450 else
1451 markOverdefined(LV, I);
1452 return true;
1453 case Instruction::LShr:
1454 case Instruction::Shl:
1455 // undef >> X -> undef. No change.
1456 // undef << X -> undef. No change.
1457 if (Op0LV.isUndefined()) break;
1458
1459 // X >> undef -> 0. X could be 0.
1460 // X << undef -> 0. X could be 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001461 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001462 return true;
1463 case Instruction::Select:
1464 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1465 if (Op0LV.isUndefined()) {
1466 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1467 Op1LV = getValueState(I->getOperand(2));
1468 } else if (Op1LV.isUndefined()) {
1469 // c ? undef : undef -> undef. No change.
1470 Op1LV = getValueState(I->getOperand(2));
1471 if (Op1LV.isUndefined())
1472 break;
1473 // Otherwise, c ? undef : x -> x.
1474 } else {
1475 // Leave Op1LV as Operand(1)'s LatticeValue.
1476 }
1477
1478 if (Op1LV.isConstant())
1479 markForcedConstant(LV, I, Op1LV.getConstant());
1480 else
1481 markOverdefined(LV, I);
1482 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001483 case Instruction::Call:
1484 // If a call has an undef result, it is because it is constant foldable
1485 // but one of the inputs was undef. Just force the result to
1486 // overdefined.
1487 markOverdefined(LV, I);
1488 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001489 }
1490 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001491
1492 TerminatorInst *TI = BB->getTerminator();
1493 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1494 if (!BI->isConditional()) continue;
1495 if (!getValueState(BI->getCondition()).isUndefined())
1496 continue;
1497 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001498 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesen9bca5832008-05-23 01:01:31 +00001499 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001500 if (!getValueState(SI->getCondition()).isUndefined())
1501 continue;
1502 } else {
1503 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001504 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001505
Chris Lattner05bb7892008-01-28 00:32:30 +00001506 // If the edge to the second successor isn't thought to be feasible yet,
1507 // mark it so now. We pick the second one so that this goes to some
1508 // enumerated value in a switch instead of going to the default destination.
1509 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001510 continue;
1511
1512 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1513 // and return. This will make other blocks reachable, which will allow new
1514 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001515 markEdgeExecutable(BB, TI->getSuccessor(1));
1516
1517 // This must be a conditional branch of switch on undef. At this point,
1518 // force the old terminator to branch to the first successor. This is
1519 // required because we are now influencing the dataflow of the function with
1520 // the assumption that this edge is taken. If we leave the branch condition
1521 // as undef, then further analysis could think the undef went another way
1522 // leading to an inconsistent set of conclusions.
1523 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattnerea0db072009-11-02 02:30:06 +00001524 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner05bb7892008-01-28 00:32:30 +00001525 } else {
1526 SwitchInst *SI = cast<SwitchInst>(TI);
1527 SI->setCondition(SI->getCaseValue(1));
1528 }
1529
Chris Lattnerd2d86702006-10-22 05:59:17 +00001530 return true;
1531 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001532
Chris Lattnerd2d86702006-10-22 05:59:17 +00001533 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001534}
1535
Chris Lattner82bec2c2004-11-15 04:44:20 +00001536
1537namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001538 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001539 //
Chris Lattner14051812004-11-15 07:15:04 +00001540 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001541 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001542 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001543 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001544 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001545 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001546
Chris Lattner14051812004-11-15 07:15:04 +00001547 // runOnFunction - Run the Sparse Conditional Constant Propagation
1548 // algorithm, and return true if the function was modified.
1549 //
1550 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001551
Chris Lattner14051812004-11-15 07:15:04 +00001552 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1553 AU.setPreservesCFG();
1554 }
1555 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001556} // end anonymous namespace
1557
Dan Gohman844731a2008-05-13 00:00:25 +00001558char SCCP::ID = 0;
1559static RegisterPass<SCCP>
1560X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001561
1562// createSCCPPass - This is the public interface to this file...
1563FunctionPass *llvm::createSCCPPass() {
1564 return new SCCP();
1565}
1566
1567
Chris Lattner82bec2c2004-11-15 04:44:20 +00001568// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1569// and return true if the function was modified.
1570//
1571bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001572 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001573 SCCPSolver Solver;
1574
1575 // Mark the first block of the function as being executable.
1576 Solver.MarkBlockExecutable(F.begin());
1577
Chris Lattner7e529e42004-11-15 05:45:33 +00001578 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001579 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001580 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001581
Chris Lattner82bec2c2004-11-15 04:44:20 +00001582 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001583 bool ResolvedUndefs = true;
1584 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001585 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001586 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001587 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001588 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001589
Chris Lattner7e529e42004-11-15 05:45:33 +00001590 bool MadeChanges = false;
1591
1592 // If we decided that there are basic blocks that are dead in this function,
1593 // delete their contents now. Note that we cannot actually delete the blocks,
1594 // as we cannot modify the CFG of the function.
1595 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001596 SmallVector<Instruction*, 512> Insts;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001597 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner57939df2007-03-04 04:50:21 +00001598
Chris Lattner7e529e42004-11-15 05:45:33 +00001599 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001600 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001601 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001602 ++NumDeadBlocks;
1603
Chris Lattner7e529e42004-11-15 05:45:33 +00001604 // Delete the instructions backwards, as it has a reduced likelihood of
1605 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001606 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1607 I != E; ++I)
1608 Insts.push_back(I);
1609 while (!Insts.empty()) {
1610 Instruction *I = Insts.back();
1611 Insts.pop_back();
1612 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001613 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner7e529e42004-11-15 05:45:33 +00001614 BB->getInstList().erase(I);
1615 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001616 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001617 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001618 } else {
1619 // Iterate over all of the instructions in a function, replacing them with
1620 // constants if we have found them to be of constant values.
1621 //
1622 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1623 Instruction *Inst = BI++;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001624 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
Chris Lattnerf4023a12008-04-24 00:16:28 +00001625 continue;
1626
1627 LatticeVal &IV = Values[Inst];
1628 if (!IV.isConstant() && !IV.isUndefined())
1629 continue;
1630
1631 Constant *Const = IV.isConstant()
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001632 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001633 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001634
Chris Lattnerf4023a12008-04-24 00:16:28 +00001635 // Replaces all of the uses of a variable with uses of the constant.
1636 Inst->replaceAllUsesWith(Const);
1637
1638 // Delete the instruction.
1639 Inst->eraseFromParent();
1640
1641 // Hey, we just changed something!
1642 MadeChanges = true;
1643 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001644 }
1645 }
1646
1647 return MadeChanges;
1648}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001649
1650namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001651 //===--------------------------------------------------------------------===//
1652 //
1653 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1654 /// Constant Propagation.
1655 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001656 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001657 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001658 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001659 bool runOnModule(Module &M);
1660 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001661} // end anonymous namespace
1662
Dan Gohman844731a2008-05-13 00:00:25 +00001663char IPSCCP::ID = 0;
1664static RegisterPass<IPSCCP>
1665Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1666
Chris Lattner59acc7d2004-12-10 08:02:06 +00001667// createIPSCCPPass - This is the public interface to this file...
1668ModulePass *llvm::createIPSCCPPass() {
1669 return new IPSCCP();
1670}
1671
1672
1673static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001674 // Delete any dead constantexpr klingons.
1675 GV->removeDeadConstantUsers();
1676
Chris Lattner59acc7d2004-12-10 08:02:06 +00001677 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1678 UI != E; ++UI)
1679 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001680 if (SI->getOperand(0) == GV || SI->isVolatile())
1681 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001682 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1683 // Make sure we are calling the function, not passing the address.
Chris Lattnerb2710042009-11-01 06:11:53 +00001684 if (UI.getOperandNo() != 0)
Nick Lewyckyaf386132008-11-03 03:49:14 +00001685 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001686 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1687 if (LI->isVolatile())
1688 return true;
Chris Lattnerb2710042009-11-01 06:11:53 +00001689 } else if (isa<BlockAddress>(*UI)) {
1690 // blockaddress doesn't take the address of the function, it takes addr
1691 // of label.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001692 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001693 return true;
1694 }
1695 return false;
1696}
1697
1698bool IPSCCP::runOnModule(Module &M) {
1699 SCCPSolver Solver;
1700
1701 // Loop over all functions, marking arguments to those with their addresses
1702 // taken or that are external as overdefined.
1703 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001704 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001705 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001706 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001707 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001708 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1709 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001710 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001711 } else {
1712 Solver.AddTrackedFunction(F);
1713 }
1714
Chris Lattnerdd336d12004-12-11 05:15:59 +00001715 // Loop over global variables. We inform the solver about any internal global
1716 // variables that do not have their 'addresses taken'. If they don't have
1717 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001718 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1719 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001720 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001721 Solver.TrackValueOfGlobalVariable(G);
1722
Chris Lattner59acc7d2004-12-10 08:02:06 +00001723 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001724 bool ResolvedUndefs = true;
1725 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001726 Solver.Solve();
1727
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001728 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001729 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001730 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001731 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001732 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001733
1734 bool MadeChanges = false;
1735
1736 // Iterate over all of the instructions in the module, replacing them with
1737 // constants if we have found them to be of constant values.
1738 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001739 SmallVector<Instruction*, 512> Insts;
1740 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001741 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001742
Chris Lattner59acc7d2004-12-10 08:02:06 +00001743 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001744 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1745 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001746 if (!AI->use_empty()) {
1747 LatticeVal &IV = Values[AI];
1748 if (IV.isConstant() || IV.isUndefined()) {
1749 Constant *CST = IV.isConstant() ?
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001750 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001751 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Misha Brukmanfd939082005-04-21 23:48:37 +00001752
Chris Lattner59acc7d2004-12-10 08:02:06 +00001753 // Replaces all of the uses of a variable with uses of the
1754 // constant.
1755 AI->replaceAllUsesWith(CST);
1756 ++IPNumArgsElimed;
1757 }
1758 }
1759
1760 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001761 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001762 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001763 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001764
Chris Lattner59acc7d2004-12-10 08:02:06 +00001765 // Delete the instructions backwards, as it has a reduced likelihood of
1766 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001767 TerminatorInst *TI = BB->getTerminator();
1768 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001769 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001770
Chris Lattner59acc7d2004-12-10 08:02:06 +00001771 while (!Insts.empty()) {
1772 Instruction *I = Insts.back();
1773 Insts.pop_back();
1774 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001775 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner59acc7d2004-12-10 08:02:06 +00001776 BB->getInstList().erase(I);
1777 MadeChanges = true;
1778 ++IPNumInstRemoved;
1779 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001780
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001781 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1782 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001783 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001784 TI->getSuccessor(i)->removePredecessor(BB);
1785 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001786 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001787 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001788 BB->getInstList().erase(TI);
1789
Chris Lattner864737b2004-12-11 05:32:19 +00001790 if (&*BB != &F->front())
1791 BlocksToErase.push_back(BB);
1792 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001793 new UnreachableInst(M.getContext(), BB);
Chris Lattner864737b2004-12-11 05:32:19 +00001794
Chris Lattner59acc7d2004-12-10 08:02:06 +00001795 } else {
1796 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1797 Instruction *Inst = BI++;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001798 if (Inst->getType()->isVoidTy())
Chris Lattnereb5f4092008-04-24 00:21:50 +00001799 continue;
1800
1801 LatticeVal &IV = Values[Inst];
1802 if (!IV.isConstant() && !IV.isUndefined())
1803 continue;
1804
1805 Constant *Const = IV.isConstant()
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001806 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001807 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001808
Chris Lattnereb5f4092008-04-24 00:21:50 +00001809 // Replaces all of the uses of a variable with uses of the
1810 // constant.
1811 Inst->replaceAllUsesWith(Const);
1812
1813 // Delete the instruction.
Chris Lattnerd9d46242009-01-14 21:01:16 +00001814 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattnereb5f4092008-04-24 00:21:50 +00001815 Inst->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001816
Chris Lattnereb5f4092008-04-24 00:21:50 +00001817 // Hey, we just changed something!
1818 MadeChanges = true;
1819 ++IPNumInstRemoved;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001820 }
1821 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001822
1823 // Now that all instructions in the function are constant folded, erase dead
1824 // blocks, because we can now use ConstantFoldTerminator to get rid of
1825 // in-edges.
1826 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1827 // If there are any PHI nodes in this successor, drop entries for BB now.
1828 BasicBlock *DeadBB = BlocksToErase[i];
1829 while (!DeadBB->use_empty()) {
1830 Instruction *I = cast<Instruction>(DeadBB->use_back());
1831 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001832 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001833 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001834 // if this is a branch or switch on undef. Fold it manually as a
1835 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001836#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001837 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1838 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1839 "Branch should be foldable!");
1840 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1841 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1842 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001843 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001844 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001845#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001846
1847 // Make this an uncond branch to the first successor.
1848 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001849 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001850
1851 // Remove entries in successor phi nodes to remove edges.
1852 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1853 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1854
1855 // Remove the old terminator.
1856 TI->eraseFromParent();
1857 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001858 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001859
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001860 // Finally, delete the basic block.
1861 F->getBasicBlockList().erase(DeadBB);
1862 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001863 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001864 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001865
1866 // If we inferred constant or undef return values for a function, we replaced
1867 // all call uses with the inferred value. This means we don't need to bother
1868 // actually returning anything from the function. Replace all return
1869 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001870 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001871 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001872 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001873 E = RV.end(); I != E; ++I)
1874 if (!I->second.isOverdefined() &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001875 !I->first->getReturnType()->isVoidTy()) {
Chris Lattner0417feb2004-12-11 02:53:57 +00001876 Function *F = I->first;
1877 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1878 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1879 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001880 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner0417feb2004-12-11 02:53:57 +00001881 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001882
1883 // If we infered constant or undef values for globals variables, we can delete
1884 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001885 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1886 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001887 E = TG.end(); I != E; ++I) {
1888 GlobalVariable *GV = I->first;
1889 assert(!I->second.isOverdefined() &&
1890 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001891 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001892 while (!GV->use_empty()) {
1893 StoreInst *SI = cast<StoreInst>(GV->use_back());
1894 SI->eraseFromParent();
1895 }
1896 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001897 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001898 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001899
Chris Lattner59acc7d2004-12-10 08:02:06 +00001900 return MadeChanges;
1901}