blob: b8f10e9075546f0ff8c6e8922200978531f8dc85 [file] [log] [blame]
Misha Brukman373086d2003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +00009//
Misha Brukman373086d2003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner347389d2001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattnerdd6522e2002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner347389d2001-06-27 23:38:11 +000017//
Chris Lattner347389d2001-06-27 23:38:11 +000018//===----------------------------------------------------------------------===//
19
Chris Lattner4f031622004-11-15 05:03:30 +000020#define DEBUG_TYPE "sccp"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000021#include "llvm/Transforms/Scalar.h"
Chris Lattner067d6072007-02-02 20:38:30 +000022#include "llvm/ADT/DenseMap.h"
Chris Lattner65938fc2008-08-23 23:36:38 +000023#include "llvm/ADT/DenseSet.h"
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000024#include "llvm/ADT/PointerIntPair.h"
Chris Lattner809aee22009-11-02 06:11:23 +000025#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000026#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000029#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DerivedTypes.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000033#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Instructions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/Debug.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Target/TargetLibraryInfo.h"
40#include "llvm/Transforms/IPO.h"
41#include "llvm/Transforms/Utils/Local.h"
Chris Lattner347389d2001-06-27 23:38:11 +000042#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000043using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000044
Chris Lattner79a42ac2006-12-19 21:40:18 +000045STATISTIC(NumInstRemoved, "Number of instructions removed");
46STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47
Nick Lewycky35e92c72008-03-08 07:48:41 +000048STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000049STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
51
Chris Lattner7d325382002-04-29 21:26:08 +000052namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000053/// LatticeVal class - This class represents the different lattice values that
54/// an LLVM value may occupy. It is a simple class with value semantics.
55///
Chris Lattner2dd09db2009-09-02 06:11:42 +000056class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000057 enum LatticeValueTy {
Chris Lattner1847f6d2006-12-20 06:21:33 +000058 /// undefined - This LLVM Value has no known value yet.
59 undefined,
Jakub Staszak632a3552012-01-18 21:16:33 +000060
Chris Lattner1847f6d2006-12-20 06:21:33 +000061 /// constant - This LLVM Value has a specific constant value.
62 constant,
63
64 /// forcedconstant - This LLVM Value was thought to be undef until
65 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
66 /// with another (different) constant, it goes to overdefined, instead of
67 /// asserting.
68 forcedconstant,
Jakub Staszak632a3552012-01-18 21:16:33 +000069
Chris Lattner1847f6d2006-12-20 06:21:33 +000070 /// overdefined - This instruction is not known to be constant, and we know
71 /// it has a value.
72 overdefined
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000073 };
74
75 /// Val: This stores the current lattice value along with the Constant* for
76 /// the constant if this is a 'constant' or 'forcedconstant' value.
77 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak632a3552012-01-18 21:16:33 +000078
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000079 LatticeValueTy getLatticeValue() const {
80 return Val.getInt();
81 }
Jakub Staszak632a3552012-01-18 21:16:33 +000082
Chris Lattner347389d2001-06-27 23:38:11 +000083public:
Chris Lattner7ccf1a62009-11-02 03:03:42 +000084 LatticeVal() : Val(0, undefined) {}
Jakub Staszak632a3552012-01-18 21:16:33 +000085
Chris Lattner7ccf1a62009-11-02 03:03:42 +000086 bool isUndefined() const { return getLatticeValue() == undefined; }
87 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000088 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
89 }
Chris Lattner7ccf1a62009-11-02 03:03:42 +000090 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak632a3552012-01-18 21:16:33 +000091
Chris Lattner7ccf1a62009-11-02 03:03:42 +000092 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000093 assert(isConstant() && "Cannot get the constant of a non-constant!");
94 return Val.getPointer();
95 }
Jakub Staszak632a3552012-01-18 21:16:33 +000096
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000097 /// markOverdefined - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +000098 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000099 if (isOverdefined())
100 return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000101
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000102 Val.setInt(overdefined);
103 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000104 }
105
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000106 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000107 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000108 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000109 assert(getConstant() == V && "Marking constant with different value");
110 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000111 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000112
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000113 if (isUndefined()) {
114 Val.setInt(constant);
115 assert(V && "Marking constant with NULL");
116 Val.setPointer(V);
117 } else {
Jakub Staszak632a3552012-01-18 21:16:33 +0000118 assert(getLatticeValue() == forcedconstant &&
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000119 "Cannot move from overdefined to constant!");
120 // Stay at forcedconstant if the constant is the same.
121 if (V == getConstant()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000122
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000123 // Otherwise, we go to overdefined. Assumptions made based on the
124 // forced value are possibly wrong. Assuming this is another constant
125 // could expose a contradiction.
126 Val.setInt(overdefined);
127 }
128 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000129 }
130
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000131 /// getConstantInt - If this is a constant with a ConstantInt value, return it
132 /// otherwise return null.
133 ConstantInt *getConstantInt() const {
134 if (isConstant())
135 return dyn_cast<ConstantInt>(getConstant());
136 return 0;
137 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000138
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000139 void markForcedConstant(Constant *V) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000140 assert(isUndefined() && "Can't force a defined value!");
141 Val.setInt(forcedconstant);
142 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000143 }
Chris Lattner347389d2001-06-27 23:38:11 +0000144};
Chris Lattnere405ed92009-11-02 02:47:51 +0000145} // end anonymous namespace.
146
147
148namespace {
Chris Lattner347389d2001-06-27 23:38:11 +0000149
Chris Lattner347389d2001-06-27 23:38:11 +0000150//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000151//
Chris Lattner074be1f2004-11-15 04:44:20 +0000152/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
153/// Constant Propagation.
154///
155class SCCPSolver : public InstVisitor<SCCPSolver> {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000156 const DataLayout *DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000157 const TargetLibraryInfo *TLI;
Nick Lewycky77cb8e62011-07-25 21:16:04 +0000158 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattnerf5484032009-11-02 05:55:40 +0000159 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000160
Chris Lattner156b8c72009-11-03 23:40:48 +0000161 /// StructValueState - This maintains ValueState for values that have
162 /// StructType, for example for formal arguments, calls, insertelement, etc.
163 ///
164 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000165
Chris Lattner91dbae62004-12-11 05:15:59 +0000166 /// GlobalValue - If we are tracking any values for the contents of a global
167 /// variable, we keep a mapping from the constant accessor to the element of
168 /// the global, to the currently known value. If the value becomes
169 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000170 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000171
Devang Patela7a20752008-03-11 05:46:42 +0000172 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000173 /// value out of a function, it will have an entry in this map, indicating
174 /// what the known return value for the function is.
Devang Patela7a20752008-03-11 05:46:42 +0000175 DenseMap<Function*, LatticeVal> TrackedRetVals;
176
177 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
178 /// that return multiple values.
Chris Lattner65938fc2008-08-23 23:36:38 +0000179 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000180
Chris Lattner156b8c72009-11-03 23:40:48 +0000181 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
182 /// represented here for efficient lookup.
183 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000184
Chris Lattner2c427232009-11-03 20:52:57 +0000185 /// TrackingIncomingArguments - This is the set of functions for whose
186 /// arguments we make optimistic assumptions about and try to prove as
187 /// constants.
Chris Lattnercde8de52009-11-03 19:24:51 +0000188 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000189
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000190 /// The reason for two worklists is that overdefined is the lowest state
191 /// on the lattice, and moving things to overdefined as fast as possible
192 /// makes SCCP converge much faster.
193 ///
194 /// By having a separate worklist, we accomplish this because everything
195 /// possibly overdefined will become overdefined at the soonest possible
196 /// point.
Chris Lattner65938fc2008-08-23 23:36:38 +0000197 SmallVector<Value*, 64> OverdefinedInstWorkList;
198 SmallVector<Value*, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000199
200
Chris Lattner65938fc2008-08-23 23:36:38 +0000201 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000202
203 /// KnownFeasibleEdges - Entries in this set are edges which have already had
204 /// PHI nodes retriggered.
Chris Lattner65938fc2008-08-23 23:36:38 +0000205 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
206 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000207public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000208 SCCPSolver(const DataLayout *DL, const TargetLibraryInfo *tli)
209 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000210
Chris Lattner074be1f2004-11-15 04:44:20 +0000211 /// MarkBlockExecutable - This method can be used by clients to mark all of
212 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000213 ///
214 /// This returns true if the block was not considered live before.
215 bool MarkBlockExecutable(BasicBlock *BB) {
216 if (!BBExecutable.insert(BB)) return false;
Nick Lewycky5cd95382013-06-26 00:30:18 +0000217 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000218 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000219 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000220 }
221
Chris Lattner91dbae62004-12-11 05:15:59 +0000222 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000223 /// inform the SCCPSolver that it should track loads and stores to the
224 /// specified global variable if it can. This is only legal to call if
225 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000226 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000227 // We only track the contents of scalar globals.
228 if (GV->getType()->getElementType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000229 LatticeVal &IV = TrackedGlobals[GV];
230 if (!isa<UndefValue>(GV->getInitializer()))
231 IV.markConstant(GV->getInitializer());
232 }
233 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000234
235 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
236 /// and out of the specified function (which cannot have its address taken),
237 /// this method must be called.
238 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000239 // Add an entry, F -> undef.
Chris Lattner229907c2011-07-18 04:54:35 +0000240 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000241 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000242 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000243 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
244 LatticeVal()));
245 } else
246 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000247 }
248
Chris Lattnercde8de52009-11-03 19:24:51 +0000249 void AddArgumentTrackedFunction(Function *F) {
250 TrackingIncomingArguments.insert(F);
251 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000252
Chris Lattner074be1f2004-11-15 04:44:20 +0000253 /// Solve - Solve for constants and executable blocks.
254 ///
255 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000256
Chris Lattner1847f6d2006-12-20 06:21:33 +0000257 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000258 /// that branches on undef values cannot reach any of their successors.
259 /// However, this is not a safe assumption. After we solve dataflow, this
260 /// method should be use to handle this. If this returns true, the solver
261 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000262 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000263
Chris Lattneradd44f32008-08-23 23:39:31 +0000264 bool isBlockExecutable(BasicBlock *BB) const {
265 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000266 }
267
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000268 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattnerf5484032009-11-02 05:55:40 +0000269 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000270 assert(I != ValueState.end() && "V is not in valuemap!");
271 return I->second;
Chris Lattner074be1f2004-11-15 04:44:20 +0000272 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000273
Devang Patela7a20752008-03-11 05:46:42 +0000274 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000275 ///
Devang Patela7a20752008-03-11 05:46:42 +0000276 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
277 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000278 }
279
Chris Lattner91dbae62004-12-11 05:15:59 +0000280 /// getTrackedGlobals - Get and return the set of inferred initializers for
281 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000282 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000283 return TrackedGlobals;
284 }
285
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000286 void markOverdefined(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000287 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerc33fd462007-03-04 04:50:21 +0000288 markOverdefined(ValueState[V], V);
289 }
Chris Lattner99e12952004-12-11 02:53:57 +0000290
Chris Lattner156b8c72009-11-03 23:40:48 +0000291 /// markAnythingOverdefined - Mark the specified value overdefined. This
292 /// works with both scalars and structs.
293 void markAnythingOverdefined(Value *V) {
Chris Lattner229907c2011-07-18 04:54:35 +0000294 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000295 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
296 markOverdefined(getStructValueState(V, i), V);
297 else
298 markOverdefined(V);
299 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000300
Chris Lattner347389d2001-06-27 23:38:11 +0000301private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000302 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000303 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000304 // the users of the instruction are updated later.
305 //
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000306 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
307 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000308 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000309 if (IV.isOverdefined())
310 OverdefinedInstWorkList.push_back(V);
311 else
312 InstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000313 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000314
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000315 void markConstant(Value *V, Constant *C) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000316 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerb4394642004-12-10 08:02:06 +0000317 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000318 }
319
Chris Lattnerf5484032009-11-02 05:55:40 +0000320 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000321 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000322 LatticeVal &IV = ValueState[V];
323 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000324 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000325 if (IV.isOverdefined())
326 OverdefinedInstWorkList.push_back(V);
327 else
328 InstWorkList.push_back(V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000329 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000330
331
Chris Lattnerd79334d2004-07-15 23:36:43 +0000332 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000333 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000334 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000335 void markOverdefined(LatticeVal &IV, Value *V) {
336 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000337
David Greene389fc3b2010-01-05 01:27:15 +0000338 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000339 if (Function *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000340 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000341 else
David Greene389fc3b2010-01-05 01:27:15 +0000342 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000343 // Only instructions go on the work list
344 OverdefinedInstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000345 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000346
Chris Lattnerf5484032009-11-02 05:55:40 +0000347 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000348 if (IV.isOverdefined() || MergeWithV.isUndefined())
349 return; // Noop.
350 if (MergeWithV.isOverdefined())
351 markOverdefined(IV, V);
352 else if (IV.isUndefined())
353 markConstant(IV, V, MergeWithV.getConstant());
354 else if (IV.getConstant() != MergeWithV.getConstant())
355 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000356 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000357
Chris Lattnerf5484032009-11-02 05:55:40 +0000358 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000359 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000360 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000361 }
362
Chris Lattner347389d2001-06-27 23:38:11 +0000363
Chris Lattnerf5484032009-11-02 05:55:40 +0000364 /// getValueState - Return the LatticeVal object that corresponds to the
365 /// value. This function handles the case when the value hasn't been seen yet
366 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000367 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000368 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000369
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000370 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
371 ValueState.insert(std::make_pair(V, LatticeVal()));
372 LatticeVal &LV = I.first->second;
373
374 if (!I.second)
375 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000376
Chris Lattner1847f6d2006-12-20 06:21:33 +0000377 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000378 // Undef values remain undefined.
379 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000380 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000381 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000382
Chris Lattnera3c39d32009-11-02 02:33:50 +0000383 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000384 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000385 }
386
Chris Lattner156b8c72009-11-03 23:40:48 +0000387 /// getStructValueState - Return the LatticeVal object that corresponds to the
388 /// value/field pair. This function handles the case when the value hasn't
389 /// been seen yet by properly seeding constants etc.
390 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000391 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000392 assert(i < cast<StructType>(V->getType())->getNumElements() &&
393 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000394
395 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
396 bool> I = StructValueState.insert(
397 std::make_pair(std::make_pair(V, i), LatticeVal()));
398 LatticeVal &LV = I.first->second;
399
400 if (!I.second)
401 return LV; // Common case, already in the map.
402
Chris Lattner156b8c72009-11-03 23:40:48 +0000403 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000404 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000405
Chris Lattnerfa775002012-01-26 02:32:04 +0000406 if (Elt == 0)
Chris Lattner156b8c72009-11-03 23:40:48 +0000407 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000408 else if (isa<UndefValue>(Elt))
409 ; // Undef values remain undefined.
410 else
411 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000412 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000413
Chris Lattner156b8c72009-11-03 23:40:48 +0000414 // All others are underdefined by default.
415 return LV;
416 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000417
Chris Lattner156b8c72009-11-03 23:40:48 +0000418
Chris Lattnerf5484032009-11-02 05:55:40 +0000419 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
420 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000421 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
422 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
423 return; // This edge is already known to be executable!
424
Chris Lattner809aee22009-11-02 06:11:23 +0000425 if (!MarkBlockExecutable(Dest)) {
426 // If the destination is already executable, we just made an *edge*
427 // feasible that wasn't before. Revisit the PHI nodes in the block
428 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000429 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Nick Lewycky5cd95382013-06-26 00:30:18 +0000430 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000431
Chris Lattner809aee22009-11-02 06:11:23 +0000432 PHINode *PN;
433 for (BasicBlock::iterator I = Dest->begin();
434 (PN = dyn_cast<PHINode>(I)); ++I)
435 visitPHINode(*PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000436 }
Chris Lattner347389d2001-06-27 23:38:11 +0000437 }
438
Chris Lattner074be1f2004-11-15 04:44:20 +0000439 // getFeasibleSuccessors - Return a vector of booleans to indicate which
440 // successors are reachable from a given terminator instruction.
441 //
Craig Topperb94011f2013-07-14 04:42:23 +0000442 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000443
444 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000445 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000446 //
447 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
448
449 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000450 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000451 // information, we need to update the specified user of this instruction.
452 //
Chris Lattnerfb141812009-11-03 03:42:51 +0000453 void OperandChangedState(Instruction *I) {
454 if (BBExecutable.count(I->getParent())) // Inst is executable?
455 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000456 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000457
Chris Lattner074be1f2004-11-15 04:44:20 +0000458private:
459 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000460
Chris Lattnera3c39d32009-11-02 02:33:50 +0000461 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000462 // operand made a transition, or the instruction is newly executable. Change
463 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000464 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000465
466 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000467 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000468 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000469
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000470 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000471 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000472 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000473 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000474 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000475 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000476 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000477 void visitExtractValueInst(ExtractValueInst &EVI);
478 void visitInsertValueInst(InsertValueInst &IVI);
Bill Wendlingfae14752011-08-12 20:24:12 +0000479 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000480
Chris Lattnera3c39d32009-11-02 02:33:50 +0000481 // Instructions that cannot be folded away.
Chris Lattnerf5484032009-11-02 05:55:40 +0000482 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000483 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000484 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandeze2971492009-10-24 04:23:03 +0000485 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000486 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000487 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000488 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000489 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000490 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000491 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000492 void visitCallSite (CallSite CS);
Bill Wendlingf891bf82011-07-31 06:30:59 +0000493 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000494 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Eli Friedman89b694b2011-07-27 01:08:30 +0000495 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eli Friedman366bcce2011-08-02 21:35:16 +0000496 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
497 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez8acf2952009-10-23 21:09:37 +0000498 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner156b8c72009-11-03 23:40:48 +0000499 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000500
Chris Lattner113f4f42002-06-25 16:13:24 +0000501 void visitInstruction(Instruction &I) {
Chris Lattnera3c39d32009-11-02 02:33:50 +0000502 // If a new instruction is added to LLVM that we don't handle.
Nick Lewycky5cd95382013-06-26 00:30:18 +0000503 dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
Chris Lattner156b8c72009-11-03 23:40:48 +0000504 markAnythingOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000505 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000506};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000507
Duncan Sands2be91fc2007-07-20 08:56:21 +0000508} // end anonymous namespace
509
510
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000511// getFeasibleSuccessors - Return a vector of booleans to indicate which
512// successors are reachable from a given terminator instruction.
513//
Chris Lattner074be1f2004-11-15 04:44:20 +0000514void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000515 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000516 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000517 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000518 if (BI->isUnconditional()) {
519 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000520 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000521 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000522
Chris Lattnerf5484032009-11-02 05:55:40 +0000523 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000524 ConstantInt *CI = BCValue.getConstantInt();
525 if (CI == 0) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000526 // Overdefined condition variables, and branches on unfoldable constant
527 // conditions, mean the branch could go either way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000528 if (!BCValue.isUndefined())
529 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000530 return;
531 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000532
Chris Lattner6df5cec2009-11-02 02:30:06 +0000533 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000534 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000535 return;
536 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000537
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000538 if (isa<InvokeInst>(TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000539 // Invoke instructions successors are always executable.
540 Succs[0] = Succs[1] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000541 return;
542 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000543
Chris Lattneree8b9512009-10-29 01:21:20 +0000544 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000545 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000546 Succs[0] = true;
547 return;
548 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000549 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000550 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000551
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000552 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000553 // All destinations are executable!
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000554 if (!SCValue.isUndefined())
555 Succs.assign(TI.getNumSuccessors(), true);
556 return;
557 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000558
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000559 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000560 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000561 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000562
Chris Lattneree8b9512009-10-29 01:21:20 +0000563 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
564 if (isa<IndirectBrInst>(&TI)) {
565 // Just mark all destinations executable!
566 Succs.assign(TI.getNumSuccessors(), true);
567 return;
568 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000569
Chris Lattneree8b9512009-10-29 01:21:20 +0000570#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000571 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000572#endif
573 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000574}
575
576
Chris Lattner13b52e72002-05-02 21:18:01 +0000577// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000578// block to the 'To' basic block is currently feasible.
Chris Lattner13b52e72002-05-02 21:18:01 +0000579//
Chris Lattner074be1f2004-11-15 04:44:20 +0000580bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000581 assert(BBExecutable.count(To) && "Dest should always be alive!");
582
583 // Make sure the source basic block is executable!!
584 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000585
Chris Lattnera3c39d32009-11-02 02:33:50 +0000586 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000587 TerminatorInst *TI = From->getTerminator();
588 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
589 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000590 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000591
Chris Lattnerf5484032009-11-02 05:55:40 +0000592 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000593
Chris Lattner6df5cec2009-11-02 02:30:06 +0000594 // Overdefined condition variables mean the branch could go either way,
595 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000596 ConstantInt *CI = BCValue.getConstantInt();
597 if (CI == 0)
598 return !BCValue.isUndefined();
Jakub Staszak632a3552012-01-18 21:16:33 +0000599
Chris Lattner6df5cec2009-11-02 02:30:06 +0000600 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000601 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000602 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000603
Chris Lattneree8b9512009-10-29 01:21:20 +0000604 // Invoke instructions successors are always executable.
605 if (isa<InvokeInst>(TI))
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000606 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000607
Chris Lattneree8b9512009-10-29 01:21:20 +0000608 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000609 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000610 return true;
611
Chris Lattnerf5484032009-11-02 05:55:40 +0000612 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000613 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000614
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000615 if (CI == 0)
616 return !SCValue.isUndefined();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000617
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000618 return SI->findCaseValue(CI).getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000619 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000620
Chris Lattneree8b9512009-10-29 01:21:20 +0000621 // Just mark all destinations executable!
622 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman3de2ddc2011-05-21 19:13:10 +0000623 if (isa<IndirectBrInst>(TI))
Chris Lattneree8b9512009-10-29 01:21:20 +0000624 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000625
Chris Lattneree8b9512009-10-29 01:21:20 +0000626#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000627 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000628#endif
629 llvm_unreachable(0);
Chris Lattner13b52e72002-05-02 21:18:01 +0000630}
Chris Lattner347389d2001-06-27 23:38:11 +0000631
Chris Lattnera3c39d32009-11-02 02:33:50 +0000632// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000633// operand made a transition, or the instruction is newly executable. Change
634// the value type of I to reflect these changes if appropriate. This method
635// makes sure to do the following actions:
636//
637// 1. If a phi node merges two constants in, and has conflicting value coming
638// from different branches, or if the PHI node merges in an overdefined
639// value, then the PHI node becomes overdefined.
640// 2. If a phi node merges only constants in, and they all agree on value, the
641// PHI node becomes a constant value equal to that.
642// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
643// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
644// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
645// 6. If a conditional branch has a value that is constant, make the selected
646// destination executable
647// 7. If a conditional branch has a value that is overdefined, make all
648// successors executable.
649//
Chris Lattner074be1f2004-11-15 04:44:20 +0000650void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000651 // If this PN returns a struct, just mark the result overdefined.
652 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000653 if (PN.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000654 return markAnythingOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000655
Eli Friedman0a309292011-11-11 01:16:15 +0000656 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000657 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000658
Chris Lattner7a7b1142004-03-16 19:49:59 +0000659 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
660 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000661 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000662 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000663
Chris Lattner6e560792002-04-18 15:13:15 +0000664 // Look at all of the executable operands of the PHI node. If any of them
665 // are overdefined, the PHI becomes overdefined as well. If they are all
666 // constant, and they agree with each other, the PHI becomes the identical
667 // constant. If they are constant and don't agree, the PHI is overdefined.
668 // If there are no executable operands, the PHI remains undefined.
669 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000670 Constant *OperandVal = 0;
671 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000672 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000673 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000674
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000675 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
676 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000677
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000678 if (IV.isOverdefined()) // PHI node becomes overdefined!
679 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000680
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000681 if (OperandVal == 0) { // Grab the first value.
682 OperandVal = IV.getConstant();
683 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000684 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000685
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000686 // There is already a reachable operand. If we conflict with it,
687 // then the PHI node becomes overdefined. If we agree with it, we
688 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000689
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000690 // Check to see if there are two different constants merging, if so, the PHI
691 // node is overdefined.
692 if (IV.getConstant() != OperandVal)
693 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000694 }
695
Chris Lattner6e560792002-04-18 15:13:15 +0000696 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000697 // arguments that agree with each other(and OperandVal is the constant) or
698 // OperandVal is null because there are no defined incoming arguments. If
699 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000700 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000701 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000702 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000703}
704
Chris Lattnerb4394642004-12-10 08:02:06 +0000705void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000706 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000707
Chris Lattnerb4394642004-12-10 08:02:06 +0000708 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000709 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000710
Devang Patela7a20752008-03-11 05:46:42 +0000711 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000712 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000713 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000714 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000715 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000716 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000717 return;
718 }
719 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000720
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000721 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000722 if (!TrackedMultipleRetVals.empty()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000723 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000724 if (MRVFunctionsTracked.count(F))
725 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
726 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
727 getStructValueState(ResultOp, i));
Jakub Staszak632a3552012-01-18 21:16:33 +0000728
Chris Lattnerb4394642004-12-10 08:02:06 +0000729 }
730}
731
Chris Lattner074be1f2004-11-15 04:44:20 +0000732void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000733 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000734 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000735
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000736 BasicBlock *BB = TI.getParent();
737
Chris Lattnera3c39d32009-11-02 02:33:50 +0000738 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000739 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000740 if (SuccFeasible[i])
741 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000742}
743
Chris Lattner074be1f2004-11-15 04:44:20 +0000744void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000745 LatticeVal OpSt = getValueState(I.getOperand(0));
746 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000747 markOverdefined(&I);
Chris Lattnerf5484032009-11-02 05:55:40 +0000748 else if (OpSt.isConstant()) // Propagate constant value
Jakub Staszak632a3552012-01-18 21:16:33 +0000749 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattnerf5484032009-11-02 05:55:40 +0000750 OpSt.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000751}
752
Chris Lattner156b8c72009-11-03 23:40:48 +0000753
Dan Gohman041f9d02008-06-20 01:15:44 +0000754void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000755 // If this returns a struct, mark all elements over defined, we don't track
756 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000757 if (EVI.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000758 return markAnythingOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000759
Chris Lattner156b8c72009-11-03 23:40:48 +0000760 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000761 if (EVI.getNumIndices() != 1)
762 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000763
Chris Lattner156b8c72009-11-03 23:40:48 +0000764 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000765 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000766 unsigned i = *EVI.idx_begin();
767 LatticeVal EltVal = getStructValueState(AggVal, i);
768 mergeInValue(getValueState(&EVI), &EVI, EltVal);
769 } else {
770 // Otherwise, must be extracting from an array.
771 return markOverdefined(&EVI);
772 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000773}
774
775void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000776 StructType *STy = dyn_cast<StructType>(IVI.getType());
Chris Lattner156b8c72009-11-03 23:40:48 +0000777 if (STy == 0)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000778 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000779
Chris Lattner156b8c72009-11-03 23:40:48 +0000780 // If this has more than one index, we can't handle it, drive all results to
781 // undef.
782 if (IVI.getNumIndices() != 1)
783 return markAnythingOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000784
Chris Lattner156b8c72009-11-03 23:40:48 +0000785 Value *Aggr = IVI.getAggregateOperand();
786 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000787
Chris Lattner156b8c72009-11-03 23:40:48 +0000788 // Compute the result based on what we're inserting.
789 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
790 // This passes through all values that aren't the inserted element.
791 if (i != Idx) {
792 LatticeVal EltVal = getStructValueState(Aggr, i);
793 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
794 continue;
795 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000796
Chris Lattner156b8c72009-11-03 23:40:48 +0000797 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000798 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000799 // We don't track structs in structs.
800 markOverdefined(getStructValueState(&IVI, i), &IVI);
801 else {
802 LatticeVal InVal = getValueState(Val);
803 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
804 }
805 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000806}
807
Chris Lattner074be1f2004-11-15 04:44:20 +0000808void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000809 // If this select returns a struct, just mark the result overdefined.
810 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000811 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000812 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000813
Chris Lattnerf5484032009-11-02 05:55:40 +0000814 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000815 if (CondValue.isUndefined())
816 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000817
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000818 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000819 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
820 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000821 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000822 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000823
Chris Lattner06a0ed12006-02-08 02:38:11 +0000824 // Otherwise, the condition is overdefined or a constant we can't evaluate.
825 // See if we can produce something better than overdefined based on the T/F
826 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000827 LatticeVal TVal = getValueState(I.getTrueValue());
828 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000829
Chris Lattner06a0ed12006-02-08 02:38:11 +0000830 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000831 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000832 TVal.getConstant() == FVal.getConstant())
833 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000834
Chris Lattnerf5484032009-11-02 05:55:40 +0000835 if (TVal.isUndefined()) // select ?, undef, X -> X.
836 return mergeInValue(&I, FVal);
837 if (FVal.isUndefined()) // select ?, X, undef -> X.
838 return mergeInValue(&I, TVal);
839 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000840}
841
Chris Lattnerf5484032009-11-02 05:55:40 +0000842// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000843void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000844 LatticeVal V1State = getValueState(I.getOperand(0));
845 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000846
Chris Lattner4f031622004-11-15 05:03:30 +0000847 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000848 if (IV.isOverdefined()) return;
849
Chris Lattnerf5484032009-11-02 05:55:40 +0000850 if (V1State.isConstant() && V2State.isConstant())
851 return markConstant(IV, &I,
852 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
853 V2State.getConstant()));
Jakub Staszak632a3552012-01-18 21:16:33 +0000854
Chris Lattnerf5484032009-11-02 05:55:40 +0000855 // If something is undef, wait for it to resolve.
856 if (!V1State.isOverdefined() && !V2State.isOverdefined())
857 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000858
Chris Lattnerf5484032009-11-02 05:55:40 +0000859 // Otherwise, one of our operands is overdefined. Try to produce something
860 // better than overdefined with some tricks.
Jakub Staszak632a3552012-01-18 21:16:33 +0000861
Chris Lattnerf5484032009-11-02 05:55:40 +0000862 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
863 // operand is overdefined.
864 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
865 LatticeVal *NonOverdefVal = 0;
866 if (!V1State.isOverdefined())
867 NonOverdefVal = &V1State;
868 else if (!V2State.isOverdefined())
869 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000870
Chris Lattnerf5484032009-11-02 05:55:40 +0000871 if (NonOverdefVal) {
872 if (NonOverdefVal->isUndefined()) {
873 // Could annihilate value.
874 if (I.getOpcode() == Instruction::And)
875 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner229907c2011-07-18 04:54:35 +0000876 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattnerf5484032009-11-02 05:55:40 +0000877 markConstant(IV, &I, Constant::getAllOnesValue(PT));
878 else
879 markConstant(IV, &I,
880 Constant::getAllOnesValue(I.getType()));
881 return;
Chris Lattnercbc01612004-12-11 23:15:19 +0000882 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000883
Chris Lattnerf5484032009-11-02 05:55:40 +0000884 if (I.getOpcode() == Instruction::And) {
885 // X and 0 = 0
886 if (NonOverdefVal->getConstant()->isNullValue())
887 return markConstant(IV, &I, NonOverdefVal->getConstant());
888 } else {
889 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
890 if (CI->isAllOnesValue()) // X or -1 = -1
891 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +0000892 }
893 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000894 }
Chris Lattnercbc01612004-12-11 23:15:19 +0000895
896
Chris Lattnerf5484032009-11-02 05:55:40 +0000897 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000898}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000899
Chris Lattnera3c39d32009-11-02 02:33:50 +0000900// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000901void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000902 LatticeVal V1State = getValueState(I.getOperand(0));
903 LatticeVal V2State = getValueState(I.getOperand(1));
904
Reid Spencer266e42b2006-12-23 06:05:41 +0000905 LatticeVal &IV = ValueState[&I];
906 if (IV.isOverdefined()) return;
907
Chris Lattnerf5484032009-11-02 05:55:40 +0000908 if (V1State.isConstant() && V2State.isConstant())
Jakub Staszak632a3552012-01-18 21:16:33 +0000909 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
910 V1State.getConstant(),
Chris Lattnerf5484032009-11-02 05:55:40 +0000911 V2State.getConstant()));
Jakub Staszak632a3552012-01-18 21:16:33 +0000912
Chris Lattnerf5484032009-11-02 05:55:40 +0000913 // If operands are still undefined, wait for it to resolve.
914 if (!V1State.isOverdefined() && !V2State.isOverdefined())
915 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000916
Chris Lattnerf5484032009-11-02 05:55:40 +0000917 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000918}
919
Robert Bocchinobd518d12006-01-10 19:05:05 +0000920void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000921 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000922 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000923
924#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000925 LatticeVal &ValState = getValueState(I.getOperand(0));
926 LatticeVal &IdxState = getValueState(I.getOperand(1));
927
928 if (ValState.isOverdefined() || IdxState.isOverdefined())
929 markOverdefined(&I);
930 else if(ValState.isConstant() && IdxState.isConstant())
931 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
932 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000933#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000934}
935
Robert Bocchino6dce2502006-01-17 20:06:55 +0000936void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000937 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000938 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000939#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000940 LatticeVal &ValState = getValueState(I.getOperand(0));
941 LatticeVal &EltState = getValueState(I.getOperand(1));
942 LatticeVal &IdxState = getValueState(I.getOperand(2));
943
944 if (ValState.isOverdefined() || EltState.isOverdefined() ||
945 IdxState.isOverdefined())
946 markOverdefined(&I);
947 else if(ValState.isConstant() && EltState.isConstant() &&
948 IdxState.isConstant())
949 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
950 EltState.getConstant(),
951 IdxState.getConstant()));
952 else if (ValState.isUndefined() && EltState.isConstant() &&
Jakub Staszak632a3552012-01-18 21:16:33 +0000953 IdxState.isConstant())
Chris Lattner28d921d2007-04-14 23:32:02 +0000954 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
955 EltState.getConstant(),
956 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000957#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000958}
959
Chris Lattner17bd6052006-04-08 01:19:12 +0000960void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000961 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000962 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000963#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000964 LatticeVal &V1State = getValueState(I.getOperand(0));
965 LatticeVal &V2State = getValueState(I.getOperand(1));
966 LatticeVal &MaskState = getValueState(I.getOperand(2));
967
968 if (MaskState.isUndefined() ||
969 (V1State.isUndefined() && V2State.isUndefined()))
970 return; // Undefined output if mask or both inputs undefined.
Jakub Staszak632a3552012-01-18 21:16:33 +0000971
Chris Lattner17bd6052006-04-08 01:19:12 +0000972 if (V1State.isOverdefined() || V2State.isOverdefined() ||
973 MaskState.isOverdefined()) {
974 markOverdefined(&I);
975 } else {
976 // A mix of constant/undef inputs.
Jakub Staszak632a3552012-01-18 21:16:33 +0000977 Constant *V1 = V1State.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +0000978 V1State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak632a3552012-01-18 21:16:33 +0000979 Constant *V2 = V2State.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +0000980 V2State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak632a3552012-01-18 21:16:33 +0000981 Constant *Mask = MaskState.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +0000982 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
983 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
984 }
Devang Patel21efc732006-12-04 23:54:59 +0000985#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000986}
987
Chris Lattnera3c39d32009-11-02 02:33:50 +0000988// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000989// can turn this into a getelementptr ConstantExpr.
990//
Chris Lattner074be1f2004-11-15 04:44:20 +0000991void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +0000992 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +0000993
Chris Lattner0e7ec672007-02-02 20:51:48 +0000994 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000995 Operands.reserve(I.getNumOperands());
996
997 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000998 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000999 if (State.isUndefined())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001000 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001001
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001002 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001003 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001004
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001005 assert(State.isConstant() && "Unknown state!");
1006 Operands.push_back(State.getConstant());
1007 }
1008
1009 Constant *Ptr = Operands[0];
Jay Foaded8db7d2011-07-21 14:31:17 +00001010 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1011 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001012}
Brian Gaeke960707c2003-11-11 22:41:34 +00001013
Chris Lattnerf5484032009-11-02 05:55:40 +00001014void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001015 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001016 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001017 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001018
Chris Lattner91dbae62004-12-11 05:15:59 +00001019 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1020 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001021
Chris Lattner91dbae62004-12-11 05:15:59 +00001022 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001023 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001024 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1025
Chris Lattnerf5484032009-11-02 05:55:40 +00001026 // Get the value we are storing into the global, then merge it.
1027 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001028 if (I->second.isOverdefined())
1029 TrackedGlobals.erase(I); // No need to keep tracking this!
1030}
1031
1032
Chris Lattner49f74522004-01-12 04:29:41 +00001033// Handle load instructions. If the operand is a constant pointer to a constant
1034// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001035void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001036 // If this load is of a struct, just mark the result overdefined.
Duncan Sands19d0b472010-02-16 11:11:14 +00001037 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001038 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001039
Chris Lattnerf5484032009-11-02 05:55:40 +00001040 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001041 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001042
Chris Lattner4f031622004-11-15 05:03:30 +00001043 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001044 if (IV.isOverdefined()) return;
1045
Chris Lattnerf5484032009-11-02 05:55:40 +00001046 if (!PtrVal.isConstant() || I.isVolatile())
1047 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001048
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001049 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001050
Chris Lattnerf5484032009-11-02 05:55:40 +00001051 // load null -> null
1052 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1053 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
Jakub Staszak632a3552012-01-18 21:16:33 +00001054
Chris Lattnerf5484032009-11-02 05:55:40 +00001055 // Transform load (constant global) into the value loaded.
1056 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001057 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001058 // If we are tracking this global, merge in the known value for it.
1059 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1060 TrackedGlobals.find(GV);
1061 if (It != TrackedGlobals.end()) {
1062 mergeInValue(IV, &I, It->second);
1063 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001064 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001065 }
Chris Lattner49f74522004-01-12 04:29:41 +00001066 }
1067
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001068 // Transform load from a constant into a constant if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001069 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001070 return markConstant(IV, &I, C);
Chris Lattnerf5484032009-11-02 05:55:40 +00001071
Chris Lattner49f74522004-01-12 04:29:41 +00001072 // Otherwise we cannot say for certain what value this load will produce.
1073 // Bail out.
1074 markOverdefined(IV, &I);
1075}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001076
Chris Lattnerb4394642004-12-10 08:02:06 +00001077void SCCPSolver::visitCallSite(CallSite CS) {
1078 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001079 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001080
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001081 // The common case is that we aren't tracking the callee, either because we
1082 // are not doing interprocedural analysis or the callee is indirect, or is
1083 // external. Handle these cases first.
Chris Lattnerfb141812009-11-03 03:42:51 +00001084 if (F == 0 || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001085CallOverdefined:
1086 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001087 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001088
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001089 // Otherwise, if we have a single return value case, and if the function is
1090 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001091 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001092 canConstantFoldCallTo(F)) {
Jakub Staszak632a3552012-01-18 21:16:33 +00001093
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001094 SmallVector<Constant*, 8> Operands;
1095 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1096 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001097 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001098
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001099 if (State.isUndefined())
1100 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001101 if (State.isOverdefined())
1102 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001103 assert(State.isConstant() && "Unknown state!");
1104 Operands.push_back(State.getConstant());
1105 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001106
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001107 // If we can constant fold this, mark the result of the call as a
1108 // constant.
Chad Rosiere6de63d2011-12-01 21:29:16 +00001109 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001110 return markConstant(I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001111 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001112
1113 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner156b8c72009-11-03 23:40:48 +00001114 return markAnythingOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001115 }
1116
Chris Lattnercde8de52009-11-03 19:24:51 +00001117 // If this is a local function that doesn't have its address taken, mark its
1118 // entry block executable and merge in the actual arguments to the call into
1119 // the formal arguments of the function.
1120 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1121 MarkBlockExecutable(F->begin());
Jakub Staszak632a3552012-01-18 21:16:33 +00001122
Chris Lattnercde8de52009-11-03 19:24:51 +00001123 // Propagate information from this call site into the callee.
1124 CallSite::arg_iterator CAI = CS.arg_begin();
1125 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1126 AI != E; ++AI, ++CAI) {
1127 // If this argument is byval, and if the function is not readonly, there
1128 // will be an implicit copy formed of the input aggregate.
1129 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1130 markOverdefined(AI);
1131 continue;
1132 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001133
Chris Lattner229907c2011-07-18 04:54:35 +00001134 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001135 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1136 LatticeVal CallArg = getStructValueState(*CAI, i);
1137 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1138 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001139 } else {
1140 mergeInValue(AI, getValueState(*CAI));
1141 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001142 }
1143 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001144
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001145 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattner229907c2011-07-18 04:54:35 +00001146 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001147 if (!MRVFunctionsTracked.count(F))
1148 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001149
Chris Lattner156b8c72009-11-03 23:40:48 +00001150 // If we are tracking this callee, propagate the result of the function
1151 // into this call site.
1152 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001153 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001154 TrackedMultipleRetVals[std::make_pair(F, i)]);
1155 } else {
1156 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1157 if (TFRVI == TrackedRetVals.end())
1158 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001159
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001160 // If so, propagate the return value of the callee into this call result.
1161 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001162 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001163}
Chris Lattner074be1f2004-11-15 04:44:20 +00001164
Chris Lattner074be1f2004-11-15 04:44:20 +00001165void SCCPSolver::Solve() {
1166 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001167 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001168 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001169 // Process the overdefined instruction's work list first, which drives other
1170 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001171 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001172 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001173
David Greene389fc3b2010-01-05 01:27:15 +00001174 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001175
Chris Lattner074be1f2004-11-15 04:44:20 +00001176 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001177 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001178 //
1179 // Anything on this worklist that is overdefined need not be visited
1180 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001181 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001182 //
Chandler Carruthcdf47882014-03-09 03:16:01 +00001183 for (User *U : I->users())
1184 if (Instruction *UI = dyn_cast<Instruction>(U))
1185 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001186 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001187
Chris Lattnera3c39d32009-11-02 02:33:50 +00001188 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001189 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001190 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001191
David Greene389fc3b2010-01-05 01:27:15 +00001192 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001193
Chris Lattnerf5484032009-11-02 05:55:40 +00001194 // "I" got into the work list because it made the transition from undef to
1195 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001196 //
1197 // Anything on this worklist that is overdefined need not be visited
1198 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001199 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001200 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001201 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001202 for (User *U : I->users())
1203 if (Instruction *UI = dyn_cast<Instruction>(U))
1204 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001205 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001206
Chris Lattnera3c39d32009-11-02 02:33:50 +00001207 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001208 while (!BBWorkList.empty()) {
1209 BasicBlock *BB = BBWorkList.back();
1210 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001211
David Greene389fc3b2010-01-05 01:27:15 +00001212 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001213
Chris Lattner074be1f2004-11-15 04:44:20 +00001214 // Notify all instructions in this basic block that they are newly
1215 // executable.
1216 visit(BB);
1217 }
1218 }
1219}
1220
Chris Lattner1847f6d2006-12-20 06:21:33 +00001221/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001222/// that branches on undef values cannot reach any of their successors.
1223/// However, this is not a safe assumption. After we solve dataflow, this
1224/// method should be use to handle this. If this returns true, the solver
1225/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001226///
1227/// This method handles this by finding an unresolved branch and marking it one
1228/// of the edges from the block as being feasible, even though the condition
1229/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1230/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001231/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001232/// constraints on the condition of the branch, as that would impact other users
1233/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001234///
1235/// This scan also checks for values that use undefs, whose results are actually
1236/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1237/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1238/// even if X isn't defined.
1239bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001240 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1241 if (!BBExecutable.count(BB))
1242 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001243
Chris Lattner1847f6d2006-12-20 06:21:33 +00001244 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1245 // Look for instructions which produce undef values.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001246 if (I->getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001247
Chris Lattner229907c2011-07-18 04:54:35 +00001248 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001249 // Only a few things that can be structs matter for undef.
1250
1251 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1252 if (CallSite CS = CallSite(I))
1253 if (Function *F = CS.getCalledFunction())
1254 if (MRVFunctionsTracked.count(F))
1255 continue;
1256
1257 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001258 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001259 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1260 continue;
1261
1262 // Send the results of everything else to overdefined. We could be
1263 // more precise than this but it isn't worth bothering.
1264 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1265 LatticeVal &LV = getStructValueState(I, i);
1266 if (LV.isUndefined())
1267 markOverdefined(LV, I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001268 }
1269 continue;
1270 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001271
Chris Lattner1847f6d2006-12-20 06:21:33 +00001272 LatticeVal &LV = getValueState(I);
1273 if (!LV.isUndefined()) continue;
1274
Eli Friedmand7749be2011-08-17 18:10:43 +00001275 // extractvalue is safe; check here because the argument is a struct.
1276 if (isa<ExtractValueInst>(I))
1277 continue;
1278
1279 // Compute the operand LatticeVals, for convenience below.
1280 // Anything taking a struct is conservatively assumed to require
1281 // overdefined markings.
1282 if (I->getOperand(0)->getType()->isStructTy()) {
1283 markOverdefined(I);
1284 return true;
1285 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001286 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001287 LatticeVal Op1LV;
Eli Friedmand7749be2011-08-17 18:10:43 +00001288 if (I->getNumOperands() == 2) {
1289 if (I->getOperand(1)->getType()->isStructTy()) {
1290 markOverdefined(I);
1291 return true;
1292 }
1293
Chris Lattner1847f6d2006-12-20 06:21:33 +00001294 Op1LV = getValueState(I->getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001295 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001296 // If this is an instructions whose result is defined even if the input is
1297 // not fully defined, propagate the information.
Chris Lattner229907c2011-07-18 04:54:35 +00001298 Type *ITy = I->getType();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001299 switch (I->getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001300 case Instruction::Add:
1301 case Instruction::Sub:
1302 case Instruction::Trunc:
1303 case Instruction::FPTrunc:
1304 case Instruction::BitCast:
1305 break; // Any undef -> undef
1306 case Instruction::FSub:
1307 case Instruction::FAdd:
1308 case Instruction::FMul:
1309 case Instruction::FDiv:
1310 case Instruction::FRem:
1311 // Floating-point binary operation: be conservative.
1312 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1313 markForcedConstant(I, Constant::getNullValue(ITy));
1314 else
1315 markOverdefined(I);
1316 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001317 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001318 case Instruction::SExt:
1319 case Instruction::FPToUI:
1320 case Instruction::FPToSI:
1321 case Instruction::FPExt:
1322 case Instruction::PtrToInt:
1323 case Instruction::IntToPtr:
1324 case Instruction::SIToFP:
1325 case Instruction::UIToFP:
1326 // undef -> 0; some outputs are impossible
Chris Lattnerf5484032009-11-02 05:55:40 +00001327 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001328 return true;
1329 case Instruction::Mul:
1330 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001331 // Both operands undef -> undef
1332 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1333 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001334 // undef * X -> 0. X could be zero.
1335 // undef & X -> 0. X could be zero.
Chris Lattnerf5484032009-11-02 05:55:40 +00001336 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001337 return true;
1338
1339 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001340 // Both operands undef -> undef
1341 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1342 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001343 // undef | X -> -1. X could be -1.
Chris Lattnerf5484032009-11-02 05:55:40 +00001344 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001345 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001346
Eli Friedman0793eb42011-08-16 22:06:31 +00001347 case Instruction::Xor:
1348 // undef ^ undef -> 0; strictly speaking, this is not strictly
1349 // necessary, but we try to be nice to people who expect this
1350 // behavior in simple cases
1351 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1352 markForcedConstant(I, Constant::getNullValue(ITy));
1353 return true;
1354 }
1355 // undef ^ X -> undef
1356 break;
1357
Chris Lattner1847f6d2006-12-20 06:21:33 +00001358 case Instruction::SDiv:
1359 case Instruction::UDiv:
1360 case Instruction::SRem:
1361 case Instruction::URem:
1362 // X / undef -> undef. No change.
1363 // X % undef -> undef. No change.
1364 if (Op1LV.isUndefined()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001365
Chris Lattner1847f6d2006-12-20 06:21:33 +00001366 // undef / X -> 0. X could be maxint.
1367 // undef % X -> 0. X could be 1.
Chris Lattnerf5484032009-11-02 05:55:40 +00001368 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001369 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +00001370
Chris Lattner1847f6d2006-12-20 06:21:33 +00001371 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001372 // X >>a undef -> undef.
1373 if (Op1LV.isUndefined()) break;
1374
1375 // undef >>a X -> all ones
1376 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001377 return true;
1378 case Instruction::LShr:
1379 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001380 // X << undef -> undef.
1381 // X >> undef -> undef.
1382 if (Op1LV.isUndefined()) break;
1383
1384 // undef << X -> 0
1385 // undef >> X -> 0
Chris Lattnerf5484032009-11-02 05:55:40 +00001386 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001387 return true;
1388 case Instruction::Select:
Eli Friedman0793eb42011-08-16 22:06:31 +00001389 Op1LV = getValueState(I->getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001390 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1391 if (Op0LV.isUndefined()) {
1392 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1393 Op1LV = getValueState(I->getOperand(2));
1394 } else if (Op1LV.isUndefined()) {
1395 // c ? undef : undef -> undef. No change.
1396 Op1LV = getValueState(I->getOperand(2));
1397 if (Op1LV.isUndefined())
1398 break;
1399 // Otherwise, c ? undef : x -> x.
1400 } else {
1401 // Leave Op1LV as Operand(1)'s LatticeValue.
1402 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001403
Chris Lattner1847f6d2006-12-20 06:21:33 +00001404 if (Op1LV.isConstant())
Chris Lattnerf5484032009-11-02 05:55:40 +00001405 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001406 else
Chris Lattnerf5484032009-11-02 05:55:40 +00001407 markOverdefined(I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001408 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001409 case Instruction::Load:
1410 // A load here means one of two things: a load of undef from a global,
1411 // a load from an unknown pointer. Either way, having it return undef
1412 // is okay.
1413 break;
1414 case Instruction::ICmp:
1415 // X == undef -> undef. Other comparisons get more complicated.
1416 if (cast<ICmpInst>(I)->isEquality())
1417 break;
1418 markOverdefined(I);
1419 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001420 case Instruction::Call:
1421 case Instruction::Invoke: {
1422 // There are two reasons a call can have an undef result
1423 // 1. It could be tracked.
1424 // 2. It could be constant-foldable.
1425 // Because of the way we solve return values, tracked calls must
1426 // never be marked overdefined in ResolvedUndefsIn.
1427 if (Function *F = CallSite(I).getCalledFunction())
1428 if (TrackedRetVals.count(F))
1429 break;
1430
1431 // If the call is constant-foldable, we mark it overdefined because
1432 // we do not know what return values are valid.
1433 markOverdefined(I);
1434 return true;
1435 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001436 default:
1437 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001438 // overdefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001439 markOverdefined(I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001440 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001441 }
1442 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001443
Chris Lattneradca6082010-04-05 22:14:48 +00001444 // Check to see if we have a branch or switch on an undefined value. If so
1445 // we force the branch to go one way or the other to make the successor
1446 // values live. It doesn't really matter which way we force it.
Chris Lattneraf170962006-10-22 05:59:17 +00001447 TerminatorInst *TI = BB->getTerminator();
1448 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1449 if (!BI->isConditional()) continue;
1450 if (!getValueState(BI->getCondition()).isUndefined())
1451 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001452
Chris Lattneradca6082010-04-05 22:14:48 +00001453 // If the input to SCCP is actually branch on undef, fix the undef to
1454 // false.
1455 if (isa<UndefValue>(BI->getCondition())) {
1456 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1457 markEdgeExecutable(BB, TI->getSuccessor(1));
1458 return true;
1459 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001460
Chris Lattneradca6082010-04-05 22:14:48 +00001461 // Otherwise, it is a branch on a symbolic value which is currently
1462 // considered to be undef. Handle this by forcing the input value to the
1463 // branch to false.
1464 markForcedConstant(BI->getCondition(),
1465 ConstantInt::getFalse(TI->getContext()));
1466 return true;
1467 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001468
Chris Lattneradca6082010-04-05 22:14:48 +00001469 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001470 if (!SI->getNumCases())
Dale Johannesenfecb8822008-05-23 01:01:31 +00001471 continue;
Chris Lattneraf170962006-10-22 05:59:17 +00001472 if (!getValueState(SI->getCondition()).isUndefined())
1473 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001474
Chris Lattneradca6082010-04-05 22:14:48 +00001475 // If the input to SCCP is actually switch on undef, fix the undef to
1476 // the first constant.
1477 if (isa<UndefValue>(SI->getCondition())) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001478 SI->setCondition(SI->case_begin().getCaseValue());
1479 markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001480 return true;
1481 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001482
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001483 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001484 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001485 }
Chris Lattneraf170962006-10-22 05:59:17 +00001486 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001487
Chris Lattneraf170962006-10-22 05:59:17 +00001488 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001489}
1490
Chris Lattner074be1f2004-11-15 04:44:20 +00001491
1492namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001493 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001494 //
Chris Lattner1890f942004-11-15 07:15:04 +00001495 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001496 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001497 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001498 struct SCCP : public FunctionPass {
Craig Topper3e4c6972014-03-05 09:10:37 +00001499 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiere6de63d2011-12-01 21:29:16 +00001500 AU.addRequired<TargetLibraryInfo>();
1501 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +00001502 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001503 SCCP() : FunctionPass(ID) {
1504 initializeSCCPPass(*PassRegistry::getPassRegistry());
1505 }
Devang Patel09f162c2007-05-01 21:15:47 +00001506
Chris Lattner1890f942004-11-15 07:15:04 +00001507 // runOnFunction - Run the Sparse Conditional Constant Propagation
1508 // algorithm, and return true if the function was modified.
1509 //
Craig Topper3e4c6972014-03-05 09:10:37 +00001510 bool runOnFunction(Function &F) override;
Chris Lattner1890f942004-11-15 07:15:04 +00001511 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001512} // end anonymous namespace
1513
Dan Gohmand78c4002008-05-13 00:00:25 +00001514char SCCP::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +00001515INITIALIZE_PASS(SCCP, "sccp",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001516 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner074be1f2004-11-15 04:44:20 +00001517
Chris Lattnera3c39d32009-11-02 02:33:50 +00001518// createSCCPPass - This is the public interface to this file.
Chris Lattner074be1f2004-11-15 04:44:20 +00001519FunctionPass *llvm::createSCCPPass() {
1520 return new SCCP();
1521}
1522
Chris Lattnere405ed92009-11-02 02:47:51 +00001523static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greene389fc3b2010-01-05 01:27:15 +00001524 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001525 ++NumDeadBlocks;
Bill Wendling770d0f02011-08-31 20:55:20 +00001526
1527 // Check to see if there are non-terminating instructions to delete.
1528 if (isa<TerminatorInst>(BB->begin()))
1529 return;
1530
Bill Wendling321fb372011-09-04 09:43:36 +00001531 // Delete the instructions backwards, as it has a reduced likelihood of having
1532 // to update as many def-use and use-def chains.
1533 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1534 while (EndInst != BB->begin()) {
1535 // Delete the next to last instruction.
1536 BasicBlock::iterator I = EndInst;
1537 Instruction *Inst = --I;
Bill Wendlingbf8280f2011-09-01 21:28:33 +00001538 if (!Inst->use_empty())
1539 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendling321fb372011-09-04 09:43:36 +00001540 if (isa<LandingPadInst>(Inst)) {
1541 EndInst = Inst;
Bill Wendling770d0f02011-08-31 20:55:20 +00001542 continue;
Bill Wendling321fb372011-09-04 09:43:36 +00001543 }
Bill Wendlingbf8280f2011-09-01 21:28:33 +00001544 BB->getInstList().erase(Inst);
Chris Lattnere405ed92009-11-02 02:47:51 +00001545 ++NumInstRemoved;
1546 }
1547}
Chris Lattner074be1f2004-11-15 04:44:20 +00001548
Chris Lattner074be1f2004-11-15 04:44:20 +00001549// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1550// and return true if the function was modified.
1551//
1552bool SCCP::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001553 if (skipOptnoneFunction(F))
1554 return false;
1555
David Greene389fc3b2010-01-05 01:27:15 +00001556 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola93512512014-02-25 17:30:31 +00001557 const DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1558 const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +00001559 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001560 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001561
1562 // Mark the first block of the function as being executable.
1563 Solver.MarkBlockExecutable(F.begin());
1564
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001565 // Mark all arguments to the function as being overdefined.
Chris Lattner28d921d2007-04-14 23:32:02 +00001566 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner156b8c72009-11-03 23:40:48 +00001567 Solver.markAnythingOverdefined(AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001568
Chris Lattner074be1f2004-11-15 04:44:20 +00001569 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001570 bool ResolvedUndefs = true;
1571 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001572 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001573 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001574 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001575 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001576
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001577 bool MadeChanges = false;
1578
1579 // If we decided that there are basic blocks that are dead in this function,
1580 // delete their contents now. Note that we cannot actually delete the blocks,
1581 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001582
Chris Lattnere405ed92009-11-02 02:47:51 +00001583 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattneradd44f32008-08-23 23:39:31 +00001584 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnere405ed92009-11-02 02:47:51 +00001585 DeleteInstructionInBlock(BB);
1586 MadeChanges = true;
1587 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001588 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001589
Chris Lattnere405ed92009-11-02 02:47:51 +00001590 // 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++;
1595 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1596 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001597
Chris Lattner156b8c72009-11-03 23:40:48 +00001598 // TODO: Reconstruct structs from their elements.
Duncan Sands19d0b472010-02-16 11:11:14 +00001599 if (Inst->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001600 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001601
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001602 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1603 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001604 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001605
Chris Lattnere405ed92009-11-02 02:47:51 +00001606 Constant *Const = IV.isConstant()
1607 ? IV.getConstant() : UndefValue::get(Inst->getType());
Nick Lewycky5cd95382013-06-26 00:30:18 +00001608 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Chris Lattnere405ed92009-11-02 02:47:51 +00001609
1610 // Replaces all of the uses of a variable with uses of the constant.
1611 Inst->replaceAllUsesWith(Const);
Jakub Staszak632a3552012-01-18 21:16:33 +00001612
Chris Lattnere405ed92009-11-02 02:47:51 +00001613 // Delete the instruction.
1614 Inst->eraseFromParent();
Jakub Staszak632a3552012-01-18 21:16:33 +00001615
Chris Lattnere405ed92009-11-02 02:47:51 +00001616 // Hey, we just changed something!
1617 MadeChanges = true;
1618 ++NumInstRemoved;
1619 }
1620 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001621
1622 return MadeChanges;
1623}
Chris Lattnerb4394642004-12-10 08:02:06 +00001624
1625namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001626 //===--------------------------------------------------------------------===//
1627 //
1628 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1629 /// Constant Propagation.
1630 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001631 struct IPSCCP : public ModulePass {
Craig Topper3e4c6972014-03-05 09:10:37 +00001632 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chad Rosiere6de63d2011-12-01 21:29:16 +00001633 AU.addRequired<TargetLibraryInfo>();
1634 }
Devang Patel8c78a0b2007-05-03 01:11:54 +00001635 static char ID;
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001636 IPSCCP() : ModulePass(ID) {
1637 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1638 }
Craig Topper3e4c6972014-03-05 09:10:37 +00001639 bool runOnModule(Module &M) override;
Chris Lattnerb4394642004-12-10 08:02:06 +00001640 };
Chris Lattnerb4394642004-12-10 08:02:06 +00001641} // end anonymous namespace
1642
Dan Gohmand78c4002008-05-13 00:00:25 +00001643char IPSCCP::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +00001644INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1645 "Interprocedural Sparse Conditional Constant Propagation",
1646 false, false)
1647INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1648INITIALIZE_PASS_END(IPSCCP, "ipsccp",
Owen Andersona57b97e2010-07-21 22:09:45 +00001649 "Interprocedural Sparse Conditional Constant Propagation",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001650 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +00001651
Chris Lattnera3c39d32009-11-02 02:33:50 +00001652// createIPSCCPPass - This is the public interface to this file.
Chris Lattnerb4394642004-12-10 08:02:06 +00001653ModulePass *llvm::createIPSCCPPass() {
1654 return new IPSCCP();
1655}
1656
1657
Gabor Greif9027ffb2010-03-24 10:29:52 +00001658static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001659 // Delete any dead constantexpr klingons.
1660 GV->removeDeadConstantUsers();
1661
Chandler Carruthcdf47882014-03-09 03:16:01 +00001662 for (const Use &U : GV->uses()) {
1663 const User *UR = U.getUser();
1664 if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001665 if (SI->getOperand(0) == GV || SI->isVolatile())
1666 return true; // Storing addr of GV.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001667 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001668 // Make sure we are calling the function, not passing the address.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001669 ImmutableCallSite CS(cast<Instruction>(UR));
1670 if (!CS.isCallee(&U))
Nick Lewyckyd73806a2008-11-03 03:49:14 +00001671 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001672 } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001673 if (LI->isVolatile())
1674 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001675 } else if (isa<BlockAddress>(UR)) {
Chris Lattner1a8b80e2009-11-01 06:11:53 +00001676 // blockaddress doesn't take the address of the function, it takes addr
1677 // of label.
Chris Lattner91dbae62004-12-11 05:15:59 +00001678 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001679 return true;
1680 }
Gabor Greif9027ffb2010-03-24 10:29:52 +00001681 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001682 return false;
1683}
1684
1685bool IPSCCP::runOnModule(Module &M) {
Rafael Espindola93512512014-02-25 17:30:31 +00001686 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1687 const DataLayout *DL = DLP ? &DLP->getDataLayout() : 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +00001688 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001689 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001690
Chris Lattner363226d2010-08-12 22:25:23 +00001691 // AddressTakenFunctions - This set keeps track of the address-taken functions
1692 // that are in the input. As IPSCCP runs through and simplifies code,
1693 // functions that were address taken can end up losing their
1694 // address-taken-ness. Because of this, we keep track of their addresses from
1695 // the first pass so we can use them for the later simplification pass.
1696 SmallPtrSet<Function*, 32> AddressTakenFunctions;
Jakub Staszak632a3552012-01-18 21:16:33 +00001697
Chris Lattnerb4394642004-12-10 08:02:06 +00001698 // Loop over all functions, marking arguments to those with their addresses
1699 // taken or that are external as overdefined.
1700 //
Chris Lattner47837c52009-11-02 06:34:04 +00001701 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1702 if (F->isDeclaration())
1703 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001704
Chris Lattnerfb141812009-11-03 03:42:51 +00001705 // If this is a strong or ODR definition of this function, then we can
1706 // propagate information about its result into callsites of it.
Chris Lattner156b8c72009-11-03 23:40:48 +00001707 if (!F->mayBeOverridden())
Chris Lattnerb4394642004-12-10 08:02:06 +00001708 Solver.AddTrackedFunction(F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001709
Chris Lattnerfb141812009-11-03 03:42:51 +00001710 // If this function only has direct calls that we can see, we can track its
1711 // arguments and return value aggressively, and can assume it is not called
1712 // unless we see evidence to the contrary.
Chris Lattner363226d2010-08-12 22:25:23 +00001713 if (F->hasLocalLinkage()) {
1714 if (AddressIsTaken(F))
1715 AddressTakenFunctions.insert(F);
1716 else {
1717 Solver.AddArgumentTrackedFunction(F);
1718 continue;
1719 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001720 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001721
1722 // Assume the function is called.
1723 Solver.MarkBlockExecutable(F->begin());
Jakub Staszak632a3552012-01-18 21:16:33 +00001724
Chris Lattnerfb141812009-11-03 03:42:51 +00001725 // Assume nothing about the incoming arguments.
1726 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1727 AI != E; ++AI)
Chris Lattner156b8c72009-11-03 23:40:48 +00001728 Solver.markAnythingOverdefined(AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001729 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001730
Chris Lattner91dbae62004-12-11 05:15:59 +00001731 // Loop over global variables. We inform the solver about any internal global
1732 // variables that do not have their 'addresses taken'. If they don't have
1733 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001734 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1735 G != E; ++G)
Rafael Espindola6de96a12009-01-15 20:18:42 +00001736 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattner91dbae62004-12-11 05:15:59 +00001737 Solver.TrackValueOfGlobalVariable(G);
1738
Chris Lattnerb4394642004-12-10 08:02:06 +00001739 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001740 bool ResolvedUndefs = true;
1741 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001742 Solver.Solve();
1743
David Greene389fc3b2010-01-05 01:27:15 +00001744 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001745 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001746 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001747 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001748 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001749
1750 bool MadeChanges = false;
1751
1752 // Iterate over all of the instructions in the module, replacing them with
1753 // constants if we have found them to be of constant values.
1754 //
Chris Lattner65938fc2008-08-23 23:36:38 +00001755 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001756
Chris Lattnerb4394642004-12-10 08:02:06 +00001757 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere82b0872009-11-02 03:25:55 +00001758 if (Solver.isBlockExecutable(F->begin())) {
1759 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1760 AI != E; ++AI) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001761 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001762
Chris Lattner156b8c72009-11-03 23:40:48 +00001763 // TODO: Could use getStructLatticeValueFor to find out if the entire
1764 // result is a constant and replace it entirely if so.
1765
Chris Lattnere82b0872009-11-02 03:25:55 +00001766 LatticeVal IV = Solver.getLatticeValueFor(AI);
1767 if (IV.isOverdefined()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001768
Chris Lattnere82b0872009-11-02 03:25:55 +00001769 Constant *CST = IV.isConstant() ?
1770 IV.getConstant() : UndefValue::get(AI->getType());
David Greene389fc3b2010-01-05 01:27:15 +00001771 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Jakub Staszak632a3552012-01-18 21:16:33 +00001772
Chris Lattnere82b0872009-11-02 03:25:55 +00001773 // Replaces all of the uses of a variable with uses of the
1774 // constant.
1775 AI->replaceAllUsesWith(CST);
1776 ++IPNumArgsElimed;
1777 }
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001778 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001779
Chris Lattnere405ed92009-11-02 02:47:51 +00001780 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattneradd44f32008-08-23 23:39:31 +00001781 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnere405ed92009-11-02 02:47:51 +00001782 DeleteInstructionInBlock(BB);
1783 MadeChanges = true;
Chris Lattner7285f432004-12-10 20:41:50 +00001784
Chris Lattnerbae4b642004-12-10 22:29:08 +00001785 TerminatorInst *TI = BB->getTerminator();
Chris Lattnerbae4b642004-12-10 22:29:08 +00001786 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1787 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmanc731c972007-10-03 19:26:29 +00001788 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattnerbae4b642004-12-10 22:29:08 +00001789 TI->getSuccessor(i)->removePredecessor(BB);
1790 }
Chris Lattner99e12952004-12-11 02:53:57 +00001791 if (!TI->use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001792 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnere405ed92009-11-02 02:47:51 +00001793 TI->eraseFromParent();
Chris Lattnerbae4b642004-12-10 22:29:08 +00001794
Chris Lattner8525ebe2004-12-11 05:32:19 +00001795 if (&*BB != &F->front())
1796 BlocksToErase.push_back(BB);
1797 else
Owen Anderson55f1c092009-08-13 21:58:54 +00001798 new UnreachableInst(M.getContext(), BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001799 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001800 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001801
Chris Lattnere405ed92009-11-02 02:47:51 +00001802 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1803 Instruction *Inst = BI++;
Duncan Sands19d0b472010-02-16 11:11:14 +00001804 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001805 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001806
Chris Lattner156b8c72009-11-03 23:40:48 +00001807 // TODO: Could use getStructLatticeValueFor to find out if the entire
1808 // result is a constant and replace it entirely if so.
Jakub Staszak632a3552012-01-18 21:16:33 +00001809
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001810 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1811 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001812 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001813
Chris Lattnere405ed92009-11-02 02:47:51 +00001814 Constant *Const = IV.isConstant()
1815 ? IV.getConstant() : UndefValue::get(Inst->getType());
Nick Lewycky5cd95382013-06-26 00:30:18 +00001816 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Chris Lattnere405ed92009-11-02 02:47:51 +00001817
1818 // Replaces all of the uses of a variable with uses of the
1819 // constant.
1820 Inst->replaceAllUsesWith(Const);
Jakub Staszak632a3552012-01-18 21:16:33 +00001821
Chris Lattnere405ed92009-11-02 02:47:51 +00001822 // Delete the instruction.
1823 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1824 Inst->eraseFromParent();
1825
1826 // Hey, we just changed something!
1827 MadeChanges = true;
1828 ++IPNumInstRemoved;
1829 }
1830 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001831
1832 // Now that all instructions in the function are constant folded, erase dead
1833 // blocks, because we can now use ConstantFoldTerminator to get rid of
1834 // in-edges.
1835 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1836 // If there are any PHI nodes in this successor, drop entries for BB now.
1837 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001838 for (Value::user_iterator UI = DeadBB->user_begin(),
1839 UE = DeadBB->user_end();
1840 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001841 // Grab the user and then increment the iterator early, as the user
1842 // will be deleted. Step past all adjacent uses from the same user.
1843 Instruction *I = dyn_cast<Instruction>(*UI);
1844 do { ++UI; } while (UI != UE && *UI == I);
1845
Dan Gohmand15302a2009-11-20 20:19:14 +00001846 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001847 if (!I) continue;
1848
Chris Lattnerbae4b642004-12-10 22:29:08 +00001849 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001850 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001851 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001852 // if this is a branch or switch on undef. Fold it manually as a
1853 // branch to the first successor.
Devang Patel45f1ae02008-11-21 01:52:59 +00001854#ifndef NDEBUG
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001855 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1856 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1857 "Branch should be foldable!");
1858 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1859 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1860 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001861 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001862 }
Devang Patel45f1ae02008-11-21 01:52:59 +00001863#endif
Jakub Staszak632a3552012-01-18 21:16:33 +00001864
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001865 // Make this an uncond branch to the first successor.
1866 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greife9ecc682008-04-06 20:25:17 +00001867 BranchInst::Create(TI->getSuccessor(0), TI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001868
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001869 // Remove entries in successor phi nodes to remove edges.
1870 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1871 TI->getSuccessor(i)->removePredecessor(TI->getParent());
Jakub Staszak632a3552012-01-18 21:16:33 +00001872
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001873 // Remove the old terminator.
1874 TI->eraseFromParent();
1875 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001876 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001877
Chris Lattnerbae4b642004-12-10 22:29:08 +00001878 // Finally, delete the basic block.
1879 F->getBasicBlockList().erase(DeadBB);
1880 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001881 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001882 }
Chris Lattner99e12952004-12-11 02:53:57 +00001883
1884 // If we inferred constant or undef return values for a function, we replaced
1885 // all call uses with the inferred value. This means we don't need to bother
1886 // actually returning anything from the function. Replace all return
1887 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001888 //
1889 // Do this in two stages: first identify the functions we should process, then
1890 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001891 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001892 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001893 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001894 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001895
Devang Patele418de32008-03-11 17:32:05 +00001896 // TODO: Process multiple value ret instructions also.
Devang Patela7a20752008-03-11 05:46:42 +00001897 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattner067d6072007-02-02 20:38:30 +00001898 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattnerfb141812009-11-03 03:42:51 +00001899 E = RV.end(); I != E; ++I) {
1900 Function *F = I->first;
1901 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1902 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001903
Chris Lattnerfb141812009-11-03 03:42:51 +00001904 // We can only do this if we know that nothing else can call the function.
Chris Lattner363226d2010-08-12 22:25:23 +00001905 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattnerfb141812009-11-03 03:42:51 +00001906 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001907
Chris Lattnerfb141812009-11-03 03:42:51 +00001908 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1909 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1910 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001911 ReturnsToZap.push_back(RI);
1912 }
1913
1914 // Zap all returns which we've identified as zap to change.
1915 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1916 Function *F = ReturnsToZap[i]->getParent()->getParent();
1917 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001918 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001919
Chad Rosierbb2a6da2012-03-28 00:35:33 +00001920 // If we inferred constant or undef values for globals variables, we can
1921 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001922 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1923 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001924 E = TG.end(); I != E; ++I) {
1925 GlobalVariable *GV = I->first;
1926 assert(!I->second.isOverdefined() &&
1927 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00001928 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00001929 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001930 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00001931 SI->eraseFromParent();
1932 }
1933 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001934 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001935 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001936
Chris Lattnerb4394642004-12-10 08:02:06 +00001937 return MadeChanges;
1938}