blob: 335ef3147d825fa4d52c8aae96598bb7345aa192 [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 Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/Instructions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/InstVisitor.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Pass.h"
35#include "llvm/Support/CallSite.h"
36#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 Lattner9c58cf62003-09-08 18:54:55 +0000494 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner646354b2004-10-16 18:09:41 +0000495 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Eli Friedman89b694b2011-07-27 01:08:30 +0000496 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Eli Friedman366bcce2011-08-02 21:35:16 +0000497 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
498 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez8acf2952009-10-23 21:09:37 +0000499 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner156b8c72009-11-03 23:40:48 +0000500 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000501
Chris Lattner113f4f42002-06-25 16:13:24 +0000502 void visitInstruction(Instruction &I) {
Chris Lattnera3c39d32009-11-02 02:33:50 +0000503 // If a new instruction is added to LLVM that we don't handle.
Nick Lewycky5cd95382013-06-26 00:30:18 +0000504 dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
Chris Lattner156b8c72009-11-03 23:40:48 +0000505 markAnythingOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000506 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000507};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000508
Duncan Sands2be91fc2007-07-20 08:56:21 +0000509} // end anonymous namespace
510
511
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000512// getFeasibleSuccessors - Return a vector of booleans to indicate which
513// successors are reachable from a given terminator instruction.
514//
Chris Lattner074be1f2004-11-15 04:44:20 +0000515void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000516 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000517 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000518 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000519 if (BI->isUnconditional()) {
520 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000521 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000522 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000523
Chris Lattnerf5484032009-11-02 05:55:40 +0000524 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000525 ConstantInt *CI = BCValue.getConstantInt();
526 if (CI == 0) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000527 // Overdefined condition variables, and branches on unfoldable constant
528 // conditions, mean the branch could go either way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000529 if (!BCValue.isUndefined())
530 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000531 return;
532 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000533
Chris Lattner6df5cec2009-11-02 02:30:06 +0000534 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000535 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000536 return;
537 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000538
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000539 if (isa<InvokeInst>(TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000540 // Invoke instructions successors are always executable.
541 Succs[0] = Succs[1] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000542 return;
543 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000544
Chris Lattneree8b9512009-10-29 01:21:20 +0000545 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000546 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000547 Succs[0] = true;
548 return;
549 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000550 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000551 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000552
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000553 if (CI == 0) { // Overdefined or undefined condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000554 // All destinations are executable!
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000555 if (!SCValue.isUndefined())
556 Succs.assign(TI.getNumSuccessors(), true);
557 return;
558 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000559
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000560 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000561 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000562 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000563
Chris Lattneree8b9512009-10-29 01:21:20 +0000564 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
565 if (isa<IndirectBrInst>(&TI)) {
566 // Just mark all destinations executable!
567 Succs.assign(TI.getNumSuccessors(), true);
568 return;
569 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000570
Chris Lattneree8b9512009-10-29 01:21:20 +0000571#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000572 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000573#endif
574 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000575}
576
577
Chris Lattner13b52e72002-05-02 21:18:01 +0000578// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000579// block to the 'To' basic block is currently feasible.
Chris Lattner13b52e72002-05-02 21:18:01 +0000580//
Chris Lattner074be1f2004-11-15 04:44:20 +0000581bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000582 assert(BBExecutable.count(To) && "Dest should always be alive!");
583
584 // Make sure the source basic block is executable!!
585 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000586
Chris Lattnera3c39d32009-11-02 02:33:50 +0000587 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000588 TerminatorInst *TI = From->getTerminator();
589 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
590 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000591 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000592
Chris Lattnerf5484032009-11-02 05:55:40 +0000593 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000594
Chris Lattner6df5cec2009-11-02 02:30:06 +0000595 // Overdefined condition variables mean the branch could go either way,
596 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000597 ConstantInt *CI = BCValue.getConstantInt();
598 if (CI == 0)
599 return !BCValue.isUndefined();
Jakub Staszak632a3552012-01-18 21:16:33 +0000600
Chris Lattner6df5cec2009-11-02 02:30:06 +0000601 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000602 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000603 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000604
Chris Lattneree8b9512009-10-29 01:21:20 +0000605 // Invoke instructions successors are always executable.
606 if (isa<InvokeInst>(TI))
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000607 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000608
Chris Lattneree8b9512009-10-29 01:21:20 +0000609 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000610 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000611 return true;
612
Chris Lattnerf5484032009-11-02 05:55:40 +0000613 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000614 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000615
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000616 if (CI == 0)
617 return !SCValue.isUndefined();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000618
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000619 return SI->findCaseValue(CI).getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000620 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000621
Chris Lattneree8b9512009-10-29 01:21:20 +0000622 // Just mark all destinations executable!
623 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman3de2ddc2011-05-21 19:13:10 +0000624 if (isa<IndirectBrInst>(TI))
Chris Lattneree8b9512009-10-29 01:21:20 +0000625 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000626
Chris Lattneree8b9512009-10-29 01:21:20 +0000627#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000628 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000629#endif
630 llvm_unreachable(0);
Chris Lattner13b52e72002-05-02 21:18:01 +0000631}
Chris Lattner347389d2001-06-27 23:38:11 +0000632
Chris Lattnera3c39d32009-11-02 02:33:50 +0000633// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000634// operand made a transition, or the instruction is newly executable. Change
635// the value type of I to reflect these changes if appropriate. This method
636// makes sure to do the following actions:
637//
638// 1. If a phi node merges two constants in, and has conflicting value coming
639// from different branches, or if the PHI node merges in an overdefined
640// value, then the PHI node becomes overdefined.
641// 2. If a phi node merges only constants in, and they all agree on value, the
642// PHI node becomes a constant value equal to that.
643// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
644// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
645// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
646// 6. If a conditional branch has a value that is constant, make the selected
647// destination executable
648// 7. If a conditional branch has a value that is overdefined, make all
649// successors executable.
650//
Chris Lattner074be1f2004-11-15 04:44:20 +0000651void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000652 // If this PN returns a struct, just mark the result overdefined.
653 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000654 if (PN.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000655 return markAnythingOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000656
Eli Friedman0a309292011-11-11 01:16:15 +0000657 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000658 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000659
Chris Lattner7a7b1142004-03-16 19:49:59 +0000660 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
661 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000662 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000663 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000664
Chris Lattner6e560792002-04-18 15:13:15 +0000665 // Look at all of the executable operands of the PHI node. If any of them
666 // are overdefined, the PHI becomes overdefined as well. If they are all
667 // constant, and they agree with each other, the PHI becomes the identical
668 // constant. If they are constant and don't agree, the PHI is overdefined.
669 // If there are no executable operands, the PHI remains undefined.
670 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000671 Constant *OperandVal = 0;
672 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000673 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000674 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000675
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000676 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
677 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000678
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000679 if (IV.isOverdefined()) // PHI node becomes overdefined!
680 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000681
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000682 if (OperandVal == 0) { // Grab the first value.
683 OperandVal = IV.getConstant();
684 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000685 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000686
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000687 // There is already a reachable operand. If we conflict with it,
688 // then the PHI node becomes overdefined. If we agree with it, we
689 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000690
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000691 // Check to see if there are two different constants merging, if so, the PHI
692 // node is overdefined.
693 if (IV.getConstant() != OperandVal)
694 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000695 }
696
Chris Lattner6e560792002-04-18 15:13:15 +0000697 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000698 // arguments that agree with each other(and OperandVal is the constant) or
699 // OperandVal is null because there are no defined incoming arguments. If
700 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000701 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000702 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000703 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000704}
705
Chris Lattnerb4394642004-12-10 08:02:06 +0000706void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000707 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000708
Chris Lattnerb4394642004-12-10 08:02:06 +0000709 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000710 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000711
Devang Patela7a20752008-03-11 05:46:42 +0000712 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000713 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000714 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000715 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000716 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000717 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000718 return;
719 }
720 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000721
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000722 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000723 if (!TrackedMultipleRetVals.empty()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000724 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000725 if (MRVFunctionsTracked.count(F))
726 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
727 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
728 getStructValueState(ResultOp, i));
Jakub Staszak632a3552012-01-18 21:16:33 +0000729
Chris Lattnerb4394642004-12-10 08:02:06 +0000730 }
731}
732
Chris Lattner074be1f2004-11-15 04:44:20 +0000733void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000734 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000735 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000736
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000737 BasicBlock *BB = TI.getParent();
738
Chris Lattnera3c39d32009-11-02 02:33:50 +0000739 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000740 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000741 if (SuccFeasible[i])
742 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000743}
744
Chris Lattner074be1f2004-11-15 04:44:20 +0000745void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000746 LatticeVal OpSt = getValueState(I.getOperand(0));
747 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000748 markOverdefined(&I);
Chris Lattnerf5484032009-11-02 05:55:40 +0000749 else if (OpSt.isConstant()) // Propagate constant value
Jakub Staszak632a3552012-01-18 21:16:33 +0000750 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattnerf5484032009-11-02 05:55:40 +0000751 OpSt.getConstant(), I.getType()));
Chris Lattner6e560792002-04-18 15:13:15 +0000752}
753
Chris Lattner156b8c72009-11-03 23:40:48 +0000754
Dan Gohman041f9d02008-06-20 01:15:44 +0000755void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000756 // If this returns a struct, mark all elements over defined, we don't track
757 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000758 if (EVI.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000759 return markAnythingOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000760
Chris Lattner156b8c72009-11-03 23:40:48 +0000761 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000762 if (EVI.getNumIndices() != 1)
763 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000764
Chris Lattner156b8c72009-11-03 23:40:48 +0000765 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000766 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000767 unsigned i = *EVI.idx_begin();
768 LatticeVal EltVal = getStructValueState(AggVal, i);
769 mergeInValue(getValueState(&EVI), &EVI, EltVal);
770 } else {
771 // Otherwise, must be extracting from an array.
772 return markOverdefined(&EVI);
773 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000774}
775
776void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000777 StructType *STy = dyn_cast<StructType>(IVI.getType());
Chris Lattner156b8c72009-11-03 23:40:48 +0000778 if (STy == 0)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000779 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000780
Chris Lattner156b8c72009-11-03 23:40:48 +0000781 // If this has more than one index, we can't handle it, drive all results to
782 // undef.
783 if (IVI.getNumIndices() != 1)
784 return markAnythingOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000785
Chris Lattner156b8c72009-11-03 23:40:48 +0000786 Value *Aggr = IVI.getAggregateOperand();
787 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000788
Chris Lattner156b8c72009-11-03 23:40:48 +0000789 // Compute the result based on what we're inserting.
790 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
791 // This passes through all values that aren't the inserted element.
792 if (i != Idx) {
793 LatticeVal EltVal = getStructValueState(Aggr, i);
794 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
795 continue;
796 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000797
Chris Lattner156b8c72009-11-03 23:40:48 +0000798 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000799 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000800 // We don't track structs in structs.
801 markOverdefined(getStructValueState(&IVI, i), &IVI);
802 else {
803 LatticeVal InVal = getValueState(Val);
804 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
805 }
806 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000807}
808
Chris Lattner074be1f2004-11-15 04:44:20 +0000809void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000810 // If this select returns a struct, just mark the result overdefined.
811 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000812 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000813 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000814
Chris Lattnerf5484032009-11-02 05:55:40 +0000815 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000816 if (CondValue.isUndefined())
817 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000818
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000819 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000820 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
821 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000822 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000823 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000824
Chris Lattner06a0ed12006-02-08 02:38:11 +0000825 // Otherwise, the condition is overdefined or a constant we can't evaluate.
826 // See if we can produce something better than overdefined based on the T/F
827 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000828 LatticeVal TVal = getValueState(I.getTrueValue());
829 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000830
Chris Lattner06a0ed12006-02-08 02:38:11 +0000831 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000832 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000833 TVal.getConstant() == FVal.getConstant())
834 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000835
Chris Lattnerf5484032009-11-02 05:55:40 +0000836 if (TVal.isUndefined()) // select ?, undef, X -> X.
837 return mergeInValue(&I, FVal);
838 if (FVal.isUndefined()) // select ?, X, undef -> X.
839 return mergeInValue(&I, TVal);
840 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000841}
842
Chris Lattnerf5484032009-11-02 05:55:40 +0000843// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000844void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000845 LatticeVal V1State = getValueState(I.getOperand(0));
846 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000847
Chris Lattner4f031622004-11-15 05:03:30 +0000848 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000849 if (IV.isOverdefined()) return;
850
Chris Lattnerf5484032009-11-02 05:55:40 +0000851 if (V1State.isConstant() && V2State.isConstant())
852 return markConstant(IV, &I,
853 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
854 V2State.getConstant()));
Jakub Staszak632a3552012-01-18 21:16:33 +0000855
Chris Lattnerf5484032009-11-02 05:55:40 +0000856 // If something is undef, wait for it to resolve.
857 if (!V1State.isOverdefined() && !V2State.isOverdefined())
858 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000859
Chris Lattnerf5484032009-11-02 05:55:40 +0000860 // Otherwise, one of our operands is overdefined. Try to produce something
861 // better than overdefined with some tricks.
Jakub Staszak632a3552012-01-18 21:16:33 +0000862
Chris Lattnerf5484032009-11-02 05:55:40 +0000863 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
864 // operand is overdefined.
865 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
866 LatticeVal *NonOverdefVal = 0;
867 if (!V1State.isOverdefined())
868 NonOverdefVal = &V1State;
869 else if (!V2State.isOverdefined())
870 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000871
Chris Lattnerf5484032009-11-02 05:55:40 +0000872 if (NonOverdefVal) {
873 if (NonOverdefVal->isUndefined()) {
874 // Could annihilate value.
875 if (I.getOpcode() == Instruction::And)
876 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner229907c2011-07-18 04:54:35 +0000877 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattnerf5484032009-11-02 05:55:40 +0000878 markConstant(IV, &I, Constant::getAllOnesValue(PT));
879 else
880 markConstant(IV, &I,
881 Constant::getAllOnesValue(I.getType()));
882 return;
Chris Lattnercbc01612004-12-11 23:15:19 +0000883 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000884
Chris Lattnerf5484032009-11-02 05:55:40 +0000885 if (I.getOpcode() == Instruction::And) {
886 // X and 0 = 0
887 if (NonOverdefVal->getConstant()->isNullValue())
888 return markConstant(IV, &I, NonOverdefVal->getConstant());
889 } else {
890 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
891 if (CI->isAllOnesValue()) // X or -1 = -1
892 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +0000893 }
894 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000895 }
Chris Lattnercbc01612004-12-11 23:15:19 +0000896
897
Chris Lattnerf5484032009-11-02 05:55:40 +0000898 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000899}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000900
Chris Lattnera3c39d32009-11-02 02:33:50 +0000901// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000902void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000903 LatticeVal V1State = getValueState(I.getOperand(0));
904 LatticeVal V2State = getValueState(I.getOperand(1));
905
Reid Spencer266e42b2006-12-23 06:05:41 +0000906 LatticeVal &IV = ValueState[&I];
907 if (IV.isOverdefined()) return;
908
Chris Lattnerf5484032009-11-02 05:55:40 +0000909 if (V1State.isConstant() && V2State.isConstant())
Jakub Staszak632a3552012-01-18 21:16:33 +0000910 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
911 V1State.getConstant(),
Chris Lattnerf5484032009-11-02 05:55:40 +0000912 V2State.getConstant()));
Jakub Staszak632a3552012-01-18 21:16:33 +0000913
Chris Lattnerf5484032009-11-02 05:55:40 +0000914 // If operands are still undefined, wait for it to resolve.
915 if (!V1State.isOverdefined() && !V2State.isOverdefined())
916 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000917
Chris Lattnerf5484032009-11-02 05:55:40 +0000918 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000919}
920
Robert Bocchinobd518d12006-01-10 19:05:05 +0000921void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000922 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000923 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000924
925#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000926 LatticeVal &ValState = getValueState(I.getOperand(0));
927 LatticeVal &IdxState = getValueState(I.getOperand(1));
928
929 if (ValState.isOverdefined() || IdxState.isOverdefined())
930 markOverdefined(&I);
931 else if(ValState.isConstant() && IdxState.isConstant())
932 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
933 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000934#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000935}
936
Robert Bocchino6dce2502006-01-17 20:06:55 +0000937void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000938 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000939 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000940#if 0
Robert Bocchino6dce2502006-01-17 20:06:55 +0000941 LatticeVal &ValState = getValueState(I.getOperand(0));
942 LatticeVal &EltState = getValueState(I.getOperand(1));
943 LatticeVal &IdxState = getValueState(I.getOperand(2));
944
945 if (ValState.isOverdefined() || EltState.isOverdefined() ||
946 IdxState.isOverdefined())
947 markOverdefined(&I);
948 else if(ValState.isConstant() && EltState.isConstant() &&
949 IdxState.isConstant())
950 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
951 EltState.getConstant(),
952 IdxState.getConstant()));
953 else if (ValState.isUndefined() && EltState.isConstant() &&
Jakub Staszak632a3552012-01-18 21:16:33 +0000954 IdxState.isConstant())
Chris Lattner28d921d2007-04-14 23:32:02 +0000955 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
956 EltState.getConstant(),
957 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000958#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000959}
960
Chris Lattner17bd6052006-04-08 01:19:12 +0000961void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000962 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000963 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000964#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000965 LatticeVal &V1State = getValueState(I.getOperand(0));
966 LatticeVal &V2State = getValueState(I.getOperand(1));
967 LatticeVal &MaskState = getValueState(I.getOperand(2));
968
969 if (MaskState.isUndefined() ||
970 (V1State.isUndefined() && V2State.isUndefined()))
971 return; // Undefined output if mask or both inputs undefined.
Jakub Staszak632a3552012-01-18 21:16:33 +0000972
Chris Lattner17bd6052006-04-08 01:19:12 +0000973 if (V1State.isOverdefined() || V2State.isOverdefined() ||
974 MaskState.isOverdefined()) {
975 markOverdefined(&I);
976 } else {
977 // A mix of constant/undef inputs.
Jakub Staszak632a3552012-01-18 21:16:33 +0000978 Constant *V1 = V1State.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +0000979 V1State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak632a3552012-01-18 21:16:33 +0000980 Constant *V2 = V2State.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +0000981 V2State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak632a3552012-01-18 21:16:33 +0000982 Constant *Mask = MaskState.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +0000983 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
984 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
985 }
Devang Patel21efc732006-12-04 23:54:59 +0000986#endif
Chris Lattner17bd6052006-04-08 01:19:12 +0000987}
988
Chris Lattnera3c39d32009-11-02 02:33:50 +0000989// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000990// can turn this into a getelementptr ConstantExpr.
991//
Chris Lattner074be1f2004-11-15 04:44:20 +0000992void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +0000993 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +0000994
Chris Lattner0e7ec672007-02-02 20:51:48 +0000995 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000996 Operands.reserve(I.getNumOperands());
997
998 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000999 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001000 if (State.isUndefined())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001001 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001002
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001003 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001004 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001005
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001006 assert(State.isConstant() && "Unknown state!");
1007 Operands.push_back(State.getConstant());
1008 }
1009
1010 Constant *Ptr = Operands[0];
Jay Foaded8db7d2011-07-21 14:31:17 +00001011 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1012 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001013}
Brian Gaeke960707c2003-11-11 22:41:34 +00001014
Chris Lattnerf5484032009-11-02 05:55:40 +00001015void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001016 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001017 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001018 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001019
Chris Lattner91dbae62004-12-11 05:15:59 +00001020 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1021 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001022
Chris Lattner91dbae62004-12-11 05:15:59 +00001023 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001024 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001025 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1026
Chris Lattnerf5484032009-11-02 05:55:40 +00001027 // Get the value we are storing into the global, then merge it.
1028 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001029 if (I->second.isOverdefined())
1030 TrackedGlobals.erase(I); // No need to keep tracking this!
1031}
1032
1033
Chris Lattner49f74522004-01-12 04:29:41 +00001034// Handle load instructions. If the operand is a constant pointer to a constant
1035// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001036void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001037 // If this load is of a struct, just mark the result overdefined.
Duncan Sands19d0b472010-02-16 11:11:14 +00001038 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001039 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001040
Chris Lattnerf5484032009-11-02 05:55:40 +00001041 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001042 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001043
Chris Lattner4f031622004-11-15 05:03:30 +00001044 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001045 if (IV.isOverdefined()) return;
1046
Chris Lattnerf5484032009-11-02 05:55:40 +00001047 if (!PtrVal.isConstant() || I.isVolatile())
1048 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001049
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001050 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001051
Chris Lattnerf5484032009-11-02 05:55:40 +00001052 // load null -> null
1053 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1054 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
Jakub Staszak632a3552012-01-18 21:16:33 +00001055
Chris Lattnerf5484032009-11-02 05:55:40 +00001056 // Transform load (constant global) into the value loaded.
1057 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001058 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001059 // If we are tracking this global, merge in the known value for it.
1060 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1061 TrackedGlobals.find(GV);
1062 if (It != TrackedGlobals.end()) {
1063 mergeInValue(IV, &I, It->second);
1064 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001065 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001066 }
Chris Lattner49f74522004-01-12 04:29:41 +00001067 }
1068
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001069 // Transform load from a constant into a constant if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001070 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL))
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001071 return markConstant(IV, &I, C);
Chris Lattnerf5484032009-11-02 05:55:40 +00001072
Chris Lattner49f74522004-01-12 04:29:41 +00001073 // Otherwise we cannot say for certain what value this load will produce.
1074 // Bail out.
1075 markOverdefined(IV, &I);
1076}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001077
Chris Lattnerb4394642004-12-10 08:02:06 +00001078void SCCPSolver::visitCallSite(CallSite CS) {
1079 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001080 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001081
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001082 // The common case is that we aren't tracking the callee, either because we
1083 // are not doing interprocedural analysis or the callee is indirect, or is
1084 // external. Handle these cases first.
Chris Lattnerfb141812009-11-03 03:42:51 +00001085 if (F == 0 || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001086CallOverdefined:
1087 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001088 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001089
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001090 // Otherwise, if we have a single return value case, and if the function is
1091 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001092 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001093 canConstantFoldCallTo(F)) {
Jakub Staszak632a3552012-01-18 21:16:33 +00001094
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001095 SmallVector<Constant*, 8> Operands;
1096 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1097 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001098 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001099
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001100 if (State.isUndefined())
1101 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001102 if (State.isOverdefined())
1103 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001104 assert(State.isConstant() && "Unknown state!");
1105 Operands.push_back(State.getConstant());
1106 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001107
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001108 // If we can constant fold this, mark the result of the call as a
1109 // constant.
Chad Rosiere6de63d2011-12-01 21:29:16 +00001110 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001111 return markConstant(I, C);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001112 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001113
1114 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner156b8c72009-11-03 23:40:48 +00001115 return markAnythingOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001116 }
1117
Chris Lattnercde8de52009-11-03 19:24:51 +00001118 // If this is a local function that doesn't have its address taken, mark its
1119 // entry block executable and merge in the actual arguments to the call into
1120 // the formal arguments of the function.
1121 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1122 MarkBlockExecutable(F->begin());
Jakub Staszak632a3552012-01-18 21:16:33 +00001123
Chris Lattnercde8de52009-11-03 19:24:51 +00001124 // Propagate information from this call site into the callee.
1125 CallSite::arg_iterator CAI = CS.arg_begin();
1126 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1127 AI != E; ++AI, ++CAI) {
1128 // If this argument is byval, and if the function is not readonly, there
1129 // will be an implicit copy formed of the input aggregate.
1130 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1131 markOverdefined(AI);
1132 continue;
1133 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001134
Chris Lattner229907c2011-07-18 04:54:35 +00001135 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001136 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1137 LatticeVal CallArg = getStructValueState(*CAI, i);
1138 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1139 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001140 } else {
1141 mergeInValue(AI, getValueState(*CAI));
1142 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001143 }
1144 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001145
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001146 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattner229907c2011-07-18 04:54:35 +00001147 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001148 if (!MRVFunctionsTracked.count(F))
1149 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001150
Chris Lattner156b8c72009-11-03 23:40:48 +00001151 // If we are tracking this callee, propagate the result of the function
1152 // into this call site.
1153 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001154 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001155 TrackedMultipleRetVals[std::make_pair(F, i)]);
1156 } else {
1157 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1158 if (TFRVI == TrackedRetVals.end())
1159 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001160
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001161 // If so, propagate the return value of the callee into this call result.
1162 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001163 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001164}
Chris Lattner074be1f2004-11-15 04:44:20 +00001165
Chris Lattner074be1f2004-11-15 04:44:20 +00001166void SCCPSolver::Solve() {
1167 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001168 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001169 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001170 // Process the overdefined instruction's work list first, which drives other
1171 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001172 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001173 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001174
David Greene389fc3b2010-01-05 01:27:15 +00001175 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001176
Chris Lattner074be1f2004-11-15 04:44:20 +00001177 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001178 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001179 //
1180 // Anything on this worklist that is overdefined need not be visited
1181 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001182 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001183 //
1184 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1185 UI != E; ++UI)
Chris Lattnerfb141812009-11-03 03:42:51 +00001186 if (Instruction *I = dyn_cast<Instruction>(*UI))
1187 OperandChangedState(I);
Chris Lattner074be1f2004-11-15 04:44:20 +00001188 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001189
Chris Lattnera3c39d32009-11-02 02:33:50 +00001190 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001191 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001192 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001193
David Greene389fc3b2010-01-05 01:27:15 +00001194 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001195
Chris Lattnerf5484032009-11-02 05:55:40 +00001196 // "I" got into the work list because it made the transition from undef to
1197 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001198 //
1199 // Anything on this worklist that is overdefined need not be visited
1200 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001201 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001202 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001203 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chris Lattner074be1f2004-11-15 04:44:20 +00001204 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1205 UI != E; ++UI)
Chris Lattnerfb141812009-11-03 03:42:51 +00001206 if (Instruction *I = dyn_cast<Instruction>(*UI))
1207 OperandChangedState(I);
Chris Lattner074be1f2004-11-15 04:44:20 +00001208 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001209
Chris Lattnera3c39d32009-11-02 02:33:50 +00001210 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001211 while (!BBWorkList.empty()) {
1212 BasicBlock *BB = BBWorkList.back();
1213 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001214
David Greene389fc3b2010-01-05 01:27:15 +00001215 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001216
Chris Lattner074be1f2004-11-15 04:44:20 +00001217 // Notify all instructions in this basic block that they are newly
1218 // executable.
1219 visit(BB);
1220 }
1221 }
1222}
1223
Chris Lattner1847f6d2006-12-20 06:21:33 +00001224/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001225/// that branches on undef values cannot reach any of their successors.
1226/// However, this is not a safe assumption. After we solve dataflow, this
1227/// method should be use to handle this. If this returns true, the solver
1228/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001229///
1230/// This method handles this by finding an unresolved branch and marking it one
1231/// of the edges from the block as being feasible, even though the condition
1232/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1233/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001234/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001235/// constraints on the condition of the branch, as that would impact other users
1236/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001237///
1238/// This scan also checks for values that use undefs, whose results are actually
1239/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1240/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1241/// even if X isn't defined.
1242bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001243 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1244 if (!BBExecutable.count(BB))
1245 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001246
Chris Lattner1847f6d2006-12-20 06:21:33 +00001247 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1248 // Look for instructions which produce undef values.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001249 if (I->getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001250
Chris Lattner229907c2011-07-18 04:54:35 +00001251 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001252 // Only a few things that can be structs matter for undef.
1253
1254 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1255 if (CallSite CS = CallSite(I))
1256 if (Function *F = CS.getCalledFunction())
1257 if (MRVFunctionsTracked.count(F))
1258 continue;
1259
1260 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001261 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001262 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1263 continue;
1264
1265 // Send the results of everything else to overdefined. We could be
1266 // more precise than this but it isn't worth bothering.
1267 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1268 LatticeVal &LV = getStructValueState(I, i);
1269 if (LV.isUndefined())
1270 markOverdefined(LV, I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001271 }
1272 continue;
1273 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001274
Chris Lattner1847f6d2006-12-20 06:21:33 +00001275 LatticeVal &LV = getValueState(I);
1276 if (!LV.isUndefined()) continue;
1277
Eli Friedmand7749be2011-08-17 18:10:43 +00001278 // extractvalue is safe; check here because the argument is a struct.
1279 if (isa<ExtractValueInst>(I))
1280 continue;
1281
1282 // Compute the operand LatticeVals, for convenience below.
1283 // Anything taking a struct is conservatively assumed to require
1284 // overdefined markings.
1285 if (I->getOperand(0)->getType()->isStructTy()) {
1286 markOverdefined(I);
1287 return true;
1288 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001289 LatticeVal Op0LV = getValueState(I->getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001290 LatticeVal Op1LV;
Eli Friedmand7749be2011-08-17 18:10:43 +00001291 if (I->getNumOperands() == 2) {
1292 if (I->getOperand(1)->getType()->isStructTy()) {
1293 markOverdefined(I);
1294 return true;
1295 }
1296
Chris Lattner1847f6d2006-12-20 06:21:33 +00001297 Op1LV = getValueState(I->getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001298 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001299 // If this is an instructions whose result is defined even if the input is
1300 // not fully defined, propagate the information.
Chris Lattner229907c2011-07-18 04:54:35 +00001301 Type *ITy = I->getType();
Chris Lattner1847f6d2006-12-20 06:21:33 +00001302 switch (I->getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001303 case Instruction::Add:
1304 case Instruction::Sub:
1305 case Instruction::Trunc:
1306 case Instruction::FPTrunc:
1307 case Instruction::BitCast:
1308 break; // Any undef -> undef
1309 case Instruction::FSub:
1310 case Instruction::FAdd:
1311 case Instruction::FMul:
1312 case Instruction::FDiv:
1313 case Instruction::FRem:
1314 // Floating-point binary operation: be conservative.
1315 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1316 markForcedConstant(I, Constant::getNullValue(ITy));
1317 else
1318 markOverdefined(I);
1319 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001320 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001321 case Instruction::SExt:
1322 case Instruction::FPToUI:
1323 case Instruction::FPToSI:
1324 case Instruction::FPExt:
1325 case Instruction::PtrToInt:
1326 case Instruction::IntToPtr:
1327 case Instruction::SIToFP:
1328 case Instruction::UIToFP:
1329 // undef -> 0; some outputs are impossible
Chris Lattnerf5484032009-11-02 05:55:40 +00001330 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001331 return true;
1332 case Instruction::Mul:
1333 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001334 // Both operands undef -> undef
1335 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1336 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001337 // undef * X -> 0. X could be zero.
1338 // undef & X -> 0. X could be zero.
Chris Lattnerf5484032009-11-02 05:55:40 +00001339 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001340 return true;
1341
1342 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001343 // Both operands undef -> undef
1344 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1345 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001346 // undef | X -> -1. X could be -1.
Chris Lattnerf5484032009-11-02 05:55:40 +00001347 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001348 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001349
Eli Friedman0793eb42011-08-16 22:06:31 +00001350 case Instruction::Xor:
1351 // undef ^ undef -> 0; strictly speaking, this is not strictly
1352 // necessary, but we try to be nice to people who expect this
1353 // behavior in simple cases
1354 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1355 markForcedConstant(I, Constant::getNullValue(ITy));
1356 return true;
1357 }
1358 // undef ^ X -> undef
1359 break;
1360
Chris Lattner1847f6d2006-12-20 06:21:33 +00001361 case Instruction::SDiv:
1362 case Instruction::UDiv:
1363 case Instruction::SRem:
1364 case Instruction::URem:
1365 // X / undef -> undef. No change.
1366 // X % undef -> undef. No change.
1367 if (Op1LV.isUndefined()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001368
Chris Lattner1847f6d2006-12-20 06:21:33 +00001369 // undef / X -> 0. X could be maxint.
1370 // undef % X -> 0. X could be 1.
Chris Lattnerf5484032009-11-02 05:55:40 +00001371 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001372 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +00001373
Chris Lattner1847f6d2006-12-20 06:21:33 +00001374 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001375 // X >>a undef -> undef.
1376 if (Op1LV.isUndefined()) break;
1377
1378 // undef >>a X -> all ones
1379 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001380 return true;
1381 case Instruction::LShr:
1382 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001383 // X << undef -> undef.
1384 // X >> undef -> undef.
1385 if (Op1LV.isUndefined()) break;
1386
1387 // undef << X -> 0
1388 // undef >> X -> 0
Chris Lattnerf5484032009-11-02 05:55:40 +00001389 markForcedConstant(I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001390 return true;
1391 case Instruction::Select:
Eli Friedman0793eb42011-08-16 22:06:31 +00001392 Op1LV = getValueState(I->getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001393 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1394 if (Op0LV.isUndefined()) {
1395 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1396 Op1LV = getValueState(I->getOperand(2));
1397 } else if (Op1LV.isUndefined()) {
1398 // c ? undef : undef -> undef. No change.
1399 Op1LV = getValueState(I->getOperand(2));
1400 if (Op1LV.isUndefined())
1401 break;
1402 // Otherwise, c ? undef : x -> x.
1403 } else {
1404 // Leave Op1LV as Operand(1)'s LatticeValue.
1405 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001406
Chris Lattner1847f6d2006-12-20 06:21:33 +00001407 if (Op1LV.isConstant())
Chris Lattnerf5484032009-11-02 05:55:40 +00001408 markForcedConstant(I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001409 else
Chris Lattnerf5484032009-11-02 05:55:40 +00001410 markOverdefined(I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001411 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001412 case Instruction::Load:
1413 // A load here means one of two things: a load of undef from a global,
1414 // a load from an unknown pointer. Either way, having it return undef
1415 // is okay.
1416 break;
1417 case Instruction::ICmp:
1418 // X == undef -> undef. Other comparisons get more complicated.
1419 if (cast<ICmpInst>(I)->isEquality())
1420 break;
1421 markOverdefined(I);
1422 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001423 case Instruction::Call:
1424 case Instruction::Invoke: {
1425 // There are two reasons a call can have an undef result
1426 // 1. It could be tracked.
1427 // 2. It could be constant-foldable.
1428 // Because of the way we solve return values, tracked calls must
1429 // never be marked overdefined in ResolvedUndefsIn.
1430 if (Function *F = CallSite(I).getCalledFunction())
1431 if (TrackedRetVals.count(F))
1432 break;
1433
1434 // If the call is constant-foldable, we mark it overdefined because
1435 // we do not know what return values are valid.
1436 markOverdefined(I);
1437 return true;
1438 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001439 default:
1440 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001441 // overdefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001442 markOverdefined(I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001443 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001444 }
1445 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001446
Chris Lattneradca6082010-04-05 22:14:48 +00001447 // Check to see if we have a branch or switch on an undefined value. If so
1448 // we force the branch to go one way or the other to make the successor
1449 // values live. It doesn't really matter which way we force it.
Chris Lattneraf170962006-10-22 05:59:17 +00001450 TerminatorInst *TI = BB->getTerminator();
1451 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1452 if (!BI->isConditional()) continue;
1453 if (!getValueState(BI->getCondition()).isUndefined())
1454 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001455
Chris Lattneradca6082010-04-05 22:14:48 +00001456 // If the input to SCCP is actually branch on undef, fix the undef to
1457 // false.
1458 if (isa<UndefValue>(BI->getCondition())) {
1459 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1460 markEdgeExecutable(BB, TI->getSuccessor(1));
1461 return true;
1462 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001463
Chris Lattneradca6082010-04-05 22:14:48 +00001464 // Otherwise, it is a branch on a symbolic value which is currently
1465 // considered to be undef. Handle this by forcing the input value to the
1466 // branch to false.
1467 markForcedConstant(BI->getCondition(),
1468 ConstantInt::getFalse(TI->getContext()));
1469 return true;
1470 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001471
Chris Lattneradca6082010-04-05 22:14:48 +00001472 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001473 if (!SI->getNumCases())
Dale Johannesenfecb8822008-05-23 01:01:31 +00001474 continue;
Chris Lattneraf170962006-10-22 05:59:17 +00001475 if (!getValueState(SI->getCondition()).isUndefined())
1476 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001477
Chris Lattneradca6082010-04-05 22:14:48 +00001478 // If the input to SCCP is actually switch on undef, fix the undef to
1479 // the first constant.
1480 if (isa<UndefValue>(SI->getCondition())) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001481 SI->setCondition(SI->case_begin().getCaseValue());
1482 markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001483 return true;
1484 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001485
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001486 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001487 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001488 }
Chris Lattneraf170962006-10-22 05:59:17 +00001489 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001490
Chris Lattneraf170962006-10-22 05:59:17 +00001491 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001492}
1493
Chris Lattner074be1f2004-11-15 04:44:20 +00001494
1495namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001496 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001497 //
Chris Lattner1890f942004-11-15 07:15:04 +00001498 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001499 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001500 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001501 struct SCCP : public FunctionPass {
Chad Rosiere6de63d2011-12-01 21:29:16 +00001502 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1503 AU.addRequired<TargetLibraryInfo>();
1504 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +00001505 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001506 SCCP() : FunctionPass(ID) {
1507 initializeSCCPPass(*PassRegistry::getPassRegistry());
1508 }
Devang Patel09f162c2007-05-01 21:15:47 +00001509
Chris Lattner1890f942004-11-15 07:15:04 +00001510 // runOnFunction - Run the Sparse Conditional Constant Propagation
1511 // algorithm, and return true if the function was modified.
1512 //
1513 bool runOnFunction(Function &F);
Chris Lattner1890f942004-11-15 07:15:04 +00001514 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001515} // end anonymous namespace
1516
Dan Gohmand78c4002008-05-13 00:00:25 +00001517char SCCP::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +00001518INITIALIZE_PASS(SCCP, "sccp",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001519 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner074be1f2004-11-15 04:44:20 +00001520
Chris Lattnera3c39d32009-11-02 02:33:50 +00001521// createSCCPPass - This is the public interface to this file.
Chris Lattner074be1f2004-11-15 04:44:20 +00001522FunctionPass *llvm::createSCCPPass() {
1523 return new SCCP();
1524}
1525
Chris Lattnere405ed92009-11-02 02:47:51 +00001526static void DeleteInstructionInBlock(BasicBlock *BB) {
David Greene389fc3b2010-01-05 01:27:15 +00001527 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001528 ++NumDeadBlocks;
Bill Wendling770d0f02011-08-31 20:55:20 +00001529
1530 // Check to see if there are non-terminating instructions to delete.
1531 if (isa<TerminatorInst>(BB->begin()))
1532 return;
1533
Bill Wendling321fb372011-09-04 09:43:36 +00001534 // Delete the instructions backwards, as it has a reduced likelihood of having
1535 // to update as many def-use and use-def chains.
1536 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1537 while (EndInst != BB->begin()) {
1538 // Delete the next to last instruction.
1539 BasicBlock::iterator I = EndInst;
1540 Instruction *Inst = --I;
Bill Wendlingbf8280f2011-09-01 21:28:33 +00001541 if (!Inst->use_empty())
1542 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendling321fb372011-09-04 09:43:36 +00001543 if (isa<LandingPadInst>(Inst)) {
1544 EndInst = Inst;
Bill Wendling770d0f02011-08-31 20:55:20 +00001545 continue;
Bill Wendling321fb372011-09-04 09:43:36 +00001546 }
Bill Wendlingbf8280f2011-09-01 21:28:33 +00001547 BB->getInstList().erase(Inst);
Chris Lattnere405ed92009-11-02 02:47:51 +00001548 ++NumInstRemoved;
1549 }
1550}
Chris Lattner074be1f2004-11-15 04:44:20 +00001551
Chris Lattner074be1f2004-11-15 04:44:20 +00001552// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1553// and return true if the function was modified.
1554//
1555bool SCCP::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001556 if (skipOptnoneFunction(F))
1557 return false;
1558
David Greene389fc3b2010-01-05 01:27:15 +00001559 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001560 const DataLayout *DL = getAnalysisIfAvailable<DataLayout>();
Chad Rosiere6de63d2011-12-01 21:29:16 +00001561 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001562 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001563
1564 // Mark the first block of the function as being executable.
1565 Solver.MarkBlockExecutable(F.begin());
1566
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001567 // Mark all arguments to the function as being overdefined.
Chris Lattner28d921d2007-04-14 23:32:02 +00001568 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
Chris Lattner156b8c72009-11-03 23:40:48 +00001569 Solver.markAnythingOverdefined(AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001570
Chris Lattner074be1f2004-11-15 04:44:20 +00001571 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001572 bool ResolvedUndefs = true;
1573 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001574 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001575 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001576 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001577 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001578
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001579 bool MadeChanges = false;
1580
1581 // If we decided that there are basic blocks that are dead in this function,
1582 // delete their contents now. Note that we cannot actually delete the blocks,
1583 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001584
Chris Lattnere405ed92009-11-02 02:47:51 +00001585 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattneradd44f32008-08-23 23:39:31 +00001586 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnere405ed92009-11-02 02:47:51 +00001587 DeleteInstructionInBlock(BB);
1588 MadeChanges = true;
1589 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001590 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001591
Chris Lattnere405ed92009-11-02 02:47:51 +00001592 // Iterate over all of the instructions in a function, replacing them with
1593 // constants if we have found them to be of constant values.
1594 //
1595 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1596 Instruction *Inst = BI++;
1597 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1598 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001599
Chris Lattner156b8c72009-11-03 23:40:48 +00001600 // TODO: Reconstruct structs from their elements.
Duncan Sands19d0b472010-02-16 11:11:14 +00001601 if (Inst->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001602 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001603
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001604 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1605 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001606 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001607
Chris Lattnere405ed92009-11-02 02:47:51 +00001608 Constant *Const = IV.isConstant()
1609 ? IV.getConstant() : UndefValue::get(Inst->getType());
Nick Lewycky5cd95382013-06-26 00:30:18 +00001610 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Chris Lattnere405ed92009-11-02 02:47:51 +00001611
1612 // Replaces all of the uses of a variable with uses of the constant.
1613 Inst->replaceAllUsesWith(Const);
Jakub Staszak632a3552012-01-18 21:16:33 +00001614
Chris Lattnere405ed92009-11-02 02:47:51 +00001615 // Delete the instruction.
1616 Inst->eraseFromParent();
Jakub Staszak632a3552012-01-18 21:16:33 +00001617
Chris Lattnere405ed92009-11-02 02:47:51 +00001618 // Hey, we just changed something!
1619 MadeChanges = true;
1620 ++NumInstRemoved;
1621 }
1622 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001623
1624 return MadeChanges;
1625}
Chris Lattnerb4394642004-12-10 08:02:06 +00001626
1627namespace {
Chris Lattnerb4394642004-12-10 08:02:06 +00001628 //===--------------------------------------------------------------------===//
1629 //
1630 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1631 /// Constant Propagation.
1632 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001633 struct IPSCCP : public ModulePass {
Chad Rosiere6de63d2011-12-01 21:29:16 +00001634 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1635 AU.addRequired<TargetLibraryInfo>();
1636 }
Devang Patel8c78a0b2007-05-03 01:11:54 +00001637 static char ID;
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001638 IPSCCP() : ModulePass(ID) {
1639 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1640 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001641 bool runOnModule(Module &M);
1642 };
Chris Lattnerb4394642004-12-10 08:02:06 +00001643} // end anonymous namespace
1644
Dan Gohmand78c4002008-05-13 00:00:25 +00001645char IPSCCP::ID = 0;
Chad Rosiere6de63d2011-12-01 21:29:16 +00001646INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1647 "Interprocedural Sparse Conditional Constant Propagation",
1648 false, false)
1649INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1650INITIALIZE_PASS_END(IPSCCP, "ipsccp",
Owen Andersona57b97e2010-07-21 22:09:45 +00001651 "Interprocedural Sparse Conditional Constant Propagation",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001652 false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +00001653
Chris Lattnera3c39d32009-11-02 02:33:50 +00001654// createIPSCCPPass - This is the public interface to this file.
Chris Lattnerb4394642004-12-10 08:02:06 +00001655ModulePass *llvm::createIPSCCPPass() {
1656 return new IPSCCP();
1657}
1658
1659
Gabor Greif9027ffb2010-03-24 10:29:52 +00001660static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001661 // Delete any dead constantexpr klingons.
1662 GV->removeDeadConstantUsers();
1663
Gabor Greifc78d7202010-03-25 23:06:16 +00001664 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
Gabor Greif9027ffb2010-03-24 10:29:52 +00001665 UI != E; ++UI) {
1666 const User *U = *UI;
1667 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001668 if (SI->getOperand(0) == GV || SI->isVolatile())
1669 return true; // Storing addr of GV.
Gabor Greif9027ffb2010-03-24 10:29:52 +00001670 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001671 // Make sure we are calling the function, not passing the address.
Gabor Greif5d5db532010-04-01 08:21:08 +00001672 ImmutableCallSite CS(cast<Instruction>(U));
Gabor Greifa2fbc0a2010-03-24 13:21:49 +00001673 if (!CS.isCallee(UI))
Nick Lewyckyd73806a2008-11-03 03:49:14 +00001674 return true;
Gabor Greif9027ffb2010-03-24 10:29:52 +00001675 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001676 if (LI->isVolatile())
1677 return true;
Gabor Greif9027ffb2010-03-24 10:29:52 +00001678 } else if (isa<BlockAddress>(U)) {
Chris Lattner1a8b80e2009-11-01 06:11:53 +00001679 // blockaddress doesn't take the address of the function, it takes addr
1680 // of label.
Chris Lattner91dbae62004-12-11 05:15:59 +00001681 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001682 return true;
1683 }
Gabor Greif9027ffb2010-03-24 10:29:52 +00001684 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001685 return false;
1686}
1687
1688bool IPSCCP::runOnModule(Module &M) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001689 const DataLayout *DL = getAnalysisIfAvailable<DataLayout>();
Chad Rosiere6de63d2011-12-01 21:29:16 +00001690 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001691 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001692
Chris Lattner363226d2010-08-12 22:25:23 +00001693 // AddressTakenFunctions - This set keeps track of the address-taken functions
1694 // that are in the input. As IPSCCP runs through and simplifies code,
1695 // functions that were address taken can end up losing their
1696 // address-taken-ness. Because of this, we keep track of their addresses from
1697 // the first pass so we can use them for the later simplification pass.
1698 SmallPtrSet<Function*, 32> AddressTakenFunctions;
Jakub Staszak632a3552012-01-18 21:16:33 +00001699
Chris Lattnerb4394642004-12-10 08:02:06 +00001700 // Loop over all functions, marking arguments to those with their addresses
1701 // taken or that are external as overdefined.
1702 //
Chris Lattner47837c52009-11-02 06:34:04 +00001703 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1704 if (F->isDeclaration())
1705 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001706
Chris Lattnerfb141812009-11-03 03:42:51 +00001707 // If this is a strong or ODR definition of this function, then we can
1708 // propagate information about its result into callsites of it.
Chris Lattner156b8c72009-11-03 23:40:48 +00001709 if (!F->mayBeOverridden())
Chris Lattnerb4394642004-12-10 08:02:06 +00001710 Solver.AddTrackedFunction(F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001711
Chris Lattnerfb141812009-11-03 03:42:51 +00001712 // If this function only has direct calls that we can see, we can track its
1713 // arguments and return value aggressively, and can assume it is not called
1714 // unless we see evidence to the contrary.
Chris Lattner363226d2010-08-12 22:25:23 +00001715 if (F->hasLocalLinkage()) {
1716 if (AddressIsTaken(F))
1717 AddressTakenFunctions.insert(F);
1718 else {
1719 Solver.AddArgumentTrackedFunction(F);
1720 continue;
1721 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001722 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001723
1724 // Assume the function is called.
1725 Solver.MarkBlockExecutable(F->begin());
Jakub Staszak632a3552012-01-18 21:16:33 +00001726
Chris Lattnerfb141812009-11-03 03:42:51 +00001727 // Assume nothing about the incoming arguments.
1728 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1729 AI != E; ++AI)
Chris Lattner156b8c72009-11-03 23:40:48 +00001730 Solver.markAnythingOverdefined(AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001731 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001732
Chris Lattner91dbae62004-12-11 05:15:59 +00001733 // Loop over global variables. We inform the solver about any internal global
1734 // variables that do not have their 'addresses taken'. If they don't have
1735 // their addresses taken, we can propagate constants through them.
Chris Lattner8cb10a12005-04-19 19:16:19 +00001736 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1737 G != E; ++G)
Rafael Espindola6de96a12009-01-15 20:18:42 +00001738 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Chris Lattner91dbae62004-12-11 05:15:59 +00001739 Solver.TrackValueOfGlobalVariable(G);
1740
Chris Lattnerb4394642004-12-10 08:02:06 +00001741 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001742 bool ResolvedUndefs = true;
1743 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001744 Solver.Solve();
1745
David Greene389fc3b2010-01-05 01:27:15 +00001746 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001747 ResolvedUndefs = false;
Chris Lattner7285f432004-12-10 20:41:50 +00001748 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Chris Lattner1847f6d2006-12-20 06:21:33 +00001749 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
Chris Lattner7285f432004-12-10 20:41:50 +00001750 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001751
1752 bool MadeChanges = false;
1753
1754 // Iterate over all of the instructions in the module, replacing them with
1755 // constants if we have found them to be of constant values.
1756 //
Chris Lattner65938fc2008-08-23 23:36:38 +00001757 SmallVector<BasicBlock*, 512> BlocksToErase;
Chris Lattner37d400a2007-02-02 21:15:06 +00001758
Chris Lattnerb4394642004-12-10 08:02:06 +00001759 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattnere82b0872009-11-02 03:25:55 +00001760 if (Solver.isBlockExecutable(F->begin())) {
1761 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1762 AI != E; ++AI) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001763 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001764
Chris Lattner156b8c72009-11-03 23:40:48 +00001765 // TODO: Could use getStructLatticeValueFor to find out if the entire
1766 // result is a constant and replace it entirely if so.
1767
Chris Lattnere82b0872009-11-02 03:25:55 +00001768 LatticeVal IV = Solver.getLatticeValueFor(AI);
1769 if (IV.isOverdefined()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001770
Chris Lattnere82b0872009-11-02 03:25:55 +00001771 Constant *CST = IV.isConstant() ?
1772 IV.getConstant() : UndefValue::get(AI->getType());
David Greene389fc3b2010-01-05 01:27:15 +00001773 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Jakub Staszak632a3552012-01-18 21:16:33 +00001774
Chris Lattnere82b0872009-11-02 03:25:55 +00001775 // Replaces all of the uses of a variable with uses of the
1776 // constant.
1777 AI->replaceAllUsesWith(CST);
1778 ++IPNumArgsElimed;
1779 }
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001780 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001781
Chris Lattnere405ed92009-11-02 02:47:51 +00001782 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattneradd44f32008-08-23 23:39:31 +00001783 if (!Solver.isBlockExecutable(BB)) {
Chris Lattnere405ed92009-11-02 02:47:51 +00001784 DeleteInstructionInBlock(BB);
1785 MadeChanges = true;
Chris Lattner7285f432004-12-10 20:41:50 +00001786
Chris Lattnerbae4b642004-12-10 22:29:08 +00001787 TerminatorInst *TI = BB->getTerminator();
Chris Lattnerbae4b642004-12-10 22:29:08 +00001788 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1789 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohmanc731c972007-10-03 19:26:29 +00001790 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Chris Lattnerbae4b642004-12-10 22:29:08 +00001791 TI->getSuccessor(i)->removePredecessor(BB);
1792 }
Chris Lattner99e12952004-12-11 02:53:57 +00001793 if (!TI->use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +00001794 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattnere405ed92009-11-02 02:47:51 +00001795 TI->eraseFromParent();
Chris Lattnerbae4b642004-12-10 22:29:08 +00001796
Chris Lattner8525ebe2004-12-11 05:32:19 +00001797 if (&*BB != &F->front())
1798 BlocksToErase.push_back(BB);
1799 else
Owen Anderson55f1c092009-08-13 21:58:54 +00001800 new UnreachableInst(M.getContext(), BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001801 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001802 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001803
Chris Lattnere405ed92009-11-02 02:47:51 +00001804 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1805 Instruction *Inst = BI++;
Duncan Sands19d0b472010-02-16 11:11:14 +00001806 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001807 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001808
Chris Lattner156b8c72009-11-03 23:40:48 +00001809 // TODO: Could use getStructLatticeValueFor to find out if the entire
1810 // result is a constant and replace it entirely if so.
Jakub Staszak632a3552012-01-18 21:16:33 +00001811
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001812 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1813 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001814 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001815
Chris Lattnere405ed92009-11-02 02:47:51 +00001816 Constant *Const = IV.isConstant()
1817 ? IV.getConstant() : UndefValue::get(Inst->getType());
Nick Lewycky5cd95382013-06-26 00:30:18 +00001818 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Chris Lattnere405ed92009-11-02 02:47:51 +00001819
1820 // Replaces all of the uses of a variable with uses of the
1821 // constant.
1822 Inst->replaceAllUsesWith(Const);
Jakub Staszak632a3552012-01-18 21:16:33 +00001823
Chris Lattnere405ed92009-11-02 02:47:51 +00001824 // Delete the instruction.
1825 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1826 Inst->eraseFromParent();
1827
1828 // Hey, we just changed something!
1829 MadeChanges = true;
1830 ++IPNumInstRemoved;
1831 }
1832 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001833
1834 // Now that all instructions in the function are constant folded, erase dead
1835 // blocks, because we can now use ConstantFoldTerminator to get rid of
1836 // in-edges.
1837 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1838 // If there are any PHI nodes in this successor, drop entries for BB now.
1839 BasicBlock *DeadBB = BlocksToErase[i];
Dan Gohmand15302a2009-11-20 20:19:14 +00001840 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1841 UI != UE; ) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001842 // Grab the user and then increment the iterator early, as the user
1843 // will be deleted. Step past all adjacent uses from the same user.
1844 Instruction *I = dyn_cast<Instruction>(*UI);
1845 do { ++UI; } while (UI != UE && *UI == I);
1846
Dan Gohmand15302a2009-11-20 20:19:14 +00001847 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001848 if (!I) continue;
1849
Chris Lattnerbae4b642004-12-10 22:29:08 +00001850 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001851 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001852 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001853 // if this is a branch or switch on undef. Fold it manually as a
1854 // branch to the first successor.
Devang Patel45f1ae02008-11-21 01:52:59 +00001855#ifndef NDEBUG
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001856 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1857 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1858 "Branch should be foldable!");
1859 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1860 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1861 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001862 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001863 }
Devang Patel45f1ae02008-11-21 01:52:59 +00001864#endif
Jakub Staszak632a3552012-01-18 21:16:33 +00001865
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001866 // Make this an uncond branch to the first successor.
1867 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greife9ecc682008-04-06 20:25:17 +00001868 BranchInst::Create(TI->getSuccessor(0), TI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001869
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001870 // Remove entries in successor phi nodes to remove edges.
1871 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1872 TI->getSuccessor(i)->removePredecessor(TI->getParent());
Jakub Staszak632a3552012-01-18 21:16:33 +00001873
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001874 // Remove the old terminator.
1875 TI->eraseFromParent();
1876 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001877 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001878
Chris Lattnerbae4b642004-12-10 22:29:08 +00001879 // Finally, delete the basic block.
1880 F->getBasicBlockList().erase(DeadBB);
1881 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001882 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001883 }
Chris Lattner99e12952004-12-11 02:53:57 +00001884
1885 // If we inferred constant or undef return values for a function, we replaced
1886 // all call uses with the inferred value. This means we don't need to bother
1887 // actually returning anything from the function. Replace all return
1888 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001889 //
1890 // Do this in two stages: first identify the functions we should process, then
1891 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001892 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001893 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001894 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001895 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001896
Devang Patele418de32008-03-11 17:32:05 +00001897 // TODO: Process multiple value ret instructions also.
Devang Patela7a20752008-03-11 05:46:42 +00001898 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattner067d6072007-02-02 20:38:30 +00001899 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattnerfb141812009-11-03 03:42:51 +00001900 E = RV.end(); I != E; ++I) {
1901 Function *F = I->first;
1902 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1903 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001904
Chris Lattnerfb141812009-11-03 03:42:51 +00001905 // We can only do this if we know that nothing else can call the function.
Chris Lattner363226d2010-08-12 22:25:23 +00001906 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattnerfb141812009-11-03 03:42:51 +00001907 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001908
Chris Lattnerfb141812009-11-03 03:42:51 +00001909 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1910 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1911 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001912 ReturnsToZap.push_back(RI);
1913 }
1914
1915 // Zap all returns which we've identified as zap to change.
1916 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1917 Function *F = ReturnsToZap[i]->getParent()->getParent();
1918 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001919 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001920
Chad Rosierbb2a6da2012-03-28 00:35:33 +00001921 // If we inferred constant or undef values for globals variables, we can
1922 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001923 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1924 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001925 E = TG.end(); I != E; ++I) {
1926 GlobalVariable *GV = I->first;
1927 assert(!I->second.isOverdefined() &&
1928 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00001929 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00001930 while (!GV->use_empty()) {
1931 StoreInst *SI = cast<StoreInst>(GV->use_back());
1932 SI->eraseFromParent();
1933 }
1934 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001935 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001936 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001937
Chris Lattnerb4394642004-12-10 08:02:06 +00001938 return MadeChanges;
1939}