blob: b5edf4e058214cb53306fcd3943b17db257544b7 [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//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
Chris Lattneref36dfd2004-11-15 05:03:30 +000024#define DEBUG_TYPE "sccp"
Chris Lattner022103b2002-05-07 20:03:00 +000025#include "llvm/Transforms/Scalar.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000026#include "llvm/Transforms/IPO.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000027#include "llvm/Constants.h"
Chris Lattnerdd336d12004-12-11 05:15:59 +000028#include "llvm/DerivedTypes.h"
Chris Lattner9de28282003-04-25 02:50:03 +000029#include "llvm/Instructions.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000031#include "llvm/Pass.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000032#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanc4b65ea2008-06-20 01:15:44 +000033#include "llvm/Analysis/ValueTracking.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000034#include "llvm/Transforms/Utils/Local.h"
Chris Lattner59acc7d2004-12-10 08:02:06 +000035#include "llvm/Support/CallSite.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000038#include "llvm/Support/InstVisitor.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Chris Lattnerb59673e2007-02-02 20:38:30 +000040#include "llvm/ADT/DenseMap.h"
Chris Lattnercf712de2008-08-23 23:36:38 +000041#include "llvm/ADT/DenseSet.h"
Chris Lattnercc56aad2007-02-02 20:57:39 +000042#include "llvm/ADT/SmallSet.h"
Chris Lattnercd2492e2007-01-30 23:15:19 +000043#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/Statistic.h"
45#include "llvm/ADT/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000046#include <algorithm>
Dan Gohmanc9235d22008-03-21 23:51:57 +000047#include <map>
Chris Lattnerd7456022004-01-09 06:02:20 +000048using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000049
Chris Lattner0e5f4992006-12-19 21:40:18 +000050STATISTIC(NumInstRemoved, "Number of instructions removed");
51STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
52
Nick Lewycky6c36a0f2008-03-08 07:48:41 +000053STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner0e5f4992006-12-19 21:40:18 +000054STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
55STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
56STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
57
Chris Lattner0dbfc052002-04-29 21:26:08 +000058namespace {
Chris Lattner3bad2532006-12-20 06:21:33 +000059/// LatticeVal class - This class represents the different lattice values that
60/// an LLVM value may occupy. It is a simple class with value semantics.
61///
Chris Lattner3e8b6632009-09-02 06:11:42 +000062class LatticeVal {
Misha Brukmanfd939082005-04-21 23:48:37 +000063 enum {
Chris Lattner3bad2532006-12-20 06:21:33 +000064 /// undefined - This LLVM Value has no known value yet.
65 undefined,
66
67 /// constant - This LLVM Value has a specific constant value.
68 constant,
69
70 /// forcedconstant - This LLVM Value was thought to be undef until
71 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
72 /// with another (different) constant, it goes to overdefined, instead of
73 /// asserting.
74 forcedconstant,
75
76 /// overdefined - This instruction is not known to be constant, and we know
77 /// it has a value.
78 overdefined
79 } LatticeValue; // The current lattice position
80
Chris Lattnere9bb2df2001-12-03 22:26:30 +000081 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000082public:
Chris Lattneref36dfd2004-11-15 05:03:30 +000083 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner3bad2532006-12-20 06:21:33 +000084
Chris Lattner138a1242001-06-27 23:38:11 +000085 // markOverdefined - Return true if this is a new status to be in...
86 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000087 if (LatticeValue != overdefined) {
88 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000089 return true;
90 }
91 return false;
92 }
93
Chris Lattner3bad2532006-12-20 06:21:33 +000094 // markConstant - Return true if this is a new status for us.
Chris Lattnere9bb2df2001-12-03 22:26:30 +000095 inline bool markConstant(Constant *V) {
96 if (LatticeValue != constant) {
Chris Lattner3bad2532006-12-20 06:21:33 +000097 if (LatticeValue == undefined) {
98 LatticeValue = constant;
Jim Laskey52ab9042007-01-03 00:11:03 +000099 assert(V && "Marking constant with NULL");
Chris Lattner3bad2532006-12-20 06:21:33 +0000100 ConstantVal = V;
101 } else {
102 assert(LatticeValue == forcedconstant &&
103 "Cannot move from overdefined to constant!");
104 // Stay at forcedconstant if the constant is the same.
105 if (V == ConstantVal) return false;
106
107 // Otherwise, we go to overdefined. Assumptions made based on the
108 // forced value are possibly wrong. Assuming this is another constant
109 // could expose a contradiction.
110 LatticeValue = overdefined;
111 }
Chris Lattner138a1242001-06-27 23:38:11 +0000112 return true;
113 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000114 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +0000115 }
116 return false;
117 }
118
Chris Lattner3bad2532006-12-20 06:21:33 +0000119 inline void markForcedConstant(Constant *V) {
120 assert(LatticeValue == undefined && "Can't force a defined value!");
121 LatticeValue = forcedconstant;
122 ConstantVal = V;
123 }
124
125 inline bool isUndefined() const { return LatticeValue == undefined; }
126 inline bool isConstant() const {
127 return LatticeValue == constant || LatticeValue == forcedconstant;
128 }
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000129 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +0000130
Chris Lattner1daee8b2004-01-12 03:57:30 +0000131 inline Constant *getConstant() const {
132 assert(isConstant() && "Cannot get the constant of a non-constant!");
133 return ConstantVal;
134 }
Chris Lattner138a1242001-06-27 23:38:11 +0000135};
136
Chris Lattner138a1242001-06-27 23:38:11 +0000137//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +0000138//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000139/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
140/// Constant Propagation.
141///
142class SCCPSolver : public InstVisitor<SCCPSolver> {
Owen Anderson07cf79e2009-07-06 23:00:19 +0000143 LLVMContext *Context;
Chris Lattnercf712de2008-08-23 23:36:38 +0000144 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000145 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner138a1242001-06-27 23:38:11 +0000146
Chris Lattnerdd336d12004-12-11 05:15:59 +0000147 /// GlobalValue - If we are tracking any values for the contents of a global
148 /// variable, we keep a mapping from the constant accessor to the element of
149 /// the global, to the currently known value. If the value becomes
150 /// overdefined, it's entry is simply removed from this map.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000151 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattnerdd336d12004-12-11 05:15:59 +0000152
Devang Patel7c490d42008-03-11 05:46:42 +0000153 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattner59acc7d2004-12-10 08:02:06 +0000154 /// value out of a function, it will have an entry in this map, indicating
155 /// what the known return value for the function is.
Devang Patel7c490d42008-03-11 05:46:42 +0000156 DenseMap<Function*, LatticeVal> TrackedRetVals;
157
158 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
159 /// that return multiple values.
Chris Lattnercf712de2008-08-23 23:36:38 +0000160 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Chris Lattner59acc7d2004-12-10 08:02:06 +0000161
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000162 // The reason for two worklists is that overdefined is the lowest state
163 // on the lattice, and moving things to overdefined as fast as possible
164 // makes SCCP converge much faster.
165 // By having a separate worklist, we accomplish this because everything
166 // possibly overdefined will become overdefined at the soonest possible
167 // point.
Chris Lattnercf712de2008-08-23 23:36:38 +0000168 SmallVector<Value*, 64> OverdefinedInstWorkList;
169 SmallVector<Value*, 64> InstWorkList;
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000170
171
Chris Lattnercf712de2008-08-23 23:36:38 +0000172 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000173
Chris Lattner1daee8b2004-01-12 03:57:30 +0000174 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
175 /// overdefined, despite the fact that the PHI node is overdefined.
176 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
177
Chris Lattner16b18fd2003-10-08 16:55:34 +0000178 /// KnownFeasibleEdges - Entries in this set are edges which have already had
179 /// PHI nodes retriggered.
Chris Lattnercf712de2008-08-23 23:36:38 +0000180 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
181 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000182public:
Owen Anderson07cf79e2009-07-06 23:00:19 +0000183 void setContext(LLVMContext *C) { Context = C; }
Chris Lattner138a1242001-06-27 23:38:11 +0000184
Chris Lattner82bec2c2004-11-15 04:44:20 +0000185 /// MarkBlockExecutable - This method can be used by clients to mark all of
186 /// the blocks that are known to be intrinsically live in the processed unit.
187 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000188 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +0000189 BBExecutable.insert(BB); // Basic block is executable!
190 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner0dbfc052002-04-29 21:26:08 +0000191 }
192
Chris Lattnerdd336d12004-12-11 05:15:59 +0000193 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattner59acc7d2004-12-10 08:02:06 +0000194 /// inform the SCCPSolver that it should track loads and stores to the
195 /// specified global variable if it can. This is only legal to call if
196 /// performing Interprocedural SCCP.
Chris Lattnerdd336d12004-12-11 05:15:59 +0000197 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
198 const Type *ElTy = GV->getType()->getElementType();
199 if (ElTy->isFirstClassType()) {
200 LatticeVal &IV = TrackedGlobals[GV];
201 if (!isa<UndefValue>(GV->getInitializer()))
202 IV.markConstant(GV->getInitializer());
203 }
204 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000205
206 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
207 /// and out of the specified function (which cannot have its address taken),
208 /// this method must be called.
209 void AddTrackedFunction(Function *F) {
Rafael Espindolabb46f522009-01-15 20:18:42 +0000210 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Chris Lattner59acc7d2004-12-10 08:02:06 +0000211 // Add an entry, F -> undef.
Devang Patel7c490d42008-03-11 05:46:42 +0000212 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
213 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000214 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
215 LatticeVal()));
216 } else
217 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000218 }
219
Chris Lattner82bec2c2004-11-15 04:44:20 +0000220 /// Solve - Solve for constants and executable blocks.
221 ///
222 void Solve();
Chris Lattner138a1242001-06-27 23:38:11 +0000223
Chris Lattner3bad2532006-12-20 06:21:33 +0000224 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000225 /// that branches on undef values cannot reach any of their successors.
226 /// However, this is not a safe assumption. After we solve dataflow, this
227 /// method should be use to handle this. If this returns true, the solver
228 /// should be rerun.
Chris Lattner3bad2532006-12-20 06:21:33 +0000229 bool ResolvedUndefsIn(Function &F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +0000230
Chris Lattner7eb01bf2008-08-23 23:39:31 +0000231 bool isBlockExecutable(BasicBlock *BB) const {
232 return BBExecutable.count(BB);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000233 }
234
235 /// getValueMapping - Once we have solved for constants, return the mapping of
Chris Lattneref36dfd2004-11-15 05:03:30 +0000236 /// LLVM values to LatticeVals.
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000237 std::map<Value*, LatticeVal> &getValueMapping() {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000238 return ValueState;
239 }
240
Devang Patel7c490d42008-03-11 05:46:42 +0000241 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner0417feb2004-12-11 02:53:57 +0000242 ///
Devang Patel7c490d42008-03-11 05:46:42 +0000243 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
244 return TrackedRetVals;
Chris Lattner0417feb2004-12-11 02:53:57 +0000245 }
246
Chris Lattnerdd336d12004-12-11 05:15:59 +0000247 /// getTrackedGlobals - Get and return the set of inferred initializers for
248 /// global variables.
Chris Lattnerb59673e2007-02-02 20:38:30 +0000249 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattnerdd336d12004-12-11 05:15:59 +0000250 return TrackedGlobals;
251 }
252
Chris Lattner57939df2007-03-04 04:50:21 +0000253 inline void markOverdefined(Value *V) {
254 markOverdefined(ValueState[V], V);
255 }
Chris Lattner0417feb2004-12-11 02:53:57 +0000256
Chris Lattner138a1242001-06-27 23:38:11 +0000257private:
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000258 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanfd939082005-04-21 23:48:37 +0000259 // is not already a constant, add it to the instruction work list so that
Chris Lattner138a1242001-06-27 23:38:11 +0000260 // the users of the instruction are updated later.
261 //
Chris Lattner59acc7d2004-12-10 08:02:06 +0000262 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000263 if (IV.markConstant(C)) {
Dan Gohman87325772009-08-17 15:25:05 +0000264 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattner59acc7d2004-12-10 08:02:06 +0000265 InstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000266 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000267 }
Chris Lattner3bad2532006-12-20 06:21:33 +0000268
269 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
270 IV.markForcedConstant(C);
Dan Gohman87325772009-08-17 15:25:05 +0000271 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattner3bad2532006-12-20 06:21:33 +0000272 InstWorkList.push_back(V);
273 }
274
Chris Lattner59acc7d2004-12-10 08:02:06 +0000275 inline void markConstant(Value *V, Constant *C) {
276 markConstant(ValueState[V], V, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000277 }
278
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000279 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanfd939082005-04-21 23:48:37 +0000280 // value is not already overdefined, add it to the overdefined instruction
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000281 // work list so that the users of the instruction are updated later.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000282 inline void markOverdefined(LatticeVal &IV, Value *V) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000283 if (IV.markOverdefined()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000284 DEBUG(errs() << "markOverdefined: ";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000285 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000286 errs() << "Function '" << F->getName() << "'\n";
Chris Lattnerdade2d22004-12-11 06:05:53 +0000287 else
Dan Gohman87325772009-08-17 15:25:05 +0000288 errs() << *V << '\n');
Chris Lattner82bec2c2004-11-15 04:44:20 +0000289 // Only instructions go on the work list
Chris Lattner59acc7d2004-12-10 08:02:06 +0000290 OverdefinedInstWorkList.push_back(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000291 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000292 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000293
294 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
295 if (IV.isOverdefined() || MergeWithV.isUndefined())
296 return; // Noop.
297 if (MergeWithV.isOverdefined())
298 markOverdefined(IV, V);
299 else if (IV.isUndefined())
300 markConstant(IV, V, MergeWithV.getConstant());
301 else if (IV.getConstant() != MergeWithV.getConstant())
302 markOverdefined(IV, V);
Chris Lattner138a1242001-06-27 23:38:11 +0000303 }
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000304
305 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
306 return mergeInValue(ValueState[V], V, MergeWithV);
307 }
308
Chris Lattner138a1242001-06-27 23:38:11 +0000309
Chris Lattneref36dfd2004-11-15 05:03:30 +0000310 // getValueState - Return the LatticeVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000311 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000312 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000313 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000314 // Instruction object, then use this accessor to get its value from the map.
315 //
Chris Lattneref36dfd2004-11-15 05:03:30 +0000316 inline LatticeVal &getValueState(Value *V) {
Bill Wendling7a7cf6b2008-08-14 23:05:24 +0000317 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000318 if (I != ValueState.end()) return I->second; // Common case, in the map
Chris Lattner5d356a72004-10-16 18:09:41 +0000319
Chris Lattner3bad2532006-12-20 06:21:33 +0000320 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner7e529e42004-11-15 05:45:33 +0000321 if (isa<UndefValue>(V)) {
322 // Nothing to do, remain undefined.
323 } else {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000324 LatticeVal &LV = ValueState[C];
325 LV.markConstant(C); // Constants are constant
326 return LV;
Chris Lattner7e529e42004-11-15 05:45:33 +0000327 }
Chris Lattner2a88bb72002-08-30 23:39:00 +0000328 }
Chris Lattner138a1242001-06-27 23:38:11 +0000329 // All others are underdefined by default...
330 return ValueState[V];
331 }
332
Misha Brukmanfd939082005-04-21 23:48:37 +0000333 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000334 // work list if it is not already executable...
Misha Brukmanfd939082005-04-21 23:48:37 +0000335 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000336 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
337 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
338 return; // This edge is already known to be executable!
339
340 if (BBExecutable.count(Dest)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +0000341 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
342 << " -> " << Dest->getName() << "\n");
Chris Lattner16b18fd2003-10-08 16:55:34 +0000343
344 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000345 // feasible that wasn't before. Revisit the PHI nodes in the block
346 // because they have potentially new operands.
Chris Lattner59acc7d2004-12-10 08:02:06 +0000347 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
348 visitPHINode(*cast<PHINode>(I));
Chris Lattner9de28282003-04-25 02:50:03 +0000349
350 } else {
Chris Lattner82bec2c2004-11-15 04:44:20 +0000351 MarkBlockExecutable(Dest);
Chris Lattner9de28282003-04-25 02:50:03 +0000352 }
Chris Lattner138a1242001-06-27 23:38:11 +0000353 }
354
Chris Lattner82bec2c2004-11-15 04:44:20 +0000355 // getFeasibleSuccessors - Return a vector of booleans to indicate which
356 // successors are reachable from a given terminator instruction.
357 //
Chris Lattner1c1f1122007-02-02 21:15:06 +0000358 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
Chris Lattner82bec2c2004-11-15 04:44:20 +0000359
360 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
361 // block to the 'To' basic block is currently feasible...
362 //
363 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
364
365 // OperandChangedState - This method is invoked on all of the users of an
366 // instruction that was just changed state somehow.... Based on this
367 // information, we need to update the specified user of this instruction.
368 //
369 void OperandChangedState(User *U) {
370 // Only instructions use other variable values!
371 Instruction &I = cast<Instruction>(*U);
372 if (BBExecutable.count(I.getParent())) // Inst is executable?
373 visit(I);
374 }
375
376private:
377 friend class InstVisitor<SCCPSolver>;
Chris Lattner138a1242001-06-27 23:38:11 +0000378
Misha Brukmanfd939082005-04-21 23:48:37 +0000379 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000380 // operand made a transition, or the instruction is newly executable. Change
381 // the value type of I to reflect these changes if appropriate.
382 //
Chris Lattner7e708292002-06-25 16:13:24 +0000383 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000384
385 // Terminators
Chris Lattner59acc7d2004-12-10 08:02:06 +0000386 void visitReturnInst(ReturnInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000387 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000388
Chris Lattnerb8047602002-08-14 17:53:45 +0000389 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000390 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000391 void visitBinaryOperator(Instruction &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000392 void visitCmpInst(CmpInst &I);
Robert Bocchino56107e22006-01-10 19:05:05 +0000393 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino8fcf01e2006-01-17 20:06:55 +0000394 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner543abdf2006-04-08 01:19:12 +0000395 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000396 void visitExtractValueInst(ExtractValueInst &EVI);
397 void visitInsertValueInst(InsertValueInst &IVI);
Chris Lattner2a632552002-04-18 15:13:15 +0000398
399 // Instructions that cannot be folded away...
Chris Lattnerdd336d12004-12-11 05:15:59 +0000400 void visitStoreInst (Instruction &I);
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000401 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000402 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez83d63912009-09-18 22:35:49 +0000403 void visitCallInst (CallInst &I) {
Chris Lattner32c0d222009-09-27 21:35:11 +0000404 visitCallSite(CallSite::get(&I));
Victor Hernandez83d63912009-09-18 22:35:49 +0000405 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000406 void visitInvokeInst (InvokeInst &II) {
407 visitCallSite(CallSite::get(&II));
408 visitTerminatorInst(II);
Chris Lattner99b28e62003-08-27 01:08:35 +0000409 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000410 void visitCallSite (CallSite CS);
Chris Lattner36143fc2003-09-08 18:54:55 +0000411 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner5d356a72004-10-16 18:09:41 +0000412 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000413 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000414 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
415 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000416 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000417
Chris Lattner7e708292002-06-25 16:13:24 +0000418 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000419 // If a new instruction is added to LLVM that we don't handle...
Chris Lattnerbdff5482009-08-23 04:37:46 +0000420 errs() << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000421 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000422 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000423};
Chris Lattnerf6293092002-07-23 18:06:35 +0000424
Duncan Sandse2abf122007-07-20 08:56:21 +0000425} // end anonymous namespace
426
427
Chris Lattnerb9a66342002-05-02 21:44:00 +0000428// getFeasibleSuccessors - Return a vector of booleans to indicate which
429// successors are reachable from a given terminator instruction.
430//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000431void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Chris Lattner1c1f1122007-02-02 21:15:06 +0000432 SmallVector<bool, 16> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000433 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000434 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000435 if (BI->isUnconditional()) {
436 Succs[0] = true;
437 } else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000438 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000439 if (BCValue.isOverdefined() ||
Reid Spencer579dca12007-01-12 04:24:46 +0000440 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
Chris Lattner84831642004-01-12 17:40:36 +0000441 // Overdefined condition variables, and branches on unfoldable constant
442 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000443 Succs[0] = Succs[1] = true;
444 } else if (BCValue.isConstant()) {
445 // Constant condition variables mean the branch can only go a single way
Owen Anderson5defacc2009-07-31 17:39:07 +0000446 Succs[BCValue.getConstant() == ConstantInt::getFalse(*Context)] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000447 }
448 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000449 } else if (isa<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000450 // Invoke instructions successors are always executable.
451 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000452 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000453 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000454 if (SCValue.isOverdefined() || // Overdefined condition?
455 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000456 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000457 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner3a73c9e2008-05-10 23:56:54 +0000458 } else if (SCValue.isConstant())
459 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000460 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000461 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerb9a66342002-05-02 21:44:00 +0000462 }
463}
464
465
Chris Lattner59f0ce22002-05-02 21:18:01 +0000466// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
467// block to the 'To' basic block is currently feasible...
468//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000469bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner59f0ce22002-05-02 21:18:01 +0000470 assert(BBExecutable.count(To) && "Dest should always be alive!");
471
472 // Make sure the source basic block is executable!!
473 if (!BBExecutable.count(From)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000474
Chris Lattnerb9a66342002-05-02 21:44:00 +0000475 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000476 TerminatorInst *TI = From->getTerminator();
477 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
478 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000479 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000480 else {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000481 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000482 if (BCValue.isOverdefined()) {
483 // Overdefined condition variables mean the branch could go either way.
484 return true;
485 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000486 // Not branching on an evaluatable constant?
Chris Lattner54a525d2007-01-13 00:42:58 +0000487 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
Chris Lattner84831642004-01-12 17:40:36 +0000488
Chris Lattner7d275f42003-10-08 15:47:41 +0000489 // Constant condition variables mean the branch can only go a single way
Misha Brukmanfd939082005-04-21 23:48:37 +0000490 return BI->getSuccessor(BCValue.getConstant() ==
Owen Anderson5defacc2009-07-31 17:39:07 +0000491 ConstantInt::getFalse(*Context)) == To;
Chris Lattner7d275f42003-10-08 15:47:41 +0000492 }
493 return false;
494 }
Reid Spencer3ed469c2006-11-02 20:25:50 +0000495 } else if (isa<InvokeInst>(TI)) {
Chris Lattner7d275f42003-10-08 15:47:41 +0000496 // Invoke instructions successors are always executable.
497 return true;
498 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000499 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner7d275f42003-10-08 15:47:41 +0000500 if (SCValue.isOverdefined()) { // Overdefined condition?
501 // All destinations are executable!
502 return true;
503 } else if (SCValue.isConstant()) {
504 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000505 if (!isa<ConstantInt>(CPV))
506 return true; // not a foldable constant?
507
Chris Lattner7d275f42003-10-08 15:47:41 +0000508 // Make sure to skip the "default value" which isn't a value
509 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
510 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
511 return SI->getSuccessor(i) == To;
512
513 // Constant value not equal to any of the branches... must execute
514 // default branch then...
515 return SI->getDefaultDest() == To;
516 }
517 return false;
518 } else {
Torok Edwin7d696d82009-07-11 13:10:19 +0000519#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +0000520 errs() << "Unknown terminator instruction: " << *TI << '\n';
Torok Edwin7d696d82009-07-11 13:10:19 +0000521#endif
Torok Edwinc23197a2009-07-14 16:55:14 +0000522 llvm_unreachable(0);
Chris Lattner7d275f42003-10-08 15:47:41 +0000523 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000524}
Chris Lattner138a1242001-06-27 23:38:11 +0000525
Chris Lattner2a632552002-04-18 15:13:15 +0000526// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000527// operand made a transition, or the instruction is newly executable. Change
528// the value type of I to reflect these changes if appropriate. This method
529// makes sure to do the following actions:
530//
531// 1. If a phi node merges two constants in, and has conflicting value coming
532// from different branches, or if the PHI node merges in an overdefined
533// value, then the PHI node becomes overdefined.
534// 2. If a phi node merges only constants in, and they all agree on value, the
535// PHI node becomes a constant value equal to that.
536// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
537// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
538// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
539// 6. If a conditional branch has a value that is constant, make the selected
540// destination executable
541// 7. If a conditional branch has a value that is overdefined, make all
542// successors executable.
543//
Chris Lattner82bec2c2004-11-15 04:44:20 +0000544void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000545 LatticeVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000546 if (PNIV.isOverdefined()) {
547 // There may be instructions using this PHI node that are not overdefined
548 // themselves. If so, make sure that they know that the PHI node operand
549 // changed.
550 std::multimap<PHINode*, Instruction*>::iterator I, E;
551 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
552 if (I != E) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000553 SmallVector<Instruction*, 16> Users;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000554 for (; I != E; ++I) Users.push_back(I->second);
555 while (!Users.empty()) {
556 visit(Users.back());
557 Users.pop_back();
558 }
559 }
560 return; // Quick exit
561 }
Chris Lattner138a1242001-06-27 23:38:11 +0000562
Chris Lattnera2f652d2004-03-16 19:49:59 +0000563 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
564 // and slow us down a lot. Just mark them overdefined.
565 if (PN.getNumIncomingValues() > 64) {
566 markOverdefined(PNIV, &PN);
567 return;
568 }
569
Chris Lattner2a632552002-04-18 15:13:15 +0000570 // Look at all of the executable operands of the PHI node. If any of them
571 // are overdefined, the PHI becomes overdefined as well. If they are all
572 // constant, and they agree with each other, the PHI becomes the identical
573 // constant. If they are constant and don't agree, the PHI is overdefined.
574 // If there are no executable operands, the PHI remains undefined.
575 //
Chris Lattner9de28282003-04-25 02:50:03 +0000576 Constant *OperandVal = 0;
577 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000578 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
Chris Lattner9de28282003-04-25 02:50:03 +0000579 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanfd939082005-04-21 23:48:37 +0000580
Chris Lattner7e708292002-06-25 16:13:24 +0000581 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000582 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnercf712de2008-08-23 23:36:38 +0000583 markOverdefined(&PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000584 return;
585 }
586
Chris Lattner9de28282003-04-25 02:50:03 +0000587 if (OperandVal == 0) { // Grab the first value...
588 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000589 } else { // Another value is being merged in!
590 // There is already a reachable operand. If we conflict with it,
591 // then the PHI node becomes overdefined. If we agree with it, we
592 // can continue on.
Misha Brukmanfd939082005-04-21 23:48:37 +0000593
Chris Lattner2a632552002-04-18 15:13:15 +0000594 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000595 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000596 // Yes there is. This means the PHI node is not constant.
597 // You must be overdefined poor PHI.
598 //
Chris Lattnercf712de2008-08-23 23:36:38 +0000599 markOverdefined(&PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000600 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000601 }
Chris Lattner138a1242001-06-27 23:38:11 +0000602 }
603 }
Chris Lattner138a1242001-06-27 23:38:11 +0000604 }
605
Chris Lattner2a632552002-04-18 15:13:15 +0000606 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000607 // arguments that agree with each other(and OperandVal is the constant) or
608 // OperandVal is null because there are no defined incoming arguments. If
609 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000610 //
Chris Lattner9de28282003-04-25 02:50:03 +0000611 if (OperandVal)
Chris Lattnercf712de2008-08-23 23:36:38 +0000612 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000613}
614
Chris Lattner59acc7d2004-12-10 08:02:06 +0000615void SCCPSolver::visitReturnInst(ReturnInst &I) {
616 if (I.getNumOperands() == 0) return; // Ret void
617
Chris Lattner59acc7d2004-12-10 08:02:06 +0000618 Function *F = I.getParent()->getParent();
Devang Patel7c490d42008-03-11 05:46:42 +0000619 // If we are tracking the return value of this function, merge it in.
Rafael Espindolabb46f522009-01-15 20:18:42 +0000620 if (!F->hasLocalLinkage())
Devang Patel7c490d42008-03-11 05:46:42 +0000621 return;
622
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000623 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Chris Lattnerb59673e2007-02-02 20:38:30 +0000624 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patel7c490d42008-03-11 05:46:42 +0000625 TrackedRetVals.find(F);
626 if (TFRVI != TrackedRetVals.end() &&
Chris Lattner59acc7d2004-12-10 08:02:06 +0000627 !TFRVI->second.isOverdefined()) {
628 LatticeVal &IV = getValueState(I.getOperand(0));
629 mergeInValue(TFRVI->second, F, IV);
Devang Patel7c490d42008-03-11 05:46:42 +0000630 return;
631 }
632 }
633
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000634 // Handle functions that return multiple values.
635 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
636 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000637 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnerc6ee00b2008-04-23 05:38:20 +0000638 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
639 if (It == TrackedMultipleRetVals.end()) break;
640 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Chris Lattner59acc7d2004-12-10 08:02:06 +0000641 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000642 } else if (!TrackedMultipleRetVals.empty() &&
643 I.getNumOperands() == 1 &&
644 isa<StructType>(I.getOperand(0)->getType())) {
645 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
646 i != e; ++i) {
Chris Lattnercf712de2008-08-23 23:36:38 +0000647 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000648 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
649 if (It == TrackedMultipleRetVals.end()) break;
Owen Andersone922c022009-07-22 00:24:57 +0000650 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewyckyd7f20b62009-06-06 23:13:08 +0000651 mergeInValue(It->second, F, getValueState(Val));
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000652 }
Chris Lattner59acc7d2004-12-10 08:02:06 +0000653 }
654}
655
Chris Lattner82bec2c2004-11-15 04:44:20 +0000656void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner1c1f1122007-02-02 21:15:06 +0000657 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000658 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000659
Chris Lattner16b18fd2003-10-08 16:55:34 +0000660 BasicBlock *BB = TI.getParent();
661
Chris Lattnerb9a66342002-05-02 21:44:00 +0000662 // Mark all feasible successors executable...
663 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000664 if (SuccFeasible[i])
665 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000666}
667
Chris Lattner82bec2c2004-11-15 04:44:20 +0000668void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000669 Value *V = I.getOperand(0);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000670 LatticeVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000671 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000672 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000673 else if (VState.isConstant()) // Propagate constant value
Owen Andersonbaf3c402009-07-29 18:55:55 +0000674 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Reid Spencer4da49122006-12-12 05:05:00 +0000675 VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000676}
677
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000678void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000679 Value *Aggr = EVI.getAggregateOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000680
Dan Gohman60ea2682008-06-20 16:41:17 +0000681 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000682 if (isa<UndefValue>(Aggr))
683 return;
684
685 // Currently only handle single-index extractvalues.
686 if (EVI.getNumIndices() != 1) {
687 markOverdefined(&EVI);
688 return;
689 }
690
691 Function *F = 0;
692 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
693 F = CI->getCalledFunction();
694 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
695 F = II->getCalledFunction();
696
697 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
698 // result back!
699 if (F == 0 || TrackedMultipleRetVals.empty()) {
700 markOverdefined(&EVI);
701 return;
702 }
703
Chris Lattnercf712de2008-08-23 23:36:38 +0000704 // See if we are tracking the result of the callee. If not tracking this
705 // function (for example, it is a declaration) just move to overdefined.
706 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000707 markOverdefined(&EVI);
708 return;
709 }
710
711 // Otherwise, the value will be merged in here as a result of CallSite
712 // handling.
713}
714
715void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohman60ea2682008-06-20 16:41:17 +0000716 Value *Aggr = IVI.getAggregateOperand();
717 Value *Val = IVI.getInsertedValueOperand();
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000718
Dan Gohman60ea2682008-06-20 16:41:17 +0000719 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohmandfaceb42008-06-20 16:39:44 +0000720 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000721 return;
722
723 // Currently only handle single-index insertvalues.
724 if (IVI.getNumIndices() != 1) {
725 markOverdefined(&IVI);
726 return;
727 }
Dan Gohmandfaceb42008-06-20 16:39:44 +0000728
729 // Currently only handle insertvalue instructions that are in a single-use
730 // chain that builds up a return value.
731 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
732 if (!TmpIVI->hasOneUse()) {
733 markOverdefined(&IVI);
734 return;
735 }
736 const Value *V = *TmpIVI->use_begin();
737 if (isa<ReturnInst>(V))
738 break;
739 TmpIVI = dyn_cast<InsertValueInst>(V);
740 if (!TmpIVI) {
741 markOverdefined(&IVI);
742 return;
743 }
744 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000745
746 // See if we are tracking the result of the callee.
747 Function *F = IVI.getParent()->getParent();
Chris Lattnercf712de2008-08-23 23:36:38 +0000748 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000749 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
750
751 // Merge in the inserted member value.
752 if (It != TrackedMultipleRetVals.end())
753 mergeInValue(It->second, F, getValueState(Val));
754
Dan Gohman60ea2682008-06-20 16:41:17 +0000755 // Mark the aggregate result of the IVI overdefined; any tracking that we do
756 // will be done on the individual member values.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +0000757 markOverdefined(&IVI);
758}
759
Chris Lattner82bec2c2004-11-15 04:44:20 +0000760void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000761 LatticeVal &CondValue = getValueState(I.getCondition());
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000762 if (CondValue.isUndefined())
763 return;
Reid Spencer579dca12007-01-12 04:24:46 +0000764 if (CondValue.isConstant()) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000765 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
Reid Spencer579dca12007-01-12 04:24:46 +0000766 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000767 : I.getFalseValue()));
Chris Lattnerfe243eb2006-02-08 02:38:11 +0000768 return;
769 }
770 }
771
772 // Otherwise, the condition is overdefined or a constant we can't evaluate.
773 // See if we can produce something better than overdefined based on the T/F
774 // value.
775 LatticeVal &TVal = getValueState(I.getTrueValue());
776 LatticeVal &FVal = getValueState(I.getFalseValue());
777
778 // select ?, C, C -> C.
779 if (TVal.isConstant() && FVal.isConstant() &&
780 TVal.getConstant() == FVal.getConstant()) {
781 markConstant(&I, FVal.getConstant());
782 return;
783 }
784
785 if (TVal.isUndefined()) { // select ?, undef, X -> X.
786 mergeInValue(&I, FVal);
787 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
788 mergeInValue(&I, TVal);
789 } else {
790 markOverdefined(&I);
Chris Lattner6e323722004-03-12 05:52:44 +0000791 }
792}
793
Chris Lattner2a632552002-04-18 15:13:15 +0000794// Handle BinaryOperators and Shift Instructions...
Chris Lattner82bec2c2004-11-15 04:44:20 +0000795void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000796 LatticeVal &IV = ValueState[&I];
Chris Lattner1daee8b2004-01-12 03:57:30 +0000797 if (IV.isOverdefined()) return;
798
Chris Lattneref36dfd2004-11-15 05:03:30 +0000799 LatticeVal &V1State = getValueState(I.getOperand(0));
800 LatticeVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000801
Chris Lattner2a632552002-04-18 15:13:15 +0000802 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattnera177c672004-12-11 23:15:19 +0000803 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
804 // operand is overdefined.
805 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
806 LatticeVal *NonOverdefVal = 0;
807 if (!V1State.isOverdefined()) {
808 NonOverdefVal = &V1State;
809 } else if (!V2State.isOverdefined()) {
810 NonOverdefVal = &V2State;
811 }
812
813 if (NonOverdefVal) {
814 if (NonOverdefVal->isUndefined()) {
815 // Could annihilate value.
816 if (I.getOpcode() == Instruction::And)
Owen Andersona7235ea2009-07-31 20:28:14 +0000817 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +0000818 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000819 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +0000820 else
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000821 markConstant(IV, &I,
Owen Andersona7235ea2009-07-31 20:28:14 +0000822 Constant::getAllOnesValue(I.getType()));
Chris Lattnera177c672004-12-11 23:15:19 +0000823 return;
824 } else {
825 if (I.getOpcode() == Instruction::And) {
826 if (NonOverdefVal->getConstant()->isNullValue()) {
827 markConstant(IV, &I, NonOverdefVal->getConstant());
Jim Laskey52ab9042007-01-03 00:11:03 +0000828 return; // X and 0 = 0
Chris Lattnera177c672004-12-11 23:15:19 +0000829 }
830 } else {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000831 if (ConstantInt *CI =
832 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
Chris Lattnera177c672004-12-11 23:15:19 +0000833 if (CI->isAllOnesValue()) {
834 markConstant(IV, &I, NonOverdefVal->getConstant());
835 return; // X or -1 = -1
836 }
837 }
838 }
839 }
840 }
841
842
Chris Lattner1daee8b2004-01-12 03:57:30 +0000843 // If both operands are PHI nodes, it is possible that this instruction has
844 // a constant value, despite the fact that the PHI node doesn't. Check for
845 // this condition now.
846 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
847 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
848 if (PN1->getParent() == PN2->getParent()) {
849 // Since the two PHI nodes are in the same basic block, they must have
850 // entries for the same predecessors. Walk the predecessor list, and
851 // if all of the incoming values are constants, and the result of
852 // evaluating this expression with all incoming value pairs is the
853 // same, then this expression is a constant even though the PHI node
854 // is not a constant!
Chris Lattneref36dfd2004-11-15 05:03:30 +0000855 LatticeVal Result;
Chris Lattner1daee8b2004-01-12 03:57:30 +0000856 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +0000857 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000858 BasicBlock *InBlock = PN1->getIncomingBlock(i);
Chris Lattneref36dfd2004-11-15 05:03:30 +0000859 LatticeVal &In2 =
860 getValueState(PN2->getIncomingValueForBlock(InBlock));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000861
862 if (In1.isOverdefined() || In2.isOverdefined()) {
863 Result.markOverdefined();
864 break; // Cannot fold this operation over the PHI nodes!
865 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000866 Constant *V =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000867 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000868 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000869 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000870 Result.markConstant(V);
871 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000872 Result.markOverdefined();
873 break;
874 }
875 }
876 }
877
878 // If we found a constant value here, then we know the instruction is
879 // constant despite the fact that the PHI nodes are overdefined.
880 if (Result.isConstant()) {
881 markConstant(IV, &I, Result.getConstant());
882 // Remember that this instruction is virtually using the PHI node
883 // operands.
884 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
885 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
886 return;
887 } else if (Result.isUndefined()) {
888 return;
889 }
890
891 // Okay, this really is overdefined now. Since we might have
892 // speculatively thought that this was not overdefined before, and
893 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
894 // make sure to clean out any entries that we put there, for
895 // efficiency.
896 std::multimap<PHINode*, Instruction*>::iterator It, E;
897 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
898 while (It != E) {
899 if (It->second == &I) {
900 UsersOfOverdefinedPHIs.erase(It++);
901 } else
902 ++It;
903 }
904 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
905 while (It != E) {
906 if (It->second == &I) {
907 UsersOfOverdefinedPHIs.erase(It++);
908 } else
909 ++It;
910 }
911 }
912
913 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000914 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000915 markConstant(IV, &I,
Owen Andersonbaf3c402009-07-29 18:55:55 +0000916 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Chris Lattnerb16689b2004-01-12 19:08:43 +0000917 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000918 }
919}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000920
Reid Spencere4d87aa2006-12-23 06:05:41 +0000921// Handle ICmpInst instruction...
922void SCCPSolver::visitCmpInst(CmpInst &I) {
923 LatticeVal &IV = ValueState[&I];
924 if (IV.isOverdefined()) return;
925
926 LatticeVal &V1State = getValueState(I.getOperand(0));
927 LatticeVal &V2State = getValueState(I.getOperand(1));
928
929 if (V1State.isOverdefined() || V2State.isOverdefined()) {
930 // If both operands are PHI nodes, it is possible that this instruction has
931 // a constant value, despite the fact that the PHI node doesn't. Check for
932 // this condition now.
933 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
934 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
935 if (PN1->getParent() == PN2->getParent()) {
936 // Since the two PHI nodes are in the same basic block, they must have
937 // entries for the same predecessors. Walk the predecessor list, and
938 // if all of the incoming values are constants, and the result of
939 // evaluating this expression with all incoming value pairs is the
940 // same, then this expression is a constant even though the PHI node
941 // is not a constant!
942 LatticeVal Result;
943 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
944 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
945 BasicBlock *InBlock = PN1->getIncomingBlock(i);
946 LatticeVal &In2 =
947 getValueState(PN2->getIncomingValueForBlock(InBlock));
948
949 if (In1.isOverdefined() || In2.isOverdefined()) {
950 Result.markOverdefined();
951 break; // Cannot fold this operation over the PHI nodes!
952 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000953 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000954 In1.getConstant(),
955 In2.getConstant());
956 if (Result.isUndefined())
957 Result.markConstant(V);
958 else if (Result.isConstant() && Result.getConstant() != V) {
959 Result.markOverdefined();
960 break;
961 }
962 }
963 }
964
965 // If we found a constant value here, then we know the instruction is
966 // constant despite the fact that the PHI nodes are overdefined.
967 if (Result.isConstant()) {
968 markConstant(IV, &I, Result.getConstant());
969 // Remember that this instruction is virtually using the PHI node
970 // operands.
971 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
972 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
973 return;
974 } else if (Result.isUndefined()) {
975 return;
976 }
977
978 // Okay, this really is overdefined now. Since we might have
979 // speculatively thought that this was not overdefined before, and
980 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
981 // make sure to clean out any entries that we put there, for
982 // efficiency.
983 std::multimap<PHINode*, Instruction*>::iterator It, E;
984 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
985 while (It != E) {
986 if (It->second == &I) {
987 UsersOfOverdefinedPHIs.erase(It++);
988 } else
989 ++It;
990 }
991 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
992 while (It != E) {
993 if (It->second == &I) {
994 UsersOfOverdefinedPHIs.erase(It++);
995 } else
996 ++It;
997 }
998 }
999
1000 markOverdefined(IV, &I);
1001 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00001002 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001003 V1State.getConstant(),
1004 V2State.getConstant()));
1005 }
1006}
1007
Robert Bocchino56107e22006-01-10 19:05:05 +00001008void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001009 // FIXME : SCCP does not handle vectors properly.
1010 markOverdefined(&I);
1011 return;
1012
1013#if 0
Robert Bocchino56107e22006-01-10 19:05:05 +00001014 LatticeVal &ValState = getValueState(I.getOperand(0));
1015 LatticeVal &IdxState = getValueState(I.getOperand(1));
1016
1017 if (ValState.isOverdefined() || IdxState.isOverdefined())
1018 markOverdefined(&I);
1019 else if(ValState.isConstant() && IdxState.isConstant())
1020 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1021 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001022#endif
Robert Bocchino56107e22006-01-10 19:05:05 +00001023}
1024
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001025void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001026 // FIXME : SCCP does not handle vectors properly.
1027 markOverdefined(&I);
1028 return;
1029#if 0
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001030 LatticeVal &ValState = getValueState(I.getOperand(0));
1031 LatticeVal &EltState = getValueState(I.getOperand(1));
1032 LatticeVal &IdxState = getValueState(I.getOperand(2));
1033
1034 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1035 IdxState.isOverdefined())
1036 markOverdefined(&I);
1037 else if(ValState.isConstant() && EltState.isConstant() &&
1038 IdxState.isConstant())
1039 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1040 EltState.getConstant(),
1041 IdxState.getConstant()));
1042 else if (ValState.isUndefined() && EltState.isConstant() &&
Devang Patel67a821d2006-12-04 23:54:59 +00001043 IdxState.isConstant())
Chris Lattnere34e9a22007-04-14 23:32:02 +00001044 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1045 EltState.getConstant(),
1046 IdxState.getConstant()));
Devang Patel67a821d2006-12-04 23:54:59 +00001047#endif
Robert Bocchino8fcf01e2006-01-17 20:06:55 +00001048}
1049
Chris Lattner543abdf2006-04-08 01:19:12 +00001050void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Devang Patel67a821d2006-12-04 23:54:59 +00001051 // FIXME : SCCP does not handle vectors properly.
1052 markOverdefined(&I);
1053 return;
1054#if 0
Chris Lattner543abdf2006-04-08 01:19:12 +00001055 LatticeVal &V1State = getValueState(I.getOperand(0));
1056 LatticeVal &V2State = getValueState(I.getOperand(1));
1057 LatticeVal &MaskState = getValueState(I.getOperand(2));
1058
1059 if (MaskState.isUndefined() ||
1060 (V1State.isUndefined() && V2State.isUndefined()))
1061 return; // Undefined output if mask or both inputs undefined.
1062
1063 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1064 MaskState.isOverdefined()) {
1065 markOverdefined(&I);
1066 } else {
1067 // A mix of constant/undef inputs.
1068 Constant *V1 = V1State.isConstant() ?
1069 V1State.getConstant() : UndefValue::get(I.getType());
1070 Constant *V2 = V2State.isConstant() ?
1071 V2State.getConstant() : UndefValue::get(I.getType());
1072 Constant *Mask = MaskState.isConstant() ?
1073 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1074 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1075 }
Devang Patel67a821d2006-12-04 23:54:59 +00001076#endif
Chris Lattner543abdf2006-04-08 01:19:12 +00001077}
1078
Chris Lattner2a88bb72002-08-30 23:39:00 +00001079// Handle getelementptr instructions... if all operands are constants then we
1080// can turn this into a getelementptr ConstantExpr.
1081//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001082void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001083 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001084 if (IV.isOverdefined()) return;
1085
Chris Lattnere777ff22007-02-02 20:51:48 +00001086 SmallVector<Constant*, 8> Operands;
Chris Lattner2a88bb72002-08-30 23:39:00 +00001087 Operands.reserve(I.getNumOperands());
1088
1089 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001090 LatticeVal &State = getValueState(I.getOperand(i));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001091 if (State.isUndefined())
1092 return; // Operands are not resolved yet...
1093 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001094 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +00001095 return;
1096 }
1097 assert(State.isConstant() && "Unknown state!");
1098 Operands.push_back(State.getConstant());
1099 }
1100
1101 Constant *Ptr = Operands[0];
1102 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1103
Owen Andersonbaf3c402009-07-29 18:55:55 +00001104 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Chris Lattnere777ff22007-02-02 20:51:48 +00001105 Operands.size()));
Chris Lattner2a88bb72002-08-30 23:39:00 +00001106}
Brian Gaeked0fde302003-11-11 22:41:34 +00001107
Chris Lattnerdd336d12004-12-11 05:15:59 +00001108void SCCPSolver::visitStoreInst(Instruction &SI) {
1109 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1110 return;
1111 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattnerb59673e2007-02-02 20:38:30 +00001112 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattnerdd336d12004-12-11 05:15:59 +00001113 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1114
1115 // Get the value we are storing into the global.
1116 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1117
1118 mergeInValue(I->second, GV, PtrVal);
1119 if (I->second.isOverdefined())
1120 TrackedGlobals.erase(I); // No need to keep tracking this!
1121}
1122
1123
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001124// Handle load instructions. If the operand is a constant pointer to a constant
1125// global, we can replace the load with the loaded constant value!
Chris Lattner82bec2c2004-11-15 04:44:20 +00001126void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattneref36dfd2004-11-15 05:03:30 +00001127 LatticeVal &IV = ValueState[&I];
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001128 if (IV.isOverdefined()) return;
1129
Chris Lattneref36dfd2004-11-15 05:03:30 +00001130 LatticeVal &PtrVal = getValueState(I.getOperand(0));
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001131 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1132 if (PtrVal.isConstant() && !I.isVolatile()) {
1133 Value *Ptr = PtrVal.getConstant();
Christopher Lambb15147e2007-12-29 07:56:53 +00001134 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +00001135 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Chris Lattnerc76d8032004-03-07 22:16:24 +00001136 // load null -> null
Owen Andersona7235ea2009-07-31 20:28:14 +00001137 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattnerc76d8032004-03-07 22:16:24 +00001138 return;
1139 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001140
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001141 // Transform load (constant global) into the value loaded.
Chris Lattnerdd336d12004-12-11 05:15:59 +00001142 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1143 if (GV->isConstant()) {
Duncan Sands64da9402009-03-21 21:27:31 +00001144 if (GV->hasDefinitiveInitializer()) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001145 markConstant(IV, &I, GV->getInitializer());
1146 return;
1147 }
1148 } else if (!TrackedGlobals.empty()) {
1149 // If we are tracking this global, merge in the known value for it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001150 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
Chris Lattnerdd336d12004-12-11 05:15:59 +00001151 TrackedGlobals.find(GV);
1152 if (It != TrackedGlobals.end()) {
1153 mergeInValue(IV, &I, It->second);
1154 return;
1155 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001156 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001157 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001158
1159 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1160 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1161 if (CE->getOpcode() == Instruction::GetElementPtr)
Jeff Cohen9d809302005-04-23 21:38:35 +00001162 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +00001163 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Jeff Cohen9d809302005-04-23 21:38:35 +00001164 if (Constant *V =
Dan Gohmanc6f69e92009-10-05 16:36:26 +00001165 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Jeff Cohen9d809302005-04-23 21:38:35 +00001166 markConstant(IV, &I, V);
1167 return;
1168 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +00001169 }
1170
1171 // Otherwise we cannot say for certain what value this load will produce.
1172 // Bail out.
1173 markOverdefined(IV, &I);
1174}
Chris Lattner58b7b082004-04-13 19:43:54 +00001175
Chris Lattner59acc7d2004-12-10 08:02:06 +00001176void SCCPSolver::visitCallSite(CallSite CS) {
1177 Function *F = CS.getCalledFunction();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001178 Instruction *I = CS.getInstruction();
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001179
1180 // The common case is that we aren't tracking the callee, either because we
1181 // are not doing interprocedural analysis or the callee is indirect, or is
1182 // external. Handle these cases first.
Rafael Espindolabb46f522009-01-15 20:18:42 +00001183 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001184CallOverdefined:
1185 // Void return and not tracking callee, just bail.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001186 if (I->getType()->isVoidTy()) return;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001187
1188 // Otherwise, if we have a single return value case, and if the function is
1189 // a declaration, maybe we can constant fold it.
1190 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1191 canConstantFoldCallTo(F)) {
1192
1193 SmallVector<Constant*, 8> Operands;
1194 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1195 AI != E; ++AI) {
1196 LatticeVal &State = getValueState(*AI);
1197 if (State.isUndefined())
1198 return; // Operands are not resolved yet.
1199 else if (State.isOverdefined()) {
1200 markOverdefined(I);
1201 return;
1202 }
1203 assert(State.isConstant() && "Unknown state!");
1204 Operands.push_back(State.getConstant());
1205 }
1206
1207 // If we can constant fold this, mark the result of the call as a
1208 // constant.
Nick Lewyckye3f1fb12009-05-28 04:08:10 +00001209 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001210 markConstant(I, C);
1211 return;
1212 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001213 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001214
1215 // Otherwise, we don't know anything about this call, mark it overdefined.
1216 markOverdefined(I);
1217 return;
Chris Lattner58b7b082004-04-13 19:43:54 +00001218 }
1219
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001220 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001221 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1222 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001223 // If so, propagate the return value of the callee into this call result.
1224 mergeInValue(I, TFRVI->second);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001225 } else if (isa<StructType>(I->getType())) {
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001226 // Check to see if we're tracking this callee, if not, handle it in the
1227 // common path above.
Chris Lattnercf712de2008-08-23 23:36:38 +00001228 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1229 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001230 if (TMRVI == TrackedMultipleRetVals.end())
1231 goto CallOverdefined;
1232
1233 // If we are tracking this callee, propagate the return values of the call
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001234 // into this call site. We do this by walking all the uses. Single-index
1235 // ExtractValueInst uses can be tracked; anything more complicated is
1236 // currently handled conservatively.
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001237 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1238 UI != E; ++UI) {
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001239 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1240 if (EVI->getNumIndices() == 1) {
1241 mergeInValue(EVI,
Dan Gohman60ea2682008-06-20 16:41:17 +00001242 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001243 continue;
1244 }
1245 }
1246 // The aggregate value is used in a way not handled here. Assume nothing.
1247 markOverdefined(*UI);
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001248 }
Dan Gohmanc4b65ea2008-06-20 01:15:44 +00001249 } else {
1250 // Otherwise we're not tracking this callee, so handle it in the
1251 // common path above.
1252 goto CallOverdefined;
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001253 }
1254
1255 // Finally, if this is the first call to the function hit, mark its entry
1256 // block executable.
1257 if (!BBExecutable.count(F->begin()))
1258 MarkBlockExecutable(F->begin());
1259
1260 // Propagate information from this call site into the callee.
1261 CallSite::arg_iterator CAI = CS.arg_begin();
1262 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1263 AI != E; ++AI, ++CAI) {
1264 LatticeVal &IV = ValueState[AI];
Torok Edwinc3384992009-09-24 18:33:42 +00001265 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Torok Edwin30a94e32009-09-24 09:47:18 +00001266 IV.markOverdefined();
1267 continue;
1268 }
Chris Lattnerc6ee00b2008-04-23 05:38:20 +00001269 if (!IV.isOverdefined())
1270 mergeInValue(IV, AI, getValueState(*CAI));
1271 }
Chris Lattner58b7b082004-04-13 19:43:54 +00001272}
Chris Lattner82bec2c2004-11-15 04:44:20 +00001273
1274
1275void SCCPSolver::Solve() {
1276 // Process the work lists until they are empty!
Misha Brukmanfd939082005-04-21 23:48:37 +00001277 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen9d809302005-04-23 21:38:35 +00001278 !OverdefinedInstWorkList.empty()) {
Chris Lattner82bec2c2004-11-15 04:44:20 +00001279 // Process the instruction work list...
1280 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001281 Value *I = OverdefinedInstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001282 OverdefinedInstWorkList.pop_back();
1283
Dan Gohman87325772009-08-17 15:25:05 +00001284 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001285
Chris Lattner82bec2c2004-11-15 04:44:20 +00001286 // "I" got into the work list because it either made the transition from
1287 // bottom to constant
1288 //
1289 // Anything on this worklist that is overdefined need not be visited
1290 // since all of its users will have already been marked as overdefined
1291 // Update all of the users of this instruction's value...
1292 //
1293 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1294 UI != E; ++UI)
1295 OperandChangedState(*UI);
1296 }
1297 // Process the instruction work list...
1298 while (!InstWorkList.empty()) {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001299 Value *I = InstWorkList.back();
Chris Lattner82bec2c2004-11-15 04:44:20 +00001300 InstWorkList.pop_back();
1301
Dan Gohman87325772009-08-17 15:25:05 +00001302 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001303
Chris Lattner82bec2c2004-11-15 04:44:20 +00001304 // "I" got into the work list because it either made the transition from
1305 // bottom to constant
1306 //
1307 // Anything on this worklist that is overdefined need not be visited
1308 // since all of its users will have already been marked as overdefined.
1309 // Update all of the users of this instruction's value...
1310 //
1311 if (!getValueState(I).isOverdefined())
1312 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1313 UI != E; ++UI)
1314 OperandChangedState(*UI);
1315 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001316
Chris Lattner82bec2c2004-11-15 04:44:20 +00001317 // Process the basic block work list...
1318 while (!BBWorkList.empty()) {
1319 BasicBlock *BB = BBWorkList.back();
1320 BBWorkList.pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +00001321
Dan Gohman87325772009-08-17 15:25:05 +00001322 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanfd939082005-04-21 23:48:37 +00001323
Chris Lattner82bec2c2004-11-15 04:44:20 +00001324 // Notify all instructions in this basic block that they are newly
1325 // executable.
1326 visit(BB);
1327 }
1328 }
1329}
1330
Chris Lattner3bad2532006-12-20 06:21:33 +00001331/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001332/// that branches on undef values cannot reach any of their successors.
1333/// However, this is not a safe assumption. After we solve dataflow, this
1334/// method should be use to handle this. If this returns true, the solver
1335/// should be rerun.
Chris Lattnerd2d86702006-10-22 05:59:17 +00001336///
1337/// This method handles this by finding an unresolved branch and marking it one
1338/// of the edges from the block as being feasible, even though the condition
1339/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1340/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner3bad2532006-12-20 06:21:33 +00001341/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattnerd2d86702006-10-22 05:59:17 +00001342/// constraints on the condition of the branch, as that would impact other users
1343/// of the value.
Chris Lattner3bad2532006-12-20 06:21:33 +00001344///
1345/// This scan also checks for values that use undefs, whose results are actually
1346/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1347/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1348/// even if X isn't defined.
1349bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattnerd2d86702006-10-22 05:59:17 +00001350 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1351 if (!BBExecutable.count(BB))
1352 continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001353
1354 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1355 // Look for instructions which produce undef values.
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001356 if (I->getType()->isVoidTy()) continue;
Chris Lattner3bad2532006-12-20 06:21:33 +00001357
1358 LatticeVal &LV = getValueState(I);
1359 if (!LV.isUndefined()) continue;
1360
1361 // Get the lattice values of the first two operands for use below.
1362 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1363 LatticeVal Op1LV;
1364 if (I->getNumOperands() == 2) {
1365 // If this is a two-operand instruction, and if both operands are
1366 // undefs, the result stays undef.
1367 Op1LV = getValueState(I->getOperand(1));
1368 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1369 continue;
1370 }
1371
1372 // If this is an instructions whose result is defined even if the input is
1373 // not fully defined, propagate the information.
1374 const Type *ITy = I->getType();
1375 switch (I->getOpcode()) {
1376 default: break; // Leave the instruction as an undef.
1377 case Instruction::ZExt:
1378 // After a zero extend, we know the top part is zero. SExt doesn't have
1379 // to be handled here, because we don't know whether the top part is 1's
1380 // or 0's.
1381 assert(Op0LV.isUndefined());
Owen Andersona7235ea2009-07-31 20:28:14 +00001382 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001383 return true;
1384 case Instruction::Mul:
1385 case Instruction::And:
1386 // undef * X -> 0. X could be zero.
1387 // undef & X -> 0. X could be zero.
Owen Andersona7235ea2009-07-31 20:28:14 +00001388 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001389 return true;
1390
1391 case Instruction::Or:
1392 // undef | X -> -1. X could be -1.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001393 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001394 markForcedConstant(LV, I,
Owen Andersona7235ea2009-07-31 20:28:14 +00001395 Constant::getAllOnesValue(PTy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001396 else
Owen Andersona7235ea2009-07-31 20:28:14 +00001397 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Chris Lattner7ce2f8b2007-01-04 02:12:40 +00001398 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001399
1400 case Instruction::SDiv:
1401 case Instruction::UDiv:
1402 case Instruction::SRem:
1403 case Instruction::URem:
1404 // X / undef -> undef. No change.
1405 // X % undef -> undef. No change.
1406 if (Op1LV.isUndefined()) break;
1407
1408 // undef / X -> 0. X could be maxint.
1409 // undef % X -> 0. X could be 1.
Owen Andersona7235ea2009-07-31 20:28:14 +00001410 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001411 return true;
1412
1413 case Instruction::AShr:
1414 // undef >>s X -> undef. No change.
1415 if (Op0LV.isUndefined()) break;
1416
1417 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1418 if (Op0LV.isConstant())
1419 markForcedConstant(LV, I, Op0LV.getConstant());
1420 else
1421 markOverdefined(LV, I);
1422 return true;
1423 case Instruction::LShr:
1424 case Instruction::Shl:
1425 // undef >> X -> undef. No change.
1426 // undef << X -> undef. No change.
1427 if (Op0LV.isUndefined()) break;
1428
1429 // X >> undef -> 0. X could be 0.
1430 // X << undef -> 0. X could be 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001431 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Chris Lattner3bad2532006-12-20 06:21:33 +00001432 return true;
1433 case Instruction::Select:
1434 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1435 if (Op0LV.isUndefined()) {
1436 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1437 Op1LV = getValueState(I->getOperand(2));
1438 } else if (Op1LV.isUndefined()) {
1439 // c ? undef : undef -> undef. No change.
1440 Op1LV = getValueState(I->getOperand(2));
1441 if (Op1LV.isUndefined())
1442 break;
1443 // Otherwise, c ? undef : x -> x.
1444 } else {
1445 // Leave Op1LV as Operand(1)'s LatticeValue.
1446 }
1447
1448 if (Op1LV.isConstant())
1449 markForcedConstant(LV, I, Op1LV.getConstant());
1450 else
1451 markOverdefined(LV, I);
1452 return true;
Chris Lattner60301602008-05-24 03:59:33 +00001453 case Instruction::Call:
1454 // If a call has an undef result, it is because it is constant foldable
1455 // but one of the inputs was undef. Just force the result to
1456 // overdefined.
1457 markOverdefined(LV, I);
1458 return true;
Chris Lattner3bad2532006-12-20 06:21:33 +00001459 }
1460 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001461
1462 TerminatorInst *TI = BB->getTerminator();
1463 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1464 if (!BI->isConditional()) continue;
1465 if (!getValueState(BI->getCondition()).isUndefined())
1466 continue;
1467 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesen9bca5832008-05-23 01:01:31 +00001468 if (SI->getNumSuccessors()<2) // no cases
1469 continue;
Chris Lattnerd2d86702006-10-22 05:59:17 +00001470 if (!getValueState(SI->getCondition()).isUndefined())
1471 continue;
1472 } else {
1473 continue;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001474 }
Chris Lattnerd2d86702006-10-22 05:59:17 +00001475
Chris Lattner05bb7892008-01-28 00:32:30 +00001476 // If the edge to the second successor isn't thought to be feasible yet,
1477 // mark it so now. We pick the second one so that this goes to some
1478 // enumerated value in a switch instead of going to the default destination.
1479 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Chris Lattnerd2d86702006-10-22 05:59:17 +00001480 continue;
1481
1482 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1483 // and return. This will make other blocks reachable, which will allow new
1484 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner05bb7892008-01-28 00:32:30 +00001485 markEdgeExecutable(BB, TI->getSuccessor(1));
1486
1487 // This must be a conditional branch of switch on undef. At this point,
1488 // force the old terminator to branch to the first successor. This is
1489 // required because we are now influencing the dataflow of the function with
1490 // the assumption that this edge is taken. If we leave the branch condition
1491 // as undef, then further analysis could think the undef went another way
1492 // leading to an inconsistent set of conclusions.
1493 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00001494 BI->setCondition(ConstantInt::getFalse(*Context));
Chris Lattner05bb7892008-01-28 00:32:30 +00001495 } else {
1496 SwitchInst *SI = cast<SwitchInst>(TI);
1497 SI->setCondition(SI->getCaseValue(1));
1498 }
1499
Chris Lattnerd2d86702006-10-22 05:59:17 +00001500 return true;
1501 }
Chris Lattnerdade2d22004-12-11 06:05:53 +00001502
Chris Lattnerd2d86702006-10-22 05:59:17 +00001503 return false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001504}
1505
Chris Lattner82bec2c2004-11-15 04:44:20 +00001506
1507namespace {
Chris Lattner14051812004-11-15 07:15:04 +00001508 //===--------------------------------------------------------------------===//
Chris Lattner82bec2c2004-11-15 04:44:20 +00001509 //
Chris Lattner14051812004-11-15 07:15:04 +00001510 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spenceree5d25e2006-12-31 22:26:06 +00001511 /// Sparse Conditional Constant Propagator.
Chris Lattner14051812004-11-15 07:15:04 +00001512 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001513 struct SCCP : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +00001514 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +00001515 SCCP() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +00001516
Chris Lattner14051812004-11-15 07:15:04 +00001517 // runOnFunction - Run the Sparse Conditional Constant Propagation
1518 // algorithm, and return true if the function was modified.
1519 //
1520 bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +00001521
Chris Lattner14051812004-11-15 07:15:04 +00001522 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1523 AU.setPreservesCFG();
1524 }
1525 };
Chris Lattner82bec2c2004-11-15 04:44:20 +00001526} // end anonymous namespace
1527
Dan Gohman844731a2008-05-13 00:00:25 +00001528char SCCP::ID = 0;
1529static RegisterPass<SCCP>
1530X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001531
1532// createSCCPPass - This is the public interface to this file...
1533FunctionPass *llvm::createSCCPPass() {
1534 return new SCCP();
1535}
1536
1537
Chris Lattner82bec2c2004-11-15 04:44:20 +00001538// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1539// and return true if the function was modified.
1540//
1541bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001542 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner82bec2c2004-11-15 04:44:20 +00001543 SCCPSolver Solver;
Owen Andersone922c022009-07-22 00:24:57 +00001544 Solver.setContext(&F.getContext());
Chris Lattner82bec2c2004-11-15 04:44:20 +00001545
1546 // Mark the first block of the function as being executable.
1547 Solver.MarkBlockExecutable(F.begin());
1548
Chris Lattner7e529e42004-11-15 05:45:33 +00001549 // Mark all arguments to the function as being overdefined.
Chris Lattnere34e9a22007-04-14 23:32:02 +00001550 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001551 Solver.markOverdefined(AI);
Chris Lattner7e529e42004-11-15 05:45:33 +00001552
Chris Lattner82bec2c2004-11-15 04:44:20 +00001553 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001554 bool ResolvedUndefs = true;
1555 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001556 Solver.Solve();
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001557 DEBUG(errs() << "RESOLVING UNDEFs\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001558 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001559 }
Chris Lattner82bec2c2004-11-15 04:44:20 +00001560
Chris Lattner7e529e42004-11-15 05:45:33 +00001561 bool MadeChanges = false;
1562
1563 // If we decided that there are basic blocks that are dead in this function,
1564 // delete their contents now. Note that we cannot actually delete the blocks,
1565 // as we cannot modify the CFG of the function.
1566 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001567 SmallVector<Instruction*, 512> Insts;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001568 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner57939df2007-03-04 04:50:21 +00001569
Chris Lattner7e529e42004-11-15 05:45:33 +00001570 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001571 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001572 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001573 ++NumDeadBlocks;
1574
Chris Lattner7e529e42004-11-15 05:45:33 +00001575 // Delete the instructions backwards, as it has a reduced likelihood of
1576 // having to update as many def-use and use-def chains.
Chris Lattner7e529e42004-11-15 05:45:33 +00001577 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1578 I != E; ++I)
1579 Insts.push_back(I);
1580 while (!Insts.empty()) {
1581 Instruction *I = Insts.back();
1582 Insts.pop_back();
1583 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001584 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner7e529e42004-11-15 05:45:33 +00001585 BB->getInstList().erase(I);
1586 MadeChanges = true;
Chris Lattnerb77d5d82004-11-15 07:02:42 +00001587 ++NumInstRemoved;
Chris Lattner7e529e42004-11-15 05:45:33 +00001588 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001589 } else {
1590 // Iterate over all of the instructions in a function, replacing them with
1591 // constants if we have found them to be of constant values.
1592 //
1593 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1594 Instruction *Inst = BI++;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001595 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
Chris Lattnerf4023a12008-04-24 00:16:28 +00001596 continue;
1597
1598 LatticeVal &IV = Values[Inst];
1599 if (!IV.isConstant() && !IV.isUndefined())
1600 continue;
1601
1602 Constant *Const = IV.isConstant()
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001603 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001604 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001605
Chris Lattnerf4023a12008-04-24 00:16:28 +00001606 // Replaces all of the uses of a variable with uses of the constant.
1607 Inst->replaceAllUsesWith(Const);
1608
1609 // Delete the instruction.
1610 Inst->eraseFromParent();
1611
1612 // Hey, we just changed something!
1613 MadeChanges = true;
1614 ++NumInstRemoved;
Chris Lattner82bec2c2004-11-15 04:44:20 +00001615 }
1616 }
1617
1618 return MadeChanges;
1619}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001620
1621namespace {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001622 //===--------------------------------------------------------------------===//
1623 //
1624 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1625 /// Constant Propagation.
1626 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001627 struct IPSCCP : public ModulePass {
Devang Patel19974732007-05-03 01:11:54 +00001628 static char ID;
Dan Gohmanae73dc12008-09-04 17:05:41 +00001629 IPSCCP() : ModulePass(&ID) {}
Chris Lattner59acc7d2004-12-10 08:02:06 +00001630 bool runOnModule(Module &M);
1631 };
Chris Lattner59acc7d2004-12-10 08:02:06 +00001632} // end anonymous namespace
1633
Dan Gohman844731a2008-05-13 00:00:25 +00001634char IPSCCP::ID = 0;
1635static RegisterPass<IPSCCP>
1636Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1637
Chris Lattner59acc7d2004-12-10 08:02:06 +00001638// createIPSCCPPass - This is the public interface to this file...
1639ModulePass *llvm::createIPSCCPPass() {
1640 return new IPSCCP();
1641}
1642
1643
1644static bool AddressIsTaken(GlobalValue *GV) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001645 // Delete any dead constantexpr klingons.
1646 GV->removeDeadConstantUsers();
1647
Chris Lattner59acc7d2004-12-10 08:02:06 +00001648 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1649 UI != E; ++UI)
1650 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
Chris Lattnerdd336d12004-12-11 05:15:59 +00001651 if (SI->getOperand(0) == GV || SI->isVolatile())
1652 return true; // Storing addr of GV.
Chris Lattner59acc7d2004-12-10 08:02:06 +00001653 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1654 // Make sure we are calling the function, not passing the address.
1655 CallSite CS = CallSite::get(cast<Instruction>(*UI));
Nick Lewyckyaf386132008-11-03 03:49:14 +00001656 if (CS.hasArgument(GV))
1657 return true;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001658 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1659 if (LI->isVolatile())
1660 return true;
1661 } else {
Chris Lattner59acc7d2004-12-10 08:02:06 +00001662 return true;
1663 }
1664 return false;
1665}
1666
1667bool IPSCCP::runOnModule(Module &M) {
Owen Andersone922c022009-07-22 00:24:57 +00001668 LLVMContext *Context = &M.getContext();
Owen Anderson001dbfe2009-07-16 18:04:31 +00001669
Chris Lattner59acc7d2004-12-10 08:02:06 +00001670 SCCPSolver Solver;
Owen Anderson001dbfe2009-07-16 18:04:31 +00001671 Solver.setContext(Context);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001672
1673 // Loop over all functions, marking arguments to those with their addresses
1674 // taken or that are external as overdefined.
1675 //
Chris Lattner59acc7d2004-12-10 08:02:06 +00001676 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001677 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00001678 if (!F->isDeclaration())
Chris Lattner59acc7d2004-12-10 08:02:06 +00001679 Solver.MarkBlockExecutable(F->begin());
Chris Lattner7d27fc02005-04-19 19:16:19 +00001680 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1681 AI != E; ++AI)
Chris Lattner57939df2007-03-04 04:50:21 +00001682 Solver.markOverdefined(AI);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001683 } else {
1684 Solver.AddTrackedFunction(F);
1685 }
1686
Chris Lattnerdd336d12004-12-11 05:15:59 +00001687 // Loop over global variables. We inform the solver about any internal global
1688 // variables that do not have their 'addresses taken'. If they don't have
1689 // their addresses taken, we can propagate constants through them.
Chris Lattner7d27fc02005-04-19 19:16:19 +00001690 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1691 G != E; ++G)
Rafael Espindolabb46f522009-01-15 20:18:42 +00001692 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattnerdd336d12004-12-11 05:15:59 +00001693 Solver.TrackValueOfGlobalVariable(G);
1694
Chris Lattner59acc7d2004-12-10 08:02:06 +00001695 // Solve for constants.
Chris Lattner3bad2532006-12-20 06:21:33 +00001696 bool ResolvedUndefs = true;
1697 while (ResolvedUndefs) {
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001698 Solver.Solve();
1699
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001700 DEBUG(errs() << "RESOLVING UNDEFS\n");
Chris Lattner3bad2532006-12-20 06:21:33 +00001701 ResolvedUndefs = false;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001702 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner3bad2532006-12-20 06:21:33 +00001703 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001704 }
Chris Lattner59acc7d2004-12-10 08:02:06 +00001705
1706 bool MadeChanges = false;
1707
1708 // Iterate over all of the instructions in the module, replacing them with
1709 // constants if we have found them to be of constant values.
1710 //
Chris Lattnercf712de2008-08-23 23:36:38 +00001711 SmallVector<Instruction*, 512> Insts;
1712 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling7a7cf6b2008-08-14 23:05:24 +00001713 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Chris Lattner1c1f1122007-02-02 21:15:06 +00001714
Chris Lattner59acc7d2004-12-10 08:02:06 +00001715 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner7d27fc02005-04-19 19:16:19 +00001716 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1717 AI != E; ++AI)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001718 if (!AI->use_empty()) {
1719 LatticeVal &IV = Values[AI];
1720 if (IV.isConstant() || IV.isUndefined()) {
1721 Constant *CST = IV.isConstant() ?
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001722 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001723 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Misha Brukmanfd939082005-04-21 23:48:37 +00001724
Chris Lattner59acc7d2004-12-10 08:02:06 +00001725 // Replaces all of the uses of a variable with uses of the
1726 // constant.
1727 AI->replaceAllUsesWith(CST);
1728 ++IPNumArgsElimed;
1729 }
1730 }
1731
1732 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner7eb01bf2008-08-23 23:39:31 +00001733 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001734 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Chris Lattner59acc7d2004-12-10 08:02:06 +00001735 ++IPNumDeadBlocks;
Chris Lattnerfc6ac502004-12-10 20:41:50 +00001736
Chris Lattner59acc7d2004-12-10 08:02:06 +00001737 // Delete the instructions backwards, as it has a reduced likelihood of
1738 // having to update as many def-use and use-def chains.
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001739 TerminatorInst *TI = BB->getTerminator();
1740 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
Chris Lattner59acc7d2004-12-10 08:02:06 +00001741 Insts.push_back(I);
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001742
Chris Lattner59acc7d2004-12-10 08:02:06 +00001743 while (!Insts.empty()) {
1744 Instruction *I = Insts.back();
1745 Insts.pop_back();
1746 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001747 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattner59acc7d2004-12-10 08:02:06 +00001748 BB->getInstList().erase(I);
1749 MadeChanges = true;
1750 ++IPNumInstRemoved;
1751 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001752
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001753 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1754 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmancb406c22007-10-03 19:26:29 +00001755 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001756 TI->getSuccessor(i)->removePredecessor(BB);
1757 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001758 if (!TI->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001759 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001760 BB->getInstList().erase(TI);
1761
Chris Lattner864737b2004-12-11 05:32:19 +00001762 if (&*BB != &F->front())
1763 BlocksToErase.push_back(BB);
1764 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001765 new UnreachableInst(M.getContext(), BB);
Chris Lattner864737b2004-12-11 05:32:19 +00001766
Chris Lattner59acc7d2004-12-10 08:02:06 +00001767 } else {
1768 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1769 Instruction *Inst = BI++;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001770 if (Inst->getType()->isVoidTy())
Chris Lattnereb5f4092008-04-24 00:21:50 +00001771 continue;
1772
1773 LatticeVal &IV = Values[Inst];
1774 if (!IV.isConstant() && !IV.isUndefined())
1775 continue;
1776
1777 Constant *Const = IV.isConstant()
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001778 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001779 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Misha Brukmanfd939082005-04-21 23:48:37 +00001780
Chris Lattnereb5f4092008-04-24 00:21:50 +00001781 // Replaces all of the uses of a variable with uses of the
1782 // constant.
1783 Inst->replaceAllUsesWith(Const);
1784
1785 // Delete the instruction.
Chris Lattnerd9d46242009-01-14 21:01:16 +00001786 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattnereb5f4092008-04-24 00:21:50 +00001787 Inst->eraseFromParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001788
Chris Lattnereb5f4092008-04-24 00:21:50 +00001789 // Hey, we just changed something!
1790 MadeChanges = true;
1791 ++IPNumInstRemoved;
Chris Lattner59acc7d2004-12-10 08:02:06 +00001792 }
1793 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001794
1795 // Now that all instructions in the function are constant folded, erase dead
1796 // blocks, because we can now use ConstantFoldTerminator to get rid of
1797 // in-edges.
1798 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1799 // If there are any PHI nodes in this successor, drop entries for BB now.
1800 BasicBlock *DeadBB = BlocksToErase[i];
1801 while (!DeadBB->use_empty()) {
1802 Instruction *I = cast<Instruction>(DeadBB->use_back());
1803 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerddaaa372006-10-23 18:57:02 +00001804 if (!Folded) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00001805 // The constant folder may not have been able to fold the terminator
Chris Lattnerddaaa372006-10-23 18:57:02 +00001806 // if this is a branch or switch on undef. Fold it manually as a
1807 // branch to the first successor.
Devang Patelcb9a3542008-11-21 01:52:59 +00001808#ifndef NDEBUG
Chris Lattnerddaaa372006-10-23 18:57:02 +00001809 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1810 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1811 "Branch should be foldable!");
1812 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1813 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1814 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00001815 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerddaaa372006-10-23 18:57:02 +00001816 }
Devang Patelcb9a3542008-11-21 01:52:59 +00001817#endif
Chris Lattnerddaaa372006-10-23 18:57:02 +00001818
1819 // Make this an uncond branch to the first successor.
1820 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greif051a9502008-04-06 20:25:17 +00001821 BranchInst::Create(TI->getSuccessor(0), TI);
Chris Lattnerddaaa372006-10-23 18:57:02 +00001822
1823 // Remove entries in successor phi nodes to remove edges.
1824 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1825 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1826
1827 // Remove the old terminator.
1828 TI->eraseFromParent();
1829 }
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001830 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001831
Chris Lattner5f9e8b42004-12-10 22:29:08 +00001832 // Finally, delete the basic block.
1833 F->getBasicBlockList().erase(DeadBB);
1834 }
Chris Lattner1c1f1122007-02-02 21:15:06 +00001835 BlocksToErase.clear();
Chris Lattner59acc7d2004-12-10 08:02:06 +00001836 }
Chris Lattner0417feb2004-12-11 02:53:57 +00001837
1838 // If we inferred constant or undef return values for a function, we replaced
1839 // all call uses with the inferred value. This means we don't need to bother
1840 // actually returning anything from the function. Replace all return
1841 // instructions with return undef.
Devang Patel9af014f2008-03-11 17:32:05 +00001842 // TODO: Process multiple value ret instructions also.
Devang Patel7c490d42008-03-11 05:46:42 +00001843 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattnerb59673e2007-02-02 20:38:30 +00001844 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattner0417feb2004-12-11 02:53:57 +00001845 E = RV.end(); I != E; ++I)
1846 if (!I->second.isOverdefined() &&
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001847 !I->first->getReturnType()->isVoidTy()) {
Chris Lattner0417feb2004-12-11 02:53:57 +00001848 Function *F = I->first;
1849 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1850 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1851 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001852 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattner0417feb2004-12-11 02:53:57 +00001853 }
Chris Lattnerdd336d12004-12-11 05:15:59 +00001854
1855 // If we infered constant or undef values for globals variables, we can delete
1856 // the global and any stores that remain to it.
Chris Lattnerb59673e2007-02-02 20:38:30 +00001857 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1858 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattnerdd336d12004-12-11 05:15:59 +00001859 E = TG.end(); I != E; ++I) {
1860 GlobalVariable *GV = I->first;
1861 assert(!I->second.isOverdefined() &&
1862 "Overdefined values should have been taken out of the map!");
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001863 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattnerdd336d12004-12-11 05:15:59 +00001864 while (!GV->use_empty()) {
1865 StoreInst *SI = cast<StoreInst>(GV->use_back());
1866 SI->eraseFromParent();
1867 }
1868 M.getGlobalList().erase(GV);
Chris Lattnerdade2d22004-12-11 06:05:53 +00001869 ++IPNumGlobalConst;
Chris Lattnerdd336d12004-12-11 05:15:59 +00001870 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001871
Chris Lattner59acc7d2004-12-10 08:02:06 +00001872 return MadeChanges;
1873}