blob: e9fe766ba6f7d6bf899f7c13c4ed29ce4ce85b93 [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
Davide Italianof54f2f02016-05-05 21:05:36 +000020#include "llvm/Transforms/IPO/SCCP.h"
Chris Lattner067d6072007-02-02 20:38:30 +000021#include "llvm/ADT/DenseMap.h"
Chris Lattner65938fc2008-08-23 23:36:38 +000022#include "llvm/ADT/DenseSet.h"
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000023#include "llvm/ADT/PointerIntPair.h"
Chris Lattner809aee22009-11-02 06:11:23 +000024#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0d74d3c2007-01-30 23:15:19 +000025#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000026#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/ConstantFolding.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000028#include "llvm/Analysis/GlobalsModRef.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000029#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000034#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Instructions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Support/Debug.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/Transforms/IPO.h"
Davide Italianof54f2f02016-05-05 21:05:36 +000041#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000042#include "llvm/Transforms/Utils/Local.h"
Chris Lattner347389d2001-06-27 23:38:11 +000043#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000044using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000045
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "sccp"
47
Chris Lattner79a42ac2006-12-19 21:40:18 +000048STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewycky35e92c72008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Chris Lattner79a42ac2006-12-19 21:40:18 +000052STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
Chris Lattner7d325382002-04-29 21:26:08 +000055namespace {
Chris Lattner1847f6d2006-12-20 06:21:33 +000056/// LatticeVal class - This class represents the different lattice values that
57/// an LLVM value may occupy. It is a simple class with value semantics.
58///
Chris Lattner2dd09db2009-09-02 06:11:42 +000059class LatticeVal {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000060 enum LatticeValueTy {
Chris Lattner1847f6d2006-12-20 06:21:33 +000061 /// undefined - This LLVM Value has no known value yet.
62 undefined,
Jakub Staszak632a3552012-01-18 21:16:33 +000063
Chris Lattner1847f6d2006-12-20 06:21:33 +000064 /// constant - This LLVM Value has a specific constant value.
65 constant,
66
67 /// forcedconstant - This LLVM Value was thought to be undef until
68 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
69 /// with another (different) constant, it goes to overdefined, instead of
70 /// asserting.
71 forcedconstant,
Jakub Staszak632a3552012-01-18 21:16:33 +000072
Chris Lattner1847f6d2006-12-20 06:21:33 +000073 /// overdefined - This instruction is not known to be constant, and we know
74 /// it has a value.
75 overdefined
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000076 };
77
78 /// Val: This stores the current lattice value along with the Constant* for
79 /// the constant if this is a 'constant' or 'forcedconstant' value.
80 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Jakub Staszak632a3552012-01-18 21:16:33 +000081
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000082 LatticeValueTy getLatticeValue() const {
83 return Val.getInt();
84 }
Jakub Staszak632a3552012-01-18 21:16:33 +000085
Chris Lattner347389d2001-06-27 23:38:11 +000086public:
Craig Topperf40110f2014-04-25 05:29:35 +000087 LatticeVal() : Val(nullptr, undefined) {}
Jakub Staszak632a3552012-01-18 21:16:33 +000088
Chris Lattner7ccf1a62009-11-02 03:03:42 +000089 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000091 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 }
Chris Lattner7ccf1a62009-11-02 03:03:42 +000093 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Jakub Staszak632a3552012-01-18 21:16:33 +000094
Chris Lattner7ccf1a62009-11-02 03:03:42 +000095 Constant *getConstant() const {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +000096 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
98 }
Jakub Staszak632a3552012-01-18 21:16:33 +000099
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000100 /// markOverdefined - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000101 bool markOverdefined() {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000102 if (isOverdefined())
103 return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000104
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000105 Val.setInt(overdefined);
106 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000107 }
108
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000109 /// markConstant - Return true if this is a change in status.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000110 bool markConstant(Constant *V) {
Chris Lattnere1d5cd92009-11-03 16:50:11 +0000111 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000112 assert(getConstant() == V && "Marking constant with different value");
113 return false;
Chris Lattner347389d2001-06-27 23:38:11 +0000114 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000115
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000116 if (isUndefined()) {
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
119 Val.setPointer(V);
120 } else {
Jakub Staszak632a3552012-01-18 21:16:33 +0000121 assert(getLatticeValue() == forcedconstant &&
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
Jakub Staszak632a3552012-01-18 21:16:33 +0000125
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000126 // Otherwise, we go to overdefined. Assumptions made based on the
127 // forced value are possibly wrong. Assuming this is another constant
128 // could expose a contradiction.
129 Val.setInt(overdefined);
130 }
131 return true;
Chris Lattner347389d2001-06-27 23:38:11 +0000132 }
133
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000134 /// getConstantInt - If this is a constant with a ConstantInt value, return it
135 /// otherwise return null.
136 ConstantInt *getConstantInt() const {
137 if (isConstant())
138 return dyn_cast<ConstantInt>(getConstant());
Craig Topperf40110f2014-04-25 05:29:35 +0000139 return nullptr;
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000140 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000141
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000142 void markForcedConstant(Constant *V) {
Chris Lattnerefdd2bb2009-11-02 02:20:32 +0000143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
145 Val.setPointer(V);
Chris Lattner05fe6842004-01-12 03:57:30 +0000146 }
Chris Lattner347389d2001-06-27 23:38:11 +0000147};
Chris Lattnere405ed92009-11-02 02:47:51 +0000148} // end anonymous namespace.
149
150
151namespace {
Chris Lattner347389d2001-06-27 23:38:11 +0000152
Chris Lattner347389d2001-06-27 23:38:11 +0000153//===----------------------------------------------------------------------===//
Chris Lattner347389d2001-06-27 23:38:11 +0000154//
Chris Lattner074be1f2004-11-15 04:44:20 +0000155/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156/// Constant Propagation.
157///
158class SCCPSolver : public InstVisitor<SCCPSolver> {
Mehdi Amini46a43552015-03-04 18:43:29 +0000159 const DataLayout &DL;
Chad Rosiere6de63d2011-12-01 21:29:16 +0000160 const TargetLibraryInfo *TLI;
Nick Lewycky77cb8e62011-07-25 21:16:04 +0000161 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
Chris Lattnerf5484032009-11-02 05:55:40 +0000162 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Chris Lattner347389d2001-06-27 23:38:11 +0000163
Chris Lattner156b8c72009-11-03 23:40:48 +0000164 /// StructValueState - This maintains ValueState for values that have
165 /// StructType, for example for formal arguments, calls, insertelement, etc.
166 ///
167 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
Jakub Staszak632a3552012-01-18 21:16:33 +0000168
Chris Lattner91dbae62004-12-11 05:15:59 +0000169 /// GlobalValue - If we are tracking any values for the contents of a global
170 /// variable, we keep a mapping from the constant accessor to the element of
171 /// the global, to the currently known value. If the value becomes
172 /// overdefined, it's entry is simply removed from this map.
Chris Lattner067d6072007-02-02 20:38:30 +0000173 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
Chris Lattner91dbae62004-12-11 05:15:59 +0000174
Devang Patela7a20752008-03-11 05:46:42 +0000175 /// TrackedRetVals - If we are tracking arguments into and the return
Chris Lattnerb4394642004-12-10 08:02:06 +0000176 /// value out of a function, it will have an entry in this map, indicating
177 /// what the known return value for the function is.
Devang Patela7a20752008-03-11 05:46:42 +0000178 DenseMap<Function*, LatticeVal> TrackedRetVals;
179
180 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
181 /// that return multiple values.
Chris Lattner65938fc2008-08-23 23:36:38 +0000182 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Jakub Staszak632a3552012-01-18 21:16:33 +0000183
Chris Lattner156b8c72009-11-03 23:40:48 +0000184 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
185 /// represented here for efficient lookup.
186 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
Chris Lattnerb4394642004-12-10 08:02:06 +0000187
Chris Lattner2c427232009-11-03 20:52:57 +0000188 /// TrackingIncomingArguments - This is the set of functions for whose
189 /// arguments we make optimistic assumptions about and try to prove as
190 /// constants.
Chris Lattnercde8de52009-11-03 19:24:51 +0000191 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
Jakub Staszak632a3552012-01-18 21:16:33 +0000192
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000193 /// The reason for two worklists is that overdefined is the lowest state
194 /// on the lattice, and moving things to overdefined as fast as possible
195 /// makes SCCP converge much faster.
196 ///
197 /// By having a separate worklist, we accomplish this because everything
198 /// possibly overdefined will become overdefined at the soonest possible
199 /// point.
Chris Lattner65938fc2008-08-23 23:36:38 +0000200 SmallVector<Value*, 64> OverdefinedInstWorkList;
201 SmallVector<Value*, 64> InstWorkList;
Chris Lattnerd79334d2004-07-15 23:36:43 +0000202
203
Chris Lattner65938fc2008-08-23 23:36:38 +0000204 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000205
206 /// KnownFeasibleEdges - Entries in this set are edges which have already had
207 /// PHI nodes retriggered.
Chris Lattner65938fc2008-08-23 23:36:38 +0000208 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
209 DenseSet<Edge> KnownFeasibleEdges;
Chris Lattner347389d2001-06-27 23:38:11 +0000210public:
Mehdi Amini46a43552015-03-04 18:43:29 +0000211 SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
212 : DL(DL), TLI(tli) {}
Chris Lattner347389d2001-06-27 23:38:11 +0000213
Chris Lattner074be1f2004-11-15 04:44:20 +0000214 /// MarkBlockExecutable - This method can be used by clients to mark all of
215 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattner809aee22009-11-02 06:11:23 +0000216 ///
217 /// This returns true if the block was not considered live before.
218 bool MarkBlockExecutable(BasicBlock *BB) {
David Blaikie70573dc2014-11-19 07:49:26 +0000219 if (!BBExecutable.insert(BB).second)
220 return false;
Nick Lewycky5cd95382013-06-26 00:30:18 +0000221 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
Chris Lattner074be1f2004-11-15 04:44:20 +0000222 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattner809aee22009-11-02 06:11:23 +0000223 return true;
Chris Lattner7d325382002-04-29 21:26:08 +0000224 }
225
Chris Lattner91dbae62004-12-11 05:15:59 +0000226 /// TrackValueOfGlobalVariable - Clients can use this method to
Chris Lattnerb4394642004-12-10 08:02:06 +0000227 /// inform the SCCPSolver that it should track loads and stores to the
228 /// specified global variable if it can. This is only legal to call if
229 /// performing Interprocedural SCCP.
Chris Lattner91dbae62004-12-11 05:15:59 +0000230 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000231 // We only track the contents of scalar globals.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000232 if (GV->getValueType()->isSingleValueType()) {
Chris Lattner91dbae62004-12-11 05:15:59 +0000233 LatticeVal &IV = TrackedGlobals[GV];
234 if (!isa<UndefValue>(GV->getInitializer()))
235 IV.markConstant(GV->getInitializer());
236 }
237 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000238
239 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
240 /// and out of the specified function (which cannot have its address taken),
241 /// this method must be called.
242 void AddTrackedFunction(Function *F) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000243 // Add an entry, F -> undef.
Chris Lattner229907c2011-07-18 04:54:35 +0000244 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000245 MRVFunctionsTracked.insert(F);
Devang Patela7a20752008-03-11 05:46:42 +0000246 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000247 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
248 LatticeVal()));
249 } else
250 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Chris Lattnerb4394642004-12-10 08:02:06 +0000251 }
252
Chris Lattnercde8de52009-11-03 19:24:51 +0000253 void AddArgumentTrackedFunction(Function *F) {
254 TrackingIncomingArguments.insert(F);
255 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000256
Chris Lattner074be1f2004-11-15 04:44:20 +0000257 /// Solve - Solve for constants and executable blocks.
258 ///
259 void Solve();
Chris Lattner347389d2001-06-27 23:38:11 +0000260
Chris Lattner1847f6d2006-12-20 06:21:33 +0000261 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +0000262 /// that branches on undef values cannot reach any of their successors.
263 /// However, this is not a safe assumption. After we solve dataflow, this
264 /// method should be use to handle this. If this returns true, the solver
265 /// should be rerun.
Chris Lattner1847f6d2006-12-20 06:21:33 +0000266 bool ResolvedUndefsIn(Function &F);
Chris Lattner7285f432004-12-10 20:41:50 +0000267
Chris Lattneradd44f32008-08-23 23:39:31 +0000268 bool isBlockExecutable(BasicBlock *BB) const {
269 return BBExecutable.count(BB);
Chris Lattner074be1f2004-11-15 04:44:20 +0000270 }
271
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000272 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattnerf5484032009-11-02 05:55:40 +0000273 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerb5a13d42009-11-02 02:54:24 +0000274 assert(I != ValueState.end() && "V is not in valuemap!");
275 return I->second;
Chris Lattner074be1f2004-11-15 04:44:20 +0000276 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000277
Devang Patela7a20752008-03-11 05:46:42 +0000278 /// getTrackedRetVals - Get the inferred return value map.
Chris Lattner99e12952004-12-11 02:53:57 +0000279 ///
Devang Patela7a20752008-03-11 05:46:42 +0000280 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
281 return TrackedRetVals;
Chris Lattner99e12952004-12-11 02:53:57 +0000282 }
283
Chris Lattner91dbae62004-12-11 05:15:59 +0000284 /// getTrackedGlobals - Get and return the set of inferred initializers for
285 /// global variables.
Chris Lattner067d6072007-02-02 20:38:30 +0000286 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
Chris Lattner91dbae62004-12-11 05:15:59 +0000287 return TrackedGlobals;
288 }
289
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000290 void markOverdefined(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000291 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerc33fd462007-03-04 04:50:21 +0000292 markOverdefined(ValueState[V], V);
293 }
Chris Lattner99e12952004-12-11 02:53:57 +0000294
Chris Lattner156b8c72009-11-03 23:40:48 +0000295 /// markAnythingOverdefined - Mark the specified value overdefined. This
296 /// works with both scalars and structs.
297 void markAnythingOverdefined(Value *V) {
Chris Lattner229907c2011-07-18 04:54:35 +0000298 if (StructType *STy = dyn_cast<StructType>(V->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000299 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
300 markOverdefined(getStructValueState(V, i), V);
301 else
302 markOverdefined(V);
303 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000304
Chris Lattner347389d2001-06-27 23:38:11 +0000305private:
Chris Lattnerd79334d2004-07-15 23:36:43 +0000306 // markConstant - Make a value be marked as "constant". If the value
Misha Brukmanb1c93172005-04-21 23:48:37 +0000307 // is not already a constant, add it to the instruction work list so that
Chris Lattner347389d2001-06-27 23:38:11 +0000308 // the users of the instruction are updated later.
309 //
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000310 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
311 if (!IV.markConstant(C)) return;
David Greene389fc3b2010-01-05 01:27:15 +0000312 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000313 if (IV.isOverdefined())
314 OverdefinedInstWorkList.push_back(V);
315 else
316 InstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000317 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000318
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000319 void markConstant(Value *V, Constant *C) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000320 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerb4394642004-12-10 08:02:06 +0000321 markConstant(ValueState[V], V, C);
Chris Lattner347389d2001-06-27 23:38:11 +0000322 }
323
Chris Lattnerf5484032009-11-02 05:55:40 +0000324 void markForcedConstant(Value *V, Constant *C) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000325 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000326 LatticeVal &IV = ValueState[V];
327 IV.markForcedConstant(C);
David Greene389fc3b2010-01-05 01:27:15 +0000328 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Chris Lattnerc6c153b2010-04-09 01:14:31 +0000329 if (IV.isOverdefined())
330 OverdefinedInstWorkList.push_back(V);
331 else
332 InstWorkList.push_back(V);
Chris Lattnerf5484032009-11-02 05:55:40 +0000333 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000334
335
Chris Lattnerd79334d2004-07-15 23:36:43 +0000336 // markOverdefined - Make a value be marked as "overdefined". If the
Misha Brukmanb1c93172005-04-21 23:48:37 +0000337 // value is not already overdefined, add it to the overdefined instruction
Chris Lattnerd79334d2004-07-15 23:36:43 +0000338 // work list so that the users of the instruction are updated later.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000339 void markOverdefined(LatticeVal &IV, Value *V) {
340 if (!IV.markOverdefined()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000341
David Greene389fc3b2010-01-05 01:27:15 +0000342 DEBUG(dbgs() << "markOverdefined: ";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000343 if (Function *F = dyn_cast<Function>(V))
David Greene389fc3b2010-01-05 01:27:15 +0000344 dbgs() << "Function '" << F->getName() << "'\n";
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000345 else
David Greene389fc3b2010-01-05 01:27:15 +0000346 dbgs() << *V << '\n');
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000347 // Only instructions go on the work list
348 OverdefinedInstWorkList.push_back(V);
Chris Lattner7324f7c2003-10-08 16:21:03 +0000349 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000350
Chris Lattnerf5484032009-11-02 05:55:40 +0000351 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Chris Lattnerb4394642004-12-10 08:02:06 +0000352 if (IV.isOverdefined() || MergeWithV.isUndefined())
353 return; // Noop.
354 if (MergeWithV.isOverdefined())
355 markOverdefined(IV, V);
356 else if (IV.isUndefined())
357 markConstant(IV, V, MergeWithV.getConstant());
358 else if (IV.getConstant() != MergeWithV.getConstant())
359 markOverdefined(IV, V);
Chris Lattner347389d2001-06-27 23:38:11 +0000360 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000361
Chris Lattnerf5484032009-11-02 05:55:40 +0000362 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000363 assert(!V->getType()->isStructTy() && "Should use other method");
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000364 mergeInValue(ValueState[V], V, MergeWithV);
Chris Lattner06a0ed12006-02-08 02:38:11 +0000365 }
366
Chris Lattner347389d2001-06-27 23:38:11 +0000367
Chris Lattnerf5484032009-11-02 05:55:40 +0000368 /// getValueState - Return the LatticeVal object that corresponds to the
369 /// value. This function handles the case when the value hasn't been seen yet
370 /// by properly seeding constants etc.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000371 LatticeVal &getValueState(Value *V) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000372 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
Chris Lattner646354b2004-10-16 18:09:41 +0000373
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000374 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
375 ValueState.insert(std::make_pair(V, LatticeVal()));
376 LatticeVal &LV = I.first->second;
377
378 if (!I.second)
379 return LV; // Common case, already in the map.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000380
Chris Lattner1847f6d2006-12-20 06:21:33 +0000381 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000382 // Undef values remain undefined.
383 if (!isa<UndefValue>(V))
Chris Lattner067d6072007-02-02 20:38:30 +0000384 LV.markConstant(C); // Constants are constant
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000385 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000386
Chris Lattnera3c39d32009-11-02 02:33:50 +0000387 // All others are underdefined by default.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000388 return LV;
Chris Lattner347389d2001-06-27 23:38:11 +0000389 }
390
Chris Lattner156b8c72009-11-03 23:40:48 +0000391 /// getStructValueState - Return the LatticeVal object that corresponds to the
392 /// value/field pair. This function handles the case when the value hasn't
393 /// been seen yet by properly seeding constants etc.
394 LatticeVal &getStructValueState(Value *V, unsigned i) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000395 assert(V->getType()->isStructTy() && "Should use getValueState");
Chris Lattner156b8c72009-11-03 23:40:48 +0000396 assert(i < cast<StructType>(V->getType())->getNumElements() &&
397 "Invalid element #");
Benjamin Kramer3fcbb822009-11-05 14:33:27 +0000398
399 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
400 bool> I = StructValueState.insert(
401 std::make_pair(std::make_pair(V, i), LatticeVal()));
402 LatticeVal &LV = I.first->second;
403
404 if (!I.second)
405 return LV; // Common case, already in the map.
406
Chris Lattner156b8c72009-11-03 23:40:48 +0000407 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerfa775002012-01-26 02:32:04 +0000408 Constant *Elt = C->getAggregateElement(i);
Nadav Rotem465834c2012-07-24 10:51:42 +0000409
Craig Topperf40110f2014-04-25 05:29:35 +0000410 if (!Elt)
Chris Lattner156b8c72009-11-03 23:40:48 +0000411 LV.markOverdefined(); // Unknown sort of constant.
Chris Lattnerfa775002012-01-26 02:32:04 +0000412 else if (isa<UndefValue>(Elt))
413 ; // Undef values remain undefined.
414 else
415 LV.markConstant(Elt); // Constants are constant.
Chris Lattner156b8c72009-11-03 23:40:48 +0000416 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000417
Chris Lattner156b8c72009-11-03 23:40:48 +0000418 // All others are underdefined by default.
419 return LV;
420 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000421
Chris Lattner156b8c72009-11-03 23:40:48 +0000422
Chris Lattnerf5484032009-11-02 05:55:40 +0000423 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
424 /// work list if it is not already executable.
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000425 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
426 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
427 return; // This edge is already known to be executable!
428
Chris Lattner809aee22009-11-02 06:11:23 +0000429 if (!MarkBlockExecutable(Dest)) {
430 // If the destination is already executable, we just made an *edge*
431 // feasible that wasn't before. Revisit the PHI nodes in the block
432 // because they have potentially new operands.
David Greene389fc3b2010-01-05 01:27:15 +0000433 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
Nick Lewycky5cd95382013-06-26 00:30:18 +0000434 << " -> " << Dest->getName() << '\n');
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000435
Chris Lattner809aee22009-11-02 06:11:23 +0000436 PHINode *PN;
437 for (BasicBlock::iterator I = Dest->begin();
438 (PN = dyn_cast<PHINode>(I)); ++I)
439 visitPHINode(*PN);
Chris Lattnercccc5c72003-04-25 02:50:03 +0000440 }
Chris Lattner347389d2001-06-27 23:38:11 +0000441 }
442
Chris Lattner074be1f2004-11-15 04:44:20 +0000443 // getFeasibleSuccessors - Return a vector of booleans to indicate which
444 // successors are reachable from a given terminator instruction.
445 //
Craig Topperb94011f2013-07-14 04:42:23 +0000446 void getFeasibleSuccessors(TerminatorInst &TI, SmallVectorImpl<bool> &Succs);
Chris Lattner074be1f2004-11-15 04:44:20 +0000447
448 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000449 // block to the 'To' basic block is currently feasible.
Chris Lattner074be1f2004-11-15 04:44:20 +0000450 //
451 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
452
453 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnera3c39d32009-11-02 02:33:50 +0000454 // instruction that was just changed state somehow. Based on this
Chris Lattner074be1f2004-11-15 04:44:20 +0000455 // information, we need to update the specified user of this instruction.
456 //
Chris Lattnerfb141812009-11-03 03:42:51 +0000457 void OperandChangedState(Instruction *I) {
458 if (BBExecutable.count(I->getParent())) // Inst is executable?
459 visit(*I);
Chris Lattner074be1f2004-11-15 04:44:20 +0000460 }
Dale Johannesend3a58c82010-11-30 20:23:21 +0000461
Chris Lattner074be1f2004-11-15 04:44:20 +0000462private:
463 friend class InstVisitor<SCCPSolver>;
Chris Lattner347389d2001-06-27 23:38:11 +0000464
Chris Lattnera3c39d32009-11-02 02:33:50 +0000465 // visit implementations - Something changed in this instruction. Either an
Chris Lattner10b250e2001-06-29 23:56:23 +0000466 // operand made a transition, or the instruction is newly executable. Change
467 // the value type of I to reflect these changes if appropriate.
Chris Lattner113f4f42002-06-25 16:13:24 +0000468 void visitPHINode(PHINode &I);
Chris Lattner6e560792002-04-18 15:13:15 +0000469
470 // Terminators
Chris Lattnerb4394642004-12-10 08:02:06 +0000471 void visitReturnInst(ReturnInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000472 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner6e560792002-04-18 15:13:15 +0000473
Chris Lattner6e1a1b12002-08-14 17:53:45 +0000474 void visitCastInst(CastInst &I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000475 void visitSelectInst(SelectInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000476 void visitBinaryOperator(Instruction &I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000477 void visitCmpInst(CmpInst &I);
Robert Bocchinobd518d12006-01-10 19:05:05 +0000478 void visitExtractElementInst(ExtractElementInst &I);
Robert Bocchino6dce2502006-01-17 20:06:55 +0000479 void visitInsertElementInst(InsertElementInst &I);
Chris Lattner17bd6052006-04-08 01:19:12 +0000480 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman041f9d02008-06-20 01:15:44 +0000481 void visitExtractValueInst(ExtractValueInst &EVI);
482 void visitInsertValueInst(InsertValueInst &IVI);
Bill Wendlingfae14752011-08-12 20:24:12 +0000483 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
David Majnemer8a1c45d2015-12-12 05:38:55 +0000484 void visitFuncletPadInst(FuncletPadInst &FPI) {
485 markAnythingOverdefined(&FPI);
486 }
487 void visitCatchSwitchInst(CatchSwitchInst &CPI) {
David Majnemereb518bd2015-08-04 08:21:40 +0000488 markAnythingOverdefined(&CPI);
489 visitTerminatorInst(CPI);
490 }
Chris Lattner6e560792002-04-18 15:13:15 +0000491
Chris Lattnera3c39d32009-11-02 02:33:50 +0000492 // Instructions that cannot be folded away.
Chris Lattnerf5484032009-11-02 05:55:40 +0000493 void visitStoreInst (StoreInst &I);
Chris Lattner49f74522004-01-12 04:29:41 +0000494 void visitLoadInst (LoadInst &I);
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000495 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandeze2971492009-10-24 04:23:03 +0000496 void visitCallInst (CallInst &I) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000497 visitCallSite(&I);
Victor Hernandez5d034492009-09-18 22:35:49 +0000498 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000499 void visitInvokeInst (InvokeInst &II) {
Gabor Greif62f0aac2010-07-28 22:50:26 +0000500 visitCallSite(&II);
Chris Lattnerb4394642004-12-10 08:02:06 +0000501 visitTerminatorInst(II);
Chris Lattnerdf741d62003-08-27 01:08:35 +0000502 }
Chris Lattnerb4394642004-12-10 08:02:06 +0000503 void visitCallSite (CallSite CS);
Davide Italianoa7f5e882016-05-04 23:27:13 +0000504 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
505 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
506 void visitFenceInst (FenceInst &I) { /*returns void*/ }
Tim Northover6bf04e42014-06-13 14:54:09 +0000507 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
508 markAnythingOverdefined(&I);
509 }
Eli Friedman366bcce2011-08-02 21:35:16 +0000510 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
Victor Hernandez8acf2952009-10-23 21:09:37 +0000511 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner156b8c72009-11-03 23:40:48 +0000512 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
Chris Lattner6e560792002-04-18 15:13:15 +0000513
Chris Lattner113f4f42002-06-25 16:13:24 +0000514 void visitInstruction(Instruction &I) {
Chris Lattnera3c39d32009-11-02 02:33:50 +0000515 // If a new instruction is added to LLVM that we don't handle.
Nick Lewycky5cd95382013-06-26 00:30:18 +0000516 dbgs() << "SCCP: Don't know how to handle: " << I << '\n';
Chris Lattner156b8c72009-11-03 23:40:48 +0000517 markAnythingOverdefined(&I); // Just in case
Chris Lattner6e560792002-04-18 15:13:15 +0000518 }
Chris Lattner10b250e2001-06-29 23:56:23 +0000519};
Chris Lattnerb28b6802002-07-23 18:06:35 +0000520
Duncan Sands2be91fc2007-07-20 08:56:21 +0000521} // end anonymous namespace
522
523
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000524// getFeasibleSuccessors - Return a vector of booleans to indicate which
525// successors are reachable from a given terminator instruction.
526//
Chris Lattner074be1f2004-11-15 04:44:20 +0000527void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
Craig Topperb94011f2013-07-14 04:42:23 +0000528 SmallVectorImpl<bool> &Succs) {
Chris Lattnercccc5c72003-04-25 02:50:03 +0000529 Succs.resize(TI.getNumSuccessors());
Chris Lattner113f4f42002-06-25 16:13:24 +0000530 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000531 if (BI->isUnconditional()) {
532 Succs[0] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000533 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000534 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000535
Chris Lattnerf5484032009-11-02 05:55:40 +0000536 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000537 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000538 if (!CI) {
Chris Lattner6df5cec2009-11-02 02:30:06 +0000539 // Overdefined condition variables, and branches on unfoldable constant
540 // conditions, mean the branch could go either way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000541 if (!BCValue.isUndefined())
542 Succs[0] = Succs[1] = true;
Chris Lattner6df5cec2009-11-02 02:30:06 +0000543 return;
544 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000545
Chris Lattner6df5cec2009-11-02 02:30:06 +0000546 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000547 Succs[CI->isZero()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000548 return;
549 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000550
David Majnemer654e1302015-07-31 17:58:14 +0000551 // Unwinding instructions successors are always executable.
552 if (TI.isExceptional()) {
553 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattneree8b9512009-10-29 01:21:20 +0000554 return;
555 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000556
Chris Lattneree8b9512009-10-29 01:21:20 +0000557 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000558 if (!SI->getNumCases()) {
Eli Friedman56f2f212011-08-16 21:12:35 +0000559 Succs[0] = true;
560 return;
561 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000562 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000563 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000564
Craig Topperf40110f2014-04-25 05:29:35 +0000565 if (!CI) { // Overdefined or undefined condition?
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000566 // All destinations are executable!
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000567 if (!SCValue.isUndefined())
568 Succs.assign(TI.getNumSuccessors(), true);
569 return;
570 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000571
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000572 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
Chris Lattneree8b9512009-10-29 01:21:20 +0000573 return;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000574 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000575
Chris Lattneree8b9512009-10-29 01:21:20 +0000576 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
577 if (isa<IndirectBrInst>(&TI)) {
578 // Just mark all destinations executable!
579 Succs.assign(TI.getNumSuccessors(), true);
580 return;
581 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000582
Chris Lattneree8b9512009-10-29 01:21:20 +0000583#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000584 dbgs() << "Unknown terminator instruction: " << TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000585#endif
586 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000587}
588
589
Chris Lattner13b52e72002-05-02 21:18:01 +0000590// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnera3c39d32009-11-02 02:33:50 +0000591// block to the 'To' basic block is currently feasible.
Chris Lattner13b52e72002-05-02 21:18:01 +0000592//
Chris Lattner074be1f2004-11-15 04:44:20 +0000593bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
Chris Lattner13b52e72002-05-02 21:18:01 +0000594 assert(BBExecutable.count(To) && "Dest should always be alive!");
595
596 // Make sure the source basic block is executable!!
597 if (!BBExecutable.count(From)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000598
Chris Lattnera3c39d32009-11-02 02:33:50 +0000599 // Check to make sure this edge itself is actually feasible now.
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000600 TerminatorInst *TI = From->getTerminator();
601 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
602 if (BI->isUnconditional())
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000603 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000604
Chris Lattnerf5484032009-11-02 05:55:40 +0000605 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattnerfe992d42004-01-12 17:40:36 +0000606
Chris Lattner6df5cec2009-11-02 02:30:06 +0000607 // Overdefined condition variables mean the branch could go either way,
608 // undef conditions mean that neither edge is feasible yet.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000609 ConstantInt *CI = BCValue.getConstantInt();
Craig Topperf40110f2014-04-25 05:29:35 +0000610 if (!CI)
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000611 return !BCValue.isUndefined();
Jakub Staszak632a3552012-01-18 21:16:33 +0000612
Chris Lattner6df5cec2009-11-02 02:30:06 +0000613 // Constant condition variables mean the branch can only go a single way.
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000614 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattneree8b9512009-10-29 01:21:20 +0000615 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000616
David Majnemer654e1302015-07-31 17:58:14 +0000617 // Unwinding instructions successors are always executable.
618 if (TI->isExceptional())
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000619 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000620
Chris Lattneree8b9512009-10-29 01:21:20 +0000621 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000622 if (SI->getNumCases() < 1)
Eli Friedman56f2f212011-08-16 21:12:35 +0000623 return true;
624
Chris Lattnerf5484032009-11-02 05:55:40 +0000625 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000626 ConstantInt *CI = SCValue.getConstantInt();
Jakub Staszak632a3552012-01-18 21:16:33 +0000627
Craig Topperf40110f2014-04-25 05:29:35 +0000628 if (!CI)
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000629 return !SCValue.isUndefined();
Chris Lattnerfe992d42004-01-12 17:40:36 +0000630
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000631 return SI->findCaseValue(CI).getCaseSuccessor() == To;
Chris Lattner71ac22ff2003-10-08 15:47:41 +0000632 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000633
Chris Lattneree8b9512009-10-29 01:21:20 +0000634 // Just mark all destinations executable!
635 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
Eli Friedman3de2ddc2011-05-21 19:13:10 +0000636 if (isa<IndirectBrInst>(TI))
Chris Lattneree8b9512009-10-29 01:21:20 +0000637 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +0000638
Chris Lattneree8b9512009-10-29 01:21:20 +0000639#ifndef NDEBUG
David Greene389fc3b2010-01-05 01:27:15 +0000640 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
Chris Lattneree8b9512009-10-29 01:21:20 +0000641#endif
Davide Italianodd04fee2015-11-25 21:03:36 +0000642 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Chris Lattner13b52e72002-05-02 21:18:01 +0000643}
Chris Lattner347389d2001-06-27 23:38:11 +0000644
Chris Lattnera3c39d32009-11-02 02:33:50 +0000645// visit Implementations - Something changed in this instruction, either an
Chris Lattner347389d2001-06-27 23:38:11 +0000646// operand made a transition, or the instruction is newly executable. Change
647// the value type of I to reflect these changes if appropriate. This method
648// makes sure to do the following actions:
649//
650// 1. If a phi node merges two constants in, and has conflicting value coming
651// from different branches, or if the PHI node merges in an overdefined
652// value, then the PHI node becomes overdefined.
653// 2. If a phi node merges only constants in, and they all agree on value, the
654// PHI node becomes a constant value equal to that.
655// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
656// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
657// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
658// 6. If a conditional branch has a value that is constant, make the selected
659// destination executable
660// 7. If a conditional branch has a value that is overdefined, make all
661// successors executable.
662//
Chris Lattner074be1f2004-11-15 04:44:20 +0000663void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000664 // If this PN returns a struct, just mark the result overdefined.
665 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000666 if (PN.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000667 return markAnythingOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000668
Eli Friedman0a309292011-11-11 01:16:15 +0000669 if (getValueState(&PN).isOverdefined())
Chris Lattner05fe6842004-01-12 03:57:30 +0000670 return; // Quick exit
Chris Lattner347389d2001-06-27 23:38:11 +0000671
Chris Lattner7a7b1142004-03-16 19:49:59 +0000672 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
673 // and slow us down a lot. Just mark them overdefined.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000674 if (PN.getNumIncomingValues() > 64)
Chris Lattnerf5484032009-11-02 05:55:40 +0000675 return markOverdefined(&PN);
Jakub Staszak632a3552012-01-18 21:16:33 +0000676
Chris Lattner6e560792002-04-18 15:13:15 +0000677 // Look at all of the executable operands of the PHI node. If any of them
678 // are overdefined, the PHI becomes overdefined as well. If they are all
679 // constant, and they agree with each other, the PHI becomes the identical
680 // constant. If they are constant and don't agree, the PHI is overdefined.
681 // If there are no executable operands, the PHI remains undefined.
682 //
Craig Topperf40110f2014-04-25 05:29:35 +0000683 Constant *OperandVal = nullptr;
Chris Lattnercccc5c72003-04-25 02:50:03 +0000684 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000685 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Chris Lattnercccc5c72003-04-25 02:50:03 +0000686 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000687
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000688 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
689 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +0000690
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000691 if (IV.isOverdefined()) // PHI node becomes overdefined!
692 return markOverdefined(&PN);
Chris Lattner7e270582003-06-24 20:29:52 +0000693
Craig Topperf40110f2014-04-25 05:29:35 +0000694 if (!OperandVal) { // Grab the first value.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000695 OperandVal = IV.getConstant();
696 continue;
Chris Lattner347389d2001-06-27 23:38:11 +0000697 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000698
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000699 // There is already a reachable operand. If we conflict with it,
700 // then the PHI node becomes overdefined. If we agree with it, we
701 // can continue on.
Jakub Staszak632a3552012-01-18 21:16:33 +0000702
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000703 // Check to see if there are two different constants merging, if so, the PHI
704 // node is overdefined.
705 if (IV.getConstant() != OperandVal)
706 return markOverdefined(&PN);
Chris Lattner347389d2001-06-27 23:38:11 +0000707 }
708
Chris Lattner6e560792002-04-18 15:13:15 +0000709 // If we exited the loop, this means that the PHI node only has constant
Chris Lattnercccc5c72003-04-25 02:50:03 +0000710 // arguments that agree with each other(and OperandVal is the constant) or
711 // OperandVal is null because there are no defined incoming arguments. If
712 // this is the case, the PHI remains undefined.
Chris Lattner347389d2001-06-27 23:38:11 +0000713 //
Chris Lattnercccc5c72003-04-25 02:50:03 +0000714 if (OperandVal)
Chris Lattner65938fc2008-08-23 23:36:38 +0000715 markConstant(&PN, OperandVal); // Acquire operand value
Chris Lattner347389d2001-06-27 23:38:11 +0000716}
717
Chris Lattnerb4394642004-12-10 08:02:06 +0000718void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000719 if (I.getNumOperands() == 0) return; // ret void
Chris Lattnerb4394642004-12-10 08:02:06 +0000720
Chris Lattnerb4394642004-12-10 08:02:06 +0000721 Function *F = I.getParent()->getParent();
Chris Lattner156b8c72009-11-03 23:40:48 +0000722 Value *ResultOp = I.getOperand(0);
Jakub Staszak632a3552012-01-18 21:16:33 +0000723
Devang Patela7a20752008-03-11 05:46:42 +0000724 // If we are tracking the return value of this function, merge it in.
Duncan Sands19d0b472010-02-16 11:11:14 +0000725 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
Chris Lattner067d6072007-02-02 20:38:30 +0000726 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Patela7a20752008-03-11 05:46:42 +0000727 TrackedRetVals.find(F);
Chris Lattnerfb141812009-11-03 03:42:51 +0000728 if (TFRVI != TrackedRetVals.end()) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000729 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
Devang Patela7a20752008-03-11 05:46:42 +0000730 return;
731 }
732 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000733
Chris Lattner5a58a4d2008-04-23 05:38:20 +0000734 // Handle functions that return multiple values.
Chris Lattner156b8c72009-11-03 23:40:48 +0000735 if (!TrackedMultipleRetVals.empty()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000736 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
Chris Lattner156b8c72009-11-03 23:40:48 +0000737 if (MRVFunctionsTracked.count(F))
738 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
739 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
740 getStructValueState(ResultOp, i));
Jakub Staszak632a3552012-01-18 21:16:33 +0000741
Chris Lattnerb4394642004-12-10 08:02:06 +0000742 }
743}
744
Chris Lattner074be1f2004-11-15 04:44:20 +0000745void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner37d400a2007-02-02 21:15:06 +0000746 SmallVector<bool, 16> SuccFeasible;
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000747 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner347389d2001-06-27 23:38:11 +0000748
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000749 BasicBlock *BB = TI.getParent();
750
Chris Lattnera3c39d32009-11-02 02:33:50 +0000751 // Mark all feasible successors executable.
Chris Lattnerfe6c9ee2002-05-02 21:44:00 +0000752 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner0bbbe5d2003-10-08 16:55:34 +0000753 if (SuccFeasible[i])
754 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner6e560792002-04-18 15:13:15 +0000755}
756
Chris Lattner074be1f2004-11-15 04:44:20 +0000757void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000758 LatticeVal OpSt = getValueState(I.getOperand(0));
759 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner113f4f42002-06-25 16:13:24 +0000760 markOverdefined(&I);
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000761 else if (OpSt.isConstant()) {
762 Constant *C =
763 ConstantExpr::getCast(I.getOpcode(), OpSt.getConstant(), I.getType());
764 if (isa<UndefValue>(C))
765 return;
766 // Propagate constant value
767 markConstant(&I, C);
768 }
Chris Lattner6e560792002-04-18 15:13:15 +0000769}
770
Chris Lattner156b8c72009-11-03 23:40:48 +0000771
Dan Gohman041f9d02008-06-20 01:15:44 +0000772void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000773 // If this returns a struct, mark all elements over defined, we don't track
774 // structs in structs.
Duncan Sands19d0b472010-02-16 11:11:14 +0000775 if (EVI.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000776 return markAnythingOverdefined(&EVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000777
Chris Lattner156b8c72009-11-03 23:40:48 +0000778 // If this is extracting from more than one level of struct, we don't know.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000779 if (EVI.getNumIndices() != 1)
780 return markOverdefined(&EVI);
Dan Gohman041f9d02008-06-20 01:15:44 +0000781
Chris Lattner156b8c72009-11-03 23:40:48 +0000782 Value *AggVal = EVI.getAggregateOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000783 if (AggVal->getType()->isStructTy()) {
Chris Lattner02e2cee2009-11-10 22:02:09 +0000784 unsigned i = *EVI.idx_begin();
785 LatticeVal EltVal = getStructValueState(AggVal, i);
786 mergeInValue(getValueState(&EVI), &EVI, EltVal);
787 } else {
788 // Otherwise, must be extracting from an array.
789 return markOverdefined(&EVI);
790 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000791}
792
793void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Chris Lattner229907c2011-07-18 04:54:35 +0000794 StructType *STy = dyn_cast<StructType>(IVI.getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000795 if (!STy)
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000796 return markOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000797
Chris Lattner156b8c72009-11-03 23:40:48 +0000798 // If this has more than one index, we can't handle it, drive all results to
799 // undef.
800 if (IVI.getNumIndices() != 1)
801 return markAnythingOverdefined(&IVI);
Jakub Staszak632a3552012-01-18 21:16:33 +0000802
Chris Lattner156b8c72009-11-03 23:40:48 +0000803 Value *Aggr = IVI.getAggregateOperand();
804 unsigned Idx = *IVI.idx_begin();
Jakub Staszak632a3552012-01-18 21:16:33 +0000805
Chris Lattner156b8c72009-11-03 23:40:48 +0000806 // Compute the result based on what we're inserting.
807 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
808 // This passes through all values that aren't the inserted element.
809 if (i != Idx) {
810 LatticeVal EltVal = getStructValueState(Aggr, i);
811 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
812 continue;
813 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000814
Chris Lattner156b8c72009-11-03 23:40:48 +0000815 Value *Val = IVI.getInsertedValueOperand();
Duncan Sands19d0b472010-02-16 11:11:14 +0000816 if (Val->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000817 // We don't track structs in structs.
818 markOverdefined(getStructValueState(&IVI, i), &IVI);
819 else {
820 LatticeVal InVal = getValueState(Val);
821 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
822 }
823 }
Dan Gohman041f9d02008-06-20 01:15:44 +0000824}
825
Chris Lattner074be1f2004-11-15 04:44:20 +0000826void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000827 // If this select returns a struct, just mark the result overdefined.
828 // TODO: We could do a lot better than this if code actually uses this.
Duncan Sands19d0b472010-02-16 11:11:14 +0000829 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +0000830 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +0000831
Chris Lattnerf5484032009-11-02 05:55:40 +0000832 LatticeVal CondValue = getValueState(I.getCondition());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000833 if (CondValue.isUndefined())
834 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000835
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000836 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000837 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
838 mergeInValue(&I, getValueState(OpVal));
Chris Lattner9e97fbe2009-11-02 03:21:36 +0000839 return;
Chris Lattner06a0ed12006-02-08 02:38:11 +0000840 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000841
Chris Lattner06a0ed12006-02-08 02:38:11 +0000842 // Otherwise, the condition is overdefined or a constant we can't evaluate.
843 // See if we can produce something better than overdefined based on the T/F
844 // value.
Chris Lattnerf5484032009-11-02 05:55:40 +0000845 LatticeVal TVal = getValueState(I.getTrueValue());
846 LatticeVal FVal = getValueState(I.getFalseValue());
Jakub Staszak632a3552012-01-18 21:16:33 +0000847
Chris Lattner06a0ed12006-02-08 02:38:11 +0000848 // select ?, C, C -> C.
Jakub Staszak632a3552012-01-18 21:16:33 +0000849 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000850 TVal.getConstant() == FVal.getConstant())
851 return markConstant(&I, FVal.getConstant());
Chris Lattner06a0ed12006-02-08 02:38:11 +0000852
Chris Lattnerf5484032009-11-02 05:55:40 +0000853 if (TVal.isUndefined()) // select ?, undef, X -> X.
854 return mergeInValue(&I, FVal);
855 if (FVal.isUndefined()) // select ?, X, undef -> X.
856 return mergeInValue(&I, TVal);
857 markOverdefined(&I);
Chris Lattner59db22d2004-03-12 05:52:44 +0000858}
859
Chris Lattnerf5484032009-11-02 05:55:40 +0000860// Handle Binary Operators.
Chris Lattner074be1f2004-11-15 04:44:20 +0000861void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000862 LatticeVal V1State = getValueState(I.getOperand(0));
863 LatticeVal V2State = getValueState(I.getOperand(1));
Jakub Staszak632a3552012-01-18 21:16:33 +0000864
Chris Lattner4f031622004-11-15 05:03:30 +0000865 LatticeVal &IV = ValueState[&I];
Chris Lattner05fe6842004-01-12 03:57:30 +0000866 if (IV.isOverdefined()) return;
867
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000868 if (V1State.isConstant() && V2State.isConstant()) {
869 Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
870 V2State.getConstant());
871 // X op Y -> undef.
872 if (isa<UndefValue>(C))
873 return;
874 return markConstant(IV, &I, C);
875 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000876
Chris Lattnerf5484032009-11-02 05:55:40 +0000877 // If something is undef, wait for it to resolve.
878 if (!V1State.isOverdefined() && !V2State.isOverdefined())
879 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000880
Chris Lattnerf5484032009-11-02 05:55:40 +0000881 // Otherwise, one of our operands is overdefined. Try to produce something
882 // better than overdefined with some tricks.
Jakub Staszak632a3552012-01-18 21:16:33 +0000883
Chris Lattnerf5484032009-11-02 05:55:40 +0000884 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
885 // operand is overdefined.
886 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
Craig Topperf40110f2014-04-25 05:29:35 +0000887 LatticeVal *NonOverdefVal = nullptr;
Chris Lattnerf5484032009-11-02 05:55:40 +0000888 if (!V1State.isOverdefined())
889 NonOverdefVal = &V1State;
890 else if (!V2State.isOverdefined())
891 NonOverdefVal = &V2State;
Chris Lattner05fe6842004-01-12 03:57:30 +0000892
Chris Lattnerf5484032009-11-02 05:55:40 +0000893 if (NonOverdefVal) {
894 if (NonOverdefVal->isUndefined()) {
895 // Could annihilate value.
896 if (I.getOpcode() == Instruction::And)
897 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Chris Lattner229907c2011-07-18 04:54:35 +0000898 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
Chris Lattnerf5484032009-11-02 05:55:40 +0000899 markConstant(IV, &I, Constant::getAllOnesValue(PT));
900 else
901 markConstant(IV, &I,
902 Constant::getAllOnesValue(I.getType()));
903 return;
Chris Lattnercbc01612004-12-11 23:15:19 +0000904 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000905
Chris Lattnerf5484032009-11-02 05:55:40 +0000906 if (I.getOpcode() == Instruction::And) {
907 // X and 0 = 0
908 if (NonOverdefVal->getConstant()->isNullValue())
909 return markConstant(IV, &I, NonOverdefVal->getConstant());
910 } else {
911 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
912 if (CI->isAllOnesValue()) // X or -1 = -1
913 return markConstant(IV, &I, NonOverdefVal->getConstant());
Chris Lattnercbc01612004-12-11 23:15:19 +0000914 }
915 }
Chris Lattnerf5484032009-11-02 05:55:40 +0000916 }
Chris Lattnercbc01612004-12-11 23:15:19 +0000917
918
Chris Lattnerf5484032009-11-02 05:55:40 +0000919 markOverdefined(&I);
Chris Lattner6e560792002-04-18 15:13:15 +0000920}
Chris Lattnerdd6522e2002-08-30 23:39:00 +0000921
Chris Lattnera3c39d32009-11-02 02:33:50 +0000922// Handle ICmpInst instruction.
Reid Spencer266e42b2006-12-23 06:05:41 +0000923void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattnerf5484032009-11-02 05:55:40 +0000924 LatticeVal V1State = getValueState(I.getOperand(0));
925 LatticeVal V2State = getValueState(I.getOperand(1));
926
Reid Spencer266e42b2006-12-23 06:05:41 +0000927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
929
David Majnemerf1a9c9e2016-01-07 21:36:16 +0000930 if (V1State.isConstant() && V2State.isConstant()) {
931 Constant *C = ConstantExpr::getCompare(
932 I.getPredicate(), V1State.getConstant(), V2State.getConstant());
933 if (isa<UndefValue>(C))
934 return;
935 return markConstant(IV, &I, C);
936 }
Jakub Staszak632a3552012-01-18 21:16:33 +0000937
Chris Lattnerf5484032009-11-02 05:55:40 +0000938 // If operands are still undefined, wait for it to resolve.
939 if (!V1State.isOverdefined() && !V2State.isOverdefined())
940 return;
Jakub Staszak632a3552012-01-18 21:16:33 +0000941
Chris Lattnerf5484032009-11-02 05:55:40 +0000942 markOverdefined(&I);
Reid Spencer266e42b2006-12-23 06:05:41 +0000943}
944
Robert Bocchinobd518d12006-01-10 19:05:05 +0000945void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000946 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000947 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000948
949#if 0
Robert Bocchinobd518d12006-01-10 19:05:05 +0000950 LatticeVal &ValState = getValueState(I.getOperand(0));
951 LatticeVal &IdxState = getValueState(I.getOperand(1));
952
953 if (ValState.isOverdefined() || IdxState.isOverdefined())
954 markOverdefined(&I);
955 else if(ValState.isConstant() && IdxState.isConstant())
956 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
957 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000958#endif
Robert Bocchinobd518d12006-01-10 19:05:05 +0000959}
960
Robert Bocchino6dce2502006-01-17 20:06:55 +0000961void SCCPSolver::visitInsertElementInst(InsertElementInst &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
Robert Bocchino6dce2502006-01-17 20:06:55 +0000965 LatticeVal &ValState = getValueState(I.getOperand(0));
966 LatticeVal &EltState = getValueState(I.getOperand(1));
967 LatticeVal &IdxState = getValueState(I.getOperand(2));
968
969 if (ValState.isOverdefined() || EltState.isOverdefined() ||
970 IdxState.isOverdefined())
971 markOverdefined(&I);
972 else if(ValState.isConstant() && EltState.isConstant() &&
973 IdxState.isConstant())
974 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
975 EltState.getConstant(),
976 IdxState.getConstant()));
977 else if (ValState.isUndefined() && EltState.isConstant() &&
Jakub Staszak632a3552012-01-18 21:16:33 +0000978 IdxState.isConstant())
Chris Lattner28d921d2007-04-14 23:32:02 +0000979 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
980 EltState.getConstant(),
981 IdxState.getConstant()));
Devang Patel21efc732006-12-04 23:54:59 +0000982#endif
Robert Bocchino6dce2502006-01-17 20:06:55 +0000983}
984
Chris Lattner17bd6052006-04-08 01:19:12 +0000985void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +0000986 // TODO : SCCP does not handle vectors properly.
Chris Lattner7ccf1a62009-11-02 03:03:42 +0000987 return markOverdefined(&I);
Devang Patel21efc732006-12-04 23:54:59 +0000988#if 0
Chris Lattner17bd6052006-04-08 01:19:12 +0000989 LatticeVal &V1State = getValueState(I.getOperand(0));
990 LatticeVal &V2State = getValueState(I.getOperand(1));
991 LatticeVal &MaskState = getValueState(I.getOperand(2));
992
993 if (MaskState.isUndefined() ||
994 (V1State.isUndefined() && V2State.isUndefined()))
995 return; // Undefined output if mask or both inputs undefined.
Jakub Staszak632a3552012-01-18 21:16:33 +0000996
Chris Lattner17bd6052006-04-08 01:19:12 +0000997 if (V1State.isOverdefined() || V2State.isOverdefined() ||
998 MaskState.isOverdefined()) {
999 markOverdefined(&I);
1000 } else {
1001 // A mix of constant/undef inputs.
Jakub Staszak632a3552012-01-18 21:16:33 +00001002 Constant *V1 = V1State.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +00001003 V1State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak632a3552012-01-18 21:16:33 +00001004 Constant *V2 = V2State.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +00001005 V2State.getConstant() : UndefValue::get(I.getType());
Jakub Staszak632a3552012-01-18 21:16:33 +00001006 Constant *Mask = MaskState.isConstant() ?
Chris Lattner17bd6052006-04-08 01:19:12 +00001007 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1008 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1009 }
Devang Patel21efc732006-12-04 23:54:59 +00001010#endif
Chris Lattner17bd6052006-04-08 01:19:12 +00001011}
1012
Chris Lattnera3c39d32009-11-02 02:33:50 +00001013// Handle getelementptr instructions. If all operands are constants then we
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001014// can turn this into a getelementptr ConstantExpr.
1015//
Chris Lattner074be1f2004-11-15 04:44:20 +00001016void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001017 if (ValueState[&I].isOverdefined()) return;
Chris Lattner49f74522004-01-12 04:29:41 +00001018
Chris Lattner0e7ec672007-02-02 20:51:48 +00001019 SmallVector<Constant*, 8> Operands;
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001020 Operands.reserve(I.getNumOperands());
1021
1022 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001023 LatticeVal State = getValueState(I.getOperand(i));
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001024 if (State.isUndefined())
Chris Lattnera3c39d32009-11-02 02:33:50 +00001025 return; // Operands are not resolved yet.
Jakub Staszak632a3552012-01-18 21:16:33 +00001026
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001027 if (State.isOverdefined())
Chris Lattnerb70ef3c2009-11-02 23:25:39 +00001028 return markOverdefined(&I);
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001029
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001030 assert(State.isConstant() && "Unknown state!");
1031 Operands.push_back(State.getConstant());
1032 }
1033
1034 Constant *Ptr = Operands[0];
Craig Toppere1d12942014-08-27 05:25:25 +00001035 auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001036 Constant *C =
1037 ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1038 if (isa<UndefValue>(C))
1039 return;
1040 markConstant(&I, C);
Chris Lattnerdd6522e2002-08-30 23:39:00 +00001041}
Brian Gaeke960707c2003-11-11 22:41:34 +00001042
Chris Lattnerf5484032009-11-02 05:55:40 +00001043void SCCPSolver::visitStoreInst(StoreInst &SI) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001044 // If this store is of a struct, ignore it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001045 if (SI.getOperand(0)->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001046 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001047
Chris Lattner91dbae62004-12-11 05:15:59 +00001048 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1049 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001050
Chris Lattner91dbae62004-12-11 05:15:59 +00001051 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
Chris Lattner067d6072007-02-02 20:38:30 +00001052 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
Chris Lattner91dbae62004-12-11 05:15:59 +00001053 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1054
Chris Lattnerf5484032009-11-02 05:55:40 +00001055 // Get the value we are storing into the global, then merge it.
1056 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Chris Lattner91dbae62004-12-11 05:15:59 +00001057 if (I->second.isOverdefined())
1058 TrackedGlobals.erase(I); // No need to keep tracking this!
1059}
1060
1061
Chris Lattner49f74522004-01-12 04:29:41 +00001062// Handle load instructions. If the operand is a constant pointer to a constant
1063// global, we can replace the load with the loaded constant value!
Chris Lattner074be1f2004-11-15 04:44:20 +00001064void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001065 // If this load is of a struct, just mark the result overdefined.
David Majnemerf3b99dd2016-01-07 19:30:13 +00001066 if (I.getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001067 return markAnythingOverdefined(&I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001068
Chris Lattnerf5484032009-11-02 05:55:40 +00001069 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001070 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Jakub Staszak632a3552012-01-18 21:16:33 +00001071
Chris Lattner4f031622004-11-15 05:03:30 +00001072 LatticeVal &IV = ValueState[&I];
Chris Lattner49f74522004-01-12 04:29:41 +00001073 if (IV.isOverdefined()) return;
1074
Chris Lattnerf5484032009-11-02 05:55:40 +00001075 if (!PtrVal.isConstant() || I.isVolatile())
1076 return markOverdefined(IV, &I);
Jakub Staszak632a3552012-01-18 21:16:33 +00001077
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001078 Constant *Ptr = PtrVal.getConstant();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001079
David Majnemerbae94572016-01-07 19:25:39 +00001080 // load null is undefined.
Chris Lattnerf5484032009-11-02 05:55:40 +00001081 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
David Majnemerbae94572016-01-07 19:25:39 +00001082 return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001083
Chris Lattnerf5484032009-11-02 05:55:40 +00001084 // Transform load (constant global) into the value loaded.
1085 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001086 if (!TrackedGlobals.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001087 // If we are tracking this global, merge in the known value for it.
1088 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1089 TrackedGlobals.find(GV);
1090 if (It != TrackedGlobals.end()) {
1091 mergeInValue(IV, &I, It->second);
1092 return;
Chris Lattner49f74522004-01-12 04:29:41 +00001093 }
Chris Lattner91dbae62004-12-11 05:15:59 +00001094 }
Chris Lattner49f74522004-01-12 04:29:41 +00001095 }
1096
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001097 // Transform load from a constant into a constant if possible.
Eduard Burtescu14239212016-01-22 01:17:26 +00001098 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001099 if (isa<UndefValue>(C))
1100 return;
Chris Lattnere77c9aa2009-11-02 06:06:14 +00001101 return markConstant(IV, &I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001102 }
Chris Lattnerf5484032009-11-02 05:55:40 +00001103
Chris Lattner49f74522004-01-12 04:29:41 +00001104 // Otherwise we cannot say for certain what value this load will produce.
1105 // Bail out.
1106 markOverdefined(IV, &I);
1107}
Chris Lattnerff9362a2004-04-13 19:43:54 +00001108
Chris Lattnerb4394642004-12-10 08:02:06 +00001109void SCCPSolver::visitCallSite(CallSite CS) {
1110 Function *F = CS.getCalledFunction();
Chris Lattnerb4394642004-12-10 08:02:06 +00001111 Instruction *I = CS.getInstruction();
Jakub Staszak632a3552012-01-18 21:16:33 +00001112
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001113 // The common case is that we aren't tracking the callee, either because we
1114 // are not doing interprocedural analysis or the callee is indirect, or is
1115 // external. Handle these cases first.
Craig Topperf40110f2014-04-25 05:29:35 +00001116 if (!F || F->isDeclaration()) {
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001117CallOverdefined:
1118 // Void return and not tracking callee, just bail.
Chris Lattnerfdd87902009-10-05 05:54:46 +00001119 if (I->getType()->isVoidTy()) return;
Jakub Staszak632a3552012-01-18 21:16:33 +00001120
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001121 // Otherwise, if we have a single return value case, and if the function is
1122 // a declaration, maybe we can constant fold it.
Duncan Sands19d0b472010-02-16 11:11:14 +00001123 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001124 canConstantFoldCallTo(F)) {
Jakub Staszak632a3552012-01-18 21:16:33 +00001125
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001126 SmallVector<Constant*, 8> Operands;
1127 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1128 AI != E; ++AI) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001129 LatticeVal State = getValueState(*AI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001130
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001131 if (State.isUndefined())
1132 return; // Operands are not resolved yet.
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001133 if (State.isOverdefined())
1134 return markOverdefined(I);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001135 assert(State.isConstant() && "Unknown state!");
1136 Operands.push_back(State.getConstant());
1137 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001138
David Majnemer2098b86f2014-11-07 08:54:19 +00001139 if (getValueState(I).isOverdefined())
1140 return;
1141
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001142 // If we can constant fold this, mark the result of the call as a
1143 // constant.
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001144 if (Constant *C = ConstantFoldCall(F, Operands, TLI)) {
1145 // call -> undef.
1146 if (isa<UndefValue>(C))
1147 return;
Chris Lattner7ccf1a62009-11-02 03:03:42 +00001148 return markConstant(I, C);
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001149 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001150 }
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001151
1152 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattner156b8c72009-11-03 23:40:48 +00001153 return markAnythingOverdefined(I);
Chris Lattnerff9362a2004-04-13 19:43:54 +00001154 }
1155
Chris Lattnercde8de52009-11-03 19:24:51 +00001156 // If this is a local function that doesn't have its address taken, mark its
1157 // entry block executable and merge in the actual arguments to the call into
1158 // the formal arguments of the function.
1159 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001160 MarkBlockExecutable(&F->front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001161
Chris Lattnercde8de52009-11-03 19:24:51 +00001162 // Propagate information from this call site into the callee.
1163 CallSite::arg_iterator CAI = CS.arg_begin();
1164 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1165 AI != E; ++AI, ++CAI) {
1166 // If this argument is byval, and if the function is not readonly, there
1167 // will be an implicit copy formed of the input aggregate.
1168 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001169 markOverdefined(&*AI);
Chris Lattnercde8de52009-11-03 19:24:51 +00001170 continue;
1171 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001172
Chris Lattner229907c2011-07-18 04:54:35 +00001173 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
Chris Lattner762b56f2009-11-04 18:57:42 +00001174 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1175 LatticeVal CallArg = getStructValueState(*CAI, i);
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001176 mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
Chris Lattner762b56f2009-11-04 18:57:42 +00001177 }
Chris Lattner156b8c72009-11-03 23:40:48 +00001178 } else {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001179 mergeInValue(&*AI, getValueState(*CAI));
Chris Lattner156b8c72009-11-03 23:40:48 +00001180 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001181 }
1182 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001183
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001184 // If this is a single/zero retval case, see if we're tracking the function.
Chris Lattner229907c2011-07-18 04:54:35 +00001185 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
Chris Lattner156b8c72009-11-03 23:40:48 +00001186 if (!MRVFunctionsTracked.count(F))
1187 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001188
Chris Lattner156b8c72009-11-03 23:40:48 +00001189 // If we are tracking this callee, propagate the result of the function
1190 // into this call site.
1191 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Jakub Staszak632a3552012-01-18 21:16:33 +00001192 mergeInValue(getStructValueState(I, i), I,
Chris Lattner156b8c72009-11-03 23:40:48 +00001193 TrackedMultipleRetVals[std::make_pair(F, i)]);
1194 } else {
1195 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1196 if (TFRVI == TrackedRetVals.end())
1197 goto CallOverdefined; // Not tracking this callee.
Jakub Staszak632a3552012-01-18 21:16:33 +00001198
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001199 // If so, propagate the return value of the callee into this call result.
1200 mergeInValue(I, TFRVI->second);
Chris Lattner5a58a4d2008-04-23 05:38:20 +00001201 }
Chris Lattnerff9362a2004-04-13 19:43:54 +00001202}
Chris Lattner074be1f2004-11-15 04:44:20 +00001203
Chris Lattner074be1f2004-11-15 04:44:20 +00001204void SCCPSolver::Solve() {
1205 // Process the work lists until they are empty!
Misha Brukmanb1c93172005-04-21 23:48:37 +00001206 while (!BBWorkList.empty() || !InstWorkList.empty() ||
Jeff Cohen82639852005-04-23 21:38:35 +00001207 !OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001208 // Process the overdefined instruction's work list first, which drives other
1209 // things to overdefined more quickly.
Chris Lattner074be1f2004-11-15 04:44:20 +00001210 while (!OverdefinedInstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001211 Value *I = OverdefinedInstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001212
David Greene389fc3b2010-01-05 01:27:15 +00001213 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001214
Chris Lattner074be1f2004-11-15 04:44:20 +00001215 // "I" got into the work list because it either made the transition from
Chad Rosier4d87d452013-02-20 20:15:55 +00001216 // bottom to constant, or to overdefined.
Chris Lattner074be1f2004-11-15 04:44:20 +00001217 //
1218 // Anything on this worklist that is overdefined need not be visited
1219 // since all of its users will have already been marked as overdefined
Chris Lattnera3c39d32009-11-02 02:33:50 +00001220 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001221 //
Chandler Carruthcdf47882014-03-09 03:16:01 +00001222 for (User *U : I->users())
1223 if (Instruction *UI = dyn_cast<Instruction>(U))
1224 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001225 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001226
Chris Lattnera3c39d32009-11-02 02:33:50 +00001227 // Process the instruction work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001228 while (!InstWorkList.empty()) {
Chris Lattnerf5484032009-11-02 05:55:40 +00001229 Value *I = InstWorkList.pop_back_val();
Chris Lattner074be1f2004-11-15 04:44:20 +00001230
David Greene389fc3b2010-01-05 01:27:15 +00001231 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001232
Chris Lattnerf5484032009-11-02 05:55:40 +00001233 // "I" got into the work list because it made the transition from undef to
1234 // constant.
Chris Lattner074be1f2004-11-15 04:44:20 +00001235 //
1236 // Anything on this worklist that is overdefined need not be visited
1237 // since all of its users will have already been marked as overdefined.
Chris Lattnera3c39d32009-11-02 02:33:50 +00001238 // Update all of the users of this instruction's value.
Chris Lattner074be1f2004-11-15 04:44:20 +00001239 //
Duncan Sands19d0b472010-02-16 11:11:14 +00001240 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001241 for (User *U : I->users())
1242 if (Instruction *UI = dyn_cast<Instruction>(U))
1243 OperandChangedState(UI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001244 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001245
Chris Lattnera3c39d32009-11-02 02:33:50 +00001246 // Process the basic block work list.
Chris Lattner074be1f2004-11-15 04:44:20 +00001247 while (!BBWorkList.empty()) {
1248 BasicBlock *BB = BBWorkList.back();
1249 BBWorkList.pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001250
David Greene389fc3b2010-01-05 01:27:15 +00001251 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
Misha Brukmanb1c93172005-04-21 23:48:37 +00001252
Chris Lattner074be1f2004-11-15 04:44:20 +00001253 // Notify all instructions in this basic block that they are newly
1254 // executable.
1255 visit(BB);
1256 }
1257 }
1258}
1259
Chris Lattner1847f6d2006-12-20 06:21:33 +00001260/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
Chris Lattner7285f432004-12-10 20:41:50 +00001261/// that branches on undef values cannot reach any of their successors.
1262/// However, this is not a safe assumption. After we solve dataflow, this
1263/// method should be use to handle this. If this returns true, the solver
1264/// should be rerun.
Chris Lattneraf170962006-10-22 05:59:17 +00001265///
1266/// This method handles this by finding an unresolved branch and marking it one
1267/// of the edges from the block as being feasible, even though the condition
1268/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1269/// CFG and only slightly pessimizes the analysis results (by marking one,
Chris Lattner1847f6d2006-12-20 06:21:33 +00001270/// potentially infeasible, edge feasible). This cannot usefully modify the
Chris Lattneraf170962006-10-22 05:59:17 +00001271/// constraints on the condition of the branch, as that would impact other users
1272/// of the value.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001273///
1274/// This scan also checks for values that use undefs, whose results are actually
1275/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1276/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1277/// even if X isn't defined.
1278bool SCCPSolver::ResolvedUndefsIn(Function &F) {
Chris Lattneraf170962006-10-22 05:59:17 +00001279 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001280 if (!BBExecutable.count(&*BB))
Chris Lattneraf170962006-10-22 05:59:17 +00001281 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001282
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001283 for (Instruction &I : *BB) {
Chris Lattner1847f6d2006-12-20 06:21:33 +00001284 // Look for instructions which produce undef values.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001285 if (I.getType()->isVoidTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001286
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001287 if (StructType *STy = dyn_cast<StructType>(I.getType())) {
Eli Friedman1815b682011-09-20 23:28:51 +00001288 // Only a few things that can be structs matter for undef.
1289
1290 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001291 if (CallSite CS = CallSite(&I))
Eli Friedman1815b682011-09-20 23:28:51 +00001292 if (Function *F = CS.getCalledFunction())
1293 if (MRVFunctionsTracked.count(F))
1294 continue;
1295
1296 // extractvalue and insertvalue don't need to be marked; they are
Jakub Staszak632a3552012-01-18 21:16:33 +00001297 // tracked as precisely as their operands.
Eli Friedman1815b682011-09-20 23:28:51 +00001298 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1299 continue;
1300
1301 // Send the results of everything else to overdefined. We could be
1302 // more precise than this but it isn't worth bothering.
1303 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001304 LatticeVal &LV = getStructValueState(&I, i);
Eli Friedman1815b682011-09-20 23:28:51 +00001305 if (LV.isUndefined())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001306 markOverdefined(LV, &I);
Chris Lattner156b8c72009-11-03 23:40:48 +00001307 }
1308 continue;
1309 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001310
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001311 LatticeVal &LV = getValueState(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001312 if (!LV.isUndefined()) continue;
1313
Eli Friedmand7749be2011-08-17 18:10:43 +00001314 // extractvalue is safe; check here because the argument is a struct.
1315 if (isa<ExtractValueInst>(I))
1316 continue;
1317
1318 // Compute the operand LatticeVals, for convenience below.
1319 // Anything taking a struct is conservatively assumed to require
1320 // overdefined markings.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001321 if (I.getOperand(0)->getType()->isStructTy()) {
1322 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001323 return true;
1324 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001325 LatticeVal Op0LV = getValueState(I.getOperand(0));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001326 LatticeVal Op1LV;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001327 if (I.getNumOperands() == 2) {
1328 if (I.getOperand(1)->getType()->isStructTy()) {
1329 markOverdefined(&I);
Eli Friedmand7749be2011-08-17 18:10:43 +00001330 return true;
1331 }
1332
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001333 Op1LV = getValueState(I.getOperand(1));
Eli Friedmand7749be2011-08-17 18:10:43 +00001334 }
Chris Lattner1847f6d2006-12-20 06:21:33 +00001335 // If this is an instructions whose result is defined even if the input is
1336 // not fully defined, propagate the information.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001337 Type *ITy = I.getType();
1338 switch (I.getOpcode()) {
Eli Friedman0793eb42011-08-16 22:06:31 +00001339 case Instruction::Add:
1340 case Instruction::Sub:
1341 case Instruction::Trunc:
1342 case Instruction::FPTrunc:
1343 case Instruction::BitCast:
1344 break; // Any undef -> undef
1345 case Instruction::FSub:
1346 case Instruction::FAdd:
1347 case Instruction::FMul:
1348 case Instruction::FDiv:
1349 case Instruction::FRem:
1350 // Floating-point binary operation: be conservative.
1351 if (Op0LV.isUndefined() && Op1LV.isUndefined())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001352 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001353 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001354 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001355 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001356 case Instruction::ZExt:
Eli Friedman0793eb42011-08-16 22:06:31 +00001357 case Instruction::SExt:
1358 case Instruction::FPToUI:
1359 case Instruction::FPToSI:
1360 case Instruction::FPExt:
1361 case Instruction::PtrToInt:
1362 case Instruction::IntToPtr:
1363 case Instruction::SIToFP:
1364 case Instruction::UIToFP:
1365 // undef -> 0; some outputs are impossible
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001366 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001367 return true;
1368 case Instruction::Mul:
1369 case Instruction::And:
Eli Friedman0793eb42011-08-16 22:06:31 +00001370 // Both operands undef -> undef
1371 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1372 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001373 // undef * X -> 0. X could be zero.
1374 // undef & X -> 0. X could be zero.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001375 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001376 return true;
1377
1378 case Instruction::Or:
Eli Friedman0793eb42011-08-16 22:06:31 +00001379 // Both operands undef -> undef
1380 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1381 break;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001382 // undef | X -> -1. X could be -1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001383 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner806adaf2007-01-04 02:12:40 +00001384 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001385
Eli Friedman0793eb42011-08-16 22:06:31 +00001386 case Instruction::Xor:
1387 // undef ^ undef -> 0; strictly speaking, this is not strictly
1388 // necessary, but we try to be nice to people who expect this
1389 // behavior in simple cases
1390 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001391 markForcedConstant(&I, Constant::getNullValue(ITy));
Eli Friedman0793eb42011-08-16 22:06:31 +00001392 return true;
1393 }
1394 // undef ^ X -> undef
1395 break;
1396
Chris Lattner1847f6d2006-12-20 06:21:33 +00001397 case Instruction::SDiv:
1398 case Instruction::UDiv:
1399 case Instruction::SRem:
1400 case Instruction::URem:
1401 // X / undef -> undef. No change.
1402 // X % undef -> undef. No change.
1403 if (Op1LV.isUndefined()) break;
Jakub Staszak632a3552012-01-18 21:16:33 +00001404
David Majnemerf1a9c9e2016-01-07 21:36:16 +00001405 // X / 0 -> undef. No change.
1406 // X % 0 -> undef. No change.
1407 if (Op1LV.isConstant() && Op1LV.getConstant()->isZeroValue())
1408 break;
1409
Chris Lattner1847f6d2006-12-20 06:21:33 +00001410 // undef / X -> 0. X could be maxint.
1411 // undef % X -> 0. X could be 1.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001412 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001413 return true;
Jakub Staszak632a3552012-01-18 21:16:33 +00001414
Chris Lattner1847f6d2006-12-20 06:21:33 +00001415 case Instruction::AShr:
Eli Friedman0793eb42011-08-16 22:06:31 +00001416 // X >>a undef -> undef.
1417 if (Op1LV.isUndefined()) break;
1418
David Majnemer96f0d382016-05-12 03:07:40 +00001419 // Shifting by the bitwidth or more is undefined.
1420 if (Op1LV.isConstant()) {
1421 auto *ShiftAmt = Op1LV.getConstantInt();
1422 if (ShiftAmt->getLimitedValue() >=
1423 ShiftAmt->getType()->getScalarSizeInBits())
1424 break;
1425 }
1426
Eli Friedman0793eb42011-08-16 22:06:31 +00001427 // undef >>a X -> all ones
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001428 markForcedConstant(&I, Constant::getAllOnesValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001429 return true;
1430 case Instruction::LShr:
1431 case Instruction::Shl:
Eli Friedman0793eb42011-08-16 22:06:31 +00001432 // X << undef -> undef.
1433 // X >> undef -> undef.
1434 if (Op1LV.isUndefined()) break;
1435
David Majnemer96f0d382016-05-12 03:07:40 +00001436 // Shifting by the bitwidth or more is undefined.
1437 if (Op1LV.isConstant()) {
1438 auto *ShiftAmt = Op1LV.getConstantInt();
1439 if (ShiftAmt->getLimitedValue() >=
1440 ShiftAmt->getType()->getScalarSizeInBits())
1441 break;
1442 }
1443
Eli Friedman0793eb42011-08-16 22:06:31 +00001444 // undef << X -> 0
1445 // undef >> X -> 0
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001446 markForcedConstant(&I, Constant::getNullValue(ITy));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001447 return true;
1448 case Instruction::Select:
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001449 Op1LV = getValueState(I.getOperand(1));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001450 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1451 if (Op0LV.isUndefined()) {
1452 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001453 Op1LV = getValueState(I.getOperand(2));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001454 } else if (Op1LV.isUndefined()) {
1455 // c ? undef : undef -> undef. No change.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001456 Op1LV = getValueState(I.getOperand(2));
Chris Lattner1847f6d2006-12-20 06:21:33 +00001457 if (Op1LV.isUndefined())
1458 break;
1459 // Otherwise, c ? undef : x -> x.
1460 } else {
1461 // Leave Op1LV as Operand(1)'s LatticeValue.
1462 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001463
Chris Lattner1847f6d2006-12-20 06:21:33 +00001464 if (Op1LV.isConstant())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001465 markForcedConstant(&I, Op1LV.getConstant());
Chris Lattner1847f6d2006-12-20 06:21:33 +00001466 else
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001467 markOverdefined(&I);
Chris Lattner1847f6d2006-12-20 06:21:33 +00001468 return true;
Eli Friedman0793eb42011-08-16 22:06:31 +00001469 case Instruction::Load:
1470 // A load here means one of two things: a load of undef from a global,
1471 // a load from an unknown pointer. Either way, having it return undef
1472 // is okay.
1473 break;
1474 case Instruction::ICmp:
1475 // X == undef -> undef. Other comparisons get more complicated.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001476 if (cast<ICmpInst>(&I)->isEquality())
Eli Friedman0793eb42011-08-16 22:06:31 +00001477 break;
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001478 markOverdefined(&I);
Eli Friedman0793eb42011-08-16 22:06:31 +00001479 return true;
Eli Friedman1815b682011-09-20 23:28:51 +00001480 case Instruction::Call:
1481 case Instruction::Invoke: {
1482 // There are two reasons a call can have an undef result
1483 // 1. It could be tracked.
1484 // 2. It could be constant-foldable.
1485 // Because of the way we solve return values, tracked calls must
1486 // never be marked overdefined in ResolvedUndefsIn.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001487 if (Function *F = CallSite(&I).getCalledFunction())
Eli Friedman1815b682011-09-20 23:28:51 +00001488 if (TrackedRetVals.count(F))
1489 break;
1490
1491 // If the call is constant-foldable, we mark it overdefined because
1492 // we do not know what return values are valid.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001493 markOverdefined(&I);
Eli Friedman1815b682011-09-20 23:28:51 +00001494 return true;
1495 }
Eli Friedman0793eb42011-08-16 22:06:31 +00001496 default:
1497 // If we don't know what should happen here, conservatively mark it
Chris Lattner5c207c82008-05-24 03:59:33 +00001498 // overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001499 markOverdefined(&I);
Chris Lattner5c207c82008-05-24 03:59:33 +00001500 return true;
Chris Lattner1847f6d2006-12-20 06:21:33 +00001501 }
1502 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001503
Chris Lattneradca6082010-04-05 22:14:48 +00001504 // Check to see if we have a branch or switch on an undefined value. If so
1505 // we force the branch to go one way or the other to make the successor
1506 // values live. It doesn't really matter which way we force it.
Chris Lattneraf170962006-10-22 05:59:17 +00001507 TerminatorInst *TI = BB->getTerminator();
1508 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1509 if (!BI->isConditional()) continue;
1510 if (!getValueState(BI->getCondition()).isUndefined())
1511 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001512
Chris Lattneradca6082010-04-05 22:14:48 +00001513 // If the input to SCCP is actually branch on undef, fix the undef to
1514 // false.
1515 if (isa<UndefValue>(BI->getCondition())) {
1516 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001517 markEdgeExecutable(&*BB, TI->getSuccessor(1));
Chris Lattneradca6082010-04-05 22:14:48 +00001518 return true;
1519 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001520
Chris Lattneradca6082010-04-05 22:14:48 +00001521 // Otherwise, it is a branch on a symbolic value which is currently
1522 // considered to be undef. Handle this by forcing the input value to the
1523 // branch to false.
1524 markForcedConstant(BI->getCondition(),
1525 ConstantInt::getFalse(TI->getContext()));
1526 return true;
1527 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001528
Chris Lattneradca6082010-04-05 22:14:48 +00001529 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00001530 if (!SI->getNumCases())
Dale Johannesenfecb8822008-05-23 01:01:31 +00001531 continue;
Chris Lattneraf170962006-10-22 05:59:17 +00001532 if (!getValueState(SI->getCondition()).isUndefined())
1533 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001534
Chris Lattneradca6082010-04-05 22:14:48 +00001535 // If the input to SCCP is actually switch on undef, fix the undef to
1536 // the first constant.
1537 if (isa<UndefValue>(SI->getCondition())) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001538 SI->setCondition(SI->case_begin().getCaseValue());
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001539 markEdgeExecutable(&*BB, SI->case_begin().getCaseSuccessor());
Chris Lattneradca6082010-04-05 22:14:48 +00001540 return true;
1541 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001542
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00001543 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
Chris Lattneradca6082010-04-05 22:14:48 +00001544 return true;
Chris Lattner7285f432004-12-10 20:41:50 +00001545 }
Chris Lattneraf170962006-10-22 05:59:17 +00001546 }
Chris Lattner2f687fd2004-12-11 06:05:53 +00001547
Chris Lattneraf170962006-10-22 05:59:17 +00001548 return false;
Chris Lattner7285f432004-12-10 20:41:50 +00001549}
1550
Chris Lattner074be1f2004-11-15 04:44:20 +00001551
1552namespace {
Chris Lattner1890f942004-11-15 07:15:04 +00001553 //===--------------------------------------------------------------------===//
Chris Lattner074be1f2004-11-15 04:44:20 +00001554 //
Chris Lattner1890f942004-11-15 07:15:04 +00001555 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
Reid Spencere8a74ee2006-12-31 22:26:06 +00001556 /// Sparse Conditional Constant Propagator.
Chris Lattner1890f942004-11-15 07:15:04 +00001557 ///
Chris Lattner2dd09db2009-09-02 06:11:42 +00001558 struct SCCP : public FunctionPass {
Craig Topper3e4c6972014-03-05 09:10:37 +00001559 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001560 AU.addRequired<TargetLibraryInfoWrapperPass>();
James Molloyefbba722015-09-10 10:22:12 +00001561 AU.addPreserved<GlobalsAAWrapperPass>();
Chad Rosiere6de63d2011-12-01 21:29:16 +00001562 }
Nick Lewyckye7da2d62007-05-06 13:37:16 +00001563 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +00001564 SCCP() : FunctionPass(ID) {
1565 initializeSCCPPass(*PassRegistry::getPassRegistry());
1566 }
Devang Patel09f162c2007-05-01 21:15:47 +00001567
Chris Lattner1890f942004-11-15 07:15:04 +00001568 // runOnFunction - Run the Sparse Conditional Constant Propagation
1569 // algorithm, and return true if the function was modified.
1570 //
Craig Topper3e4c6972014-03-05 09:10:37 +00001571 bool runOnFunction(Function &F) override;
Chris Lattner1890f942004-11-15 07:15:04 +00001572 };
Chris Lattner074be1f2004-11-15 04:44:20 +00001573} // end anonymous namespace
1574
Dan Gohmand78c4002008-05-13 00:00:25 +00001575char SCCP::ID = 0;
Owen Andersona57b97e2010-07-21 22:09:45 +00001576INITIALIZE_PASS(SCCP, "sccp",
Owen Andersondf7a4f22010-10-07 22:25:06 +00001577 "Sparse Conditional Constant Propagation", false, false)
Chris Lattner074be1f2004-11-15 04:44:20 +00001578
Chris Lattnera3c39d32009-11-02 02:33:50 +00001579// createSCCPPass - This is the public interface to this file.
Chris Lattner074be1f2004-11-15 04:44:20 +00001580FunctionPass *llvm::createSCCPPass() {
1581 return new SCCP();
1582}
1583
Chris Lattner074be1f2004-11-15 04:44:20 +00001584// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1585// and return true if the function was modified.
1586//
1587bool SCCP::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00001588 if (skipFunction(F))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001589 return false;
1590
David Greene389fc3b2010-01-05 01:27:15 +00001591 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
Mehdi Amini46a43552015-03-04 18:43:29 +00001592 const DataLayout &DL = F.getParent()->getDataLayout();
Chandler Carruthb98f63d2015-01-15 10:41:28 +00001593 const TargetLibraryInfo *TLI =
1594 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001595 SCCPSolver Solver(DL, TLI);
Chris Lattner074be1f2004-11-15 04:44:20 +00001596
1597 // Mark the first block of the function as being executable.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001598 Solver.MarkBlockExecutable(&F.front());
Chris Lattner074be1f2004-11-15 04:44:20 +00001599
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001600 // Mark all arguments to the function as being overdefined.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001601 for (Argument &AI : F.args())
1602 Solver.markAnythingOverdefined(&AI);
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001603
Chris Lattner074be1f2004-11-15 04:44:20 +00001604 // Solve for constants.
Chris Lattner1847f6d2006-12-20 06:21:33 +00001605 bool ResolvedUndefs = true;
1606 while (ResolvedUndefs) {
Chris Lattner7285f432004-12-10 20:41:50 +00001607 Solver.Solve();
David Greene389fc3b2010-01-05 01:27:15 +00001608 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
Chris Lattner1847f6d2006-12-20 06:21:33 +00001609 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
Chris Lattner7285f432004-12-10 20:41:50 +00001610 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001611
Chris Lattnerd18c16b2004-11-15 05:45:33 +00001612 bool MadeChanges = false;
1613
1614 // If we decided that there are basic blocks that are dead in this function,
1615 // delete their contents now. Note that we cannot actually delete the blocks,
1616 // as we cannot modify the CFG of the function.
Chris Lattnerc33fd462007-03-04 04:50:21 +00001617
Chris Lattnere405ed92009-11-02 02:47:51 +00001618 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001619 if (!Solver.isBlockExecutable(&*BB)) {
David Majnemer88542a02016-01-24 06:26:47 +00001620 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1621
1622 ++NumDeadBlocks;
David Majnemerdcd6c792016-01-24 06:40:37 +00001623 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&*BB);
David Majnemer88542a02016-01-24 06:26:47 +00001624
Chris Lattnere405ed92009-11-02 02:47:51 +00001625 MadeChanges = true;
1626 continue;
Chris Lattner074be1f2004-11-15 04:44:20 +00001627 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001628
Chris Lattnere405ed92009-11-02 02:47:51 +00001629 // Iterate over all of the instructions in a function, replacing them with
1630 // constants if we have found them to be of constant values.
1631 //
1632 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001633 Instruction *Inst = &*BI++;
Chris Lattnere405ed92009-11-02 02:47:51 +00001634 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1635 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001636
Chris Lattner156b8c72009-11-03 23:40:48 +00001637 // TODO: Reconstruct structs from their elements.
Duncan Sands19d0b472010-02-16 11:11:14 +00001638 if (Inst->getType()->isStructTy())
Chris Lattner156b8c72009-11-03 23:40:48 +00001639 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001640
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001641 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1642 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001643 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001644
Chris Lattnere405ed92009-11-02 02:47:51 +00001645 Constant *Const = IV.isConstant()
1646 ? IV.getConstant() : UndefValue::get(Inst->getType());
Nick Lewycky5cd95382013-06-26 00:30:18 +00001647 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Chris Lattnere405ed92009-11-02 02:47:51 +00001648
1649 // Replaces all of the uses of a variable with uses of the constant.
1650 Inst->replaceAllUsesWith(Const);
Jakub Staszak632a3552012-01-18 21:16:33 +00001651
Chris Lattnere405ed92009-11-02 02:47:51 +00001652 // Delete the instruction.
1653 Inst->eraseFromParent();
Jakub Staszak632a3552012-01-18 21:16:33 +00001654
Chris Lattnere405ed92009-11-02 02:47:51 +00001655 // Hey, we just changed something!
1656 MadeChanges = true;
1657 ++NumInstRemoved;
1658 }
1659 }
Chris Lattner074be1f2004-11-15 04:44:20 +00001660
1661 return MadeChanges;
1662}
Chris Lattnerb4394642004-12-10 08:02:06 +00001663
Gabor Greif9027ffb2010-03-24 10:29:52 +00001664static bool AddressIsTaken(const GlobalValue *GV) {
Chris Lattner8cb10a12005-04-19 19:16:19 +00001665 // Delete any dead constantexpr klingons.
1666 GV->removeDeadConstantUsers();
1667
Chandler Carruthcdf47882014-03-09 03:16:01 +00001668 for (const Use &U : GV->uses()) {
1669 const User *UR = U.getUser();
1670 if (const StoreInst *SI = dyn_cast<StoreInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001671 if (SI->getOperand(0) == GV || SI->isVolatile())
1672 return true; // Storing addr of GV.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001673 } else if (isa<InvokeInst>(UR) || isa<CallInst>(UR)) {
Chris Lattnerb4394642004-12-10 08:02:06 +00001674 // Make sure we are calling the function, not passing the address.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001675 ImmutableCallSite CS(cast<Instruction>(UR));
1676 if (!CS.isCallee(&U))
Nick Lewyckyd73806a2008-11-03 03:49:14 +00001677 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001678 } else if (const LoadInst *LI = dyn_cast<LoadInst>(UR)) {
Chris Lattner91dbae62004-12-11 05:15:59 +00001679 if (LI->isVolatile())
1680 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001681 } else if (isa<BlockAddress>(UR)) {
Chris Lattner1a8b80e2009-11-01 06:11:53 +00001682 // blockaddress doesn't take the address of the function, it takes addr
1683 // of label.
Chris Lattner91dbae62004-12-11 05:15:59 +00001684 } else {
Chris Lattnerb4394642004-12-10 08:02:06 +00001685 return true;
1686 }
Gabor Greif9027ffb2010-03-24 10:29:52 +00001687 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001688 return false;
1689}
1690
Davide Italianof54f2f02016-05-05 21:05:36 +00001691static bool runIPSCCP(Module &M, const DataLayout &DL,
1692 const TargetLibraryInfo *TLI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001693 SCCPSolver Solver(DL, TLI);
Chris Lattnerb4394642004-12-10 08:02:06 +00001694
Chris Lattner363226d2010-08-12 22:25:23 +00001695 // AddressTakenFunctions - This set keeps track of the address-taken functions
1696 // that are in the input. As IPSCCP runs through and simplifies code,
1697 // functions that were address taken can end up losing their
1698 // address-taken-ness. Because of this, we keep track of their addresses from
1699 // the first pass so we can use them for the later simplification pass.
1700 SmallPtrSet<Function*, 32> AddressTakenFunctions;
Jakub Staszak632a3552012-01-18 21:16:33 +00001701
Chris Lattnerb4394642004-12-10 08:02:06 +00001702 // Loop over all functions, marking arguments to those with their addresses
1703 // taken or that are external as overdefined.
1704 //
Davide Italianoe7c56c52016-05-14 20:59:09 +00001705 for (Function &F : M) {
1706 if (F.isDeclaration())
Chris Lattner47837c52009-11-02 06:34:04 +00001707 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001708
Sanjoy Das5ce32722016-04-08 00:48:30 +00001709 // If this is an exact definition of this function, then we can propagate
1710 // information about its result into callsites of it.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001711 if (F.hasExactDefinition())
1712 Solver.AddTrackedFunction(&F);
Jakub Staszak632a3552012-01-18 21:16:33 +00001713
Chris Lattnerfb141812009-11-03 03:42:51 +00001714 // If this function only has direct calls that we can see, we can track its
1715 // arguments and return value aggressively, and can assume it is not called
1716 // unless we see evidence to the contrary.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001717 if (F.hasLocalLinkage()) {
1718 if (AddressIsTaken(&F))
1719 AddressTakenFunctions.insert(&F);
Chris Lattner363226d2010-08-12 22:25:23 +00001720 else {
Davide Italianoe7c56c52016-05-14 20:59:09 +00001721 Solver.AddArgumentTrackedFunction(&F);
Chris Lattner363226d2010-08-12 22:25:23 +00001722 continue;
1723 }
Chris Lattnercde8de52009-11-03 19:24:51 +00001724 }
Chris Lattnerfb141812009-11-03 03:42:51 +00001725
1726 // Assume the function is called.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001727 Solver.MarkBlockExecutable(&F.front());
Jakub Staszak632a3552012-01-18 21:16:33 +00001728
Chris Lattnerfb141812009-11-03 03:42:51 +00001729 // Assume nothing about the incoming arguments.
Davide Italianoe7c56c52016-05-14 20:59:09 +00001730 for (Argument &AI : F.args())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001731 Solver.markAnythingOverdefined(&AI);
Chris Lattner47837c52009-11-02 06:34:04 +00001732 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001733
Chris Lattner91dbae62004-12-11 05:15:59 +00001734 // Loop over global variables. We inform the solver about any internal global
1735 // variables that do not have their 'addresses taken'. If they don't have
1736 // their addresses taken, we can propagate constants through them.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001737 for (GlobalVariable &G : M.globals())
1738 if (!G.isConstant() && G.hasLocalLinkage() && !AddressIsTaken(&G))
1739 Solver.TrackValueOfGlobalVariable(&G);
Chris Lattner91dbae62004-12-11 05:15:59 +00001740
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) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001760 if (F->isDeclaration())
1761 continue;
1762
1763 if (Solver.isBlockExecutable(&F->front())) {
Chris Lattnere82b0872009-11-02 03:25:55 +00001764 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1765 AI != E; ++AI) {
Duncan Sands19d0b472010-02-16 11:11:14 +00001766 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001767
Chris Lattner156b8c72009-11-03 23:40:48 +00001768 // TODO: Could use getStructLatticeValueFor to find out if the entire
1769 // result is a constant and replace it entirely if so.
1770
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001771 LatticeVal IV = Solver.getLatticeValueFor(&*AI);
Chris Lattnere82b0872009-11-02 03:25:55 +00001772 if (IV.isOverdefined()) continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001773
Chris Lattnere82b0872009-11-02 03:25:55 +00001774 Constant *CST = IV.isConstant() ?
1775 IV.getConstant() : UndefValue::get(AI->getType());
David Greene389fc3b2010-01-05 01:27:15 +00001776 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Jakub Staszak632a3552012-01-18 21:16:33 +00001777
Chris Lattnere82b0872009-11-02 03:25:55 +00001778 // Replaces all of the uses of a variable with uses of the
1779 // constant.
1780 AI->replaceAllUsesWith(CST);
1781 ++IPNumArgsElimed;
1782 }
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001783 }
Chris Lattnerb4394642004-12-10 08:02:06 +00001784
Chris Lattnere405ed92009-11-02 02:47:51 +00001785 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001786 if (!Solver.isBlockExecutable(&*BB)) {
David Majnemer88542a02016-01-24 06:26:47 +00001787 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
Chris Lattner7285f432004-12-10 20:41:50 +00001788
David Majnemer88542a02016-01-24 06:26:47 +00001789 ++NumDeadBlocks;
1790 NumInstRemoved +=
David Majnemereec87852016-01-24 16:46:53 +00001791 changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false);
David Majnemer88542a02016-01-24 06:26:47 +00001792
1793 MadeChanges = true;
Chris Lattnerbae4b642004-12-10 22:29:08 +00001794
Chris Lattner8525ebe2004-12-11 05:32:19 +00001795 if (&*BB != &F->front())
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001796 BlocksToErase.push_back(&*BB);
Chris Lattnere405ed92009-11-02 02:47:51 +00001797 continue;
Chris Lattnerb4394642004-12-10 08:02:06 +00001798 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001799
Chris Lattnere405ed92009-11-02 02:47:51 +00001800 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001801 Instruction *Inst = &*BI++;
Duncan Sands19d0b472010-02-16 11:11:14 +00001802 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
Chris Lattnere405ed92009-11-02 02:47:51 +00001803 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001804
Chris Lattner156b8c72009-11-03 23:40:48 +00001805 // TODO: Could use getStructLatticeValueFor to find out if the entire
1806 // result is a constant and replace it entirely if so.
Jakub Staszak632a3552012-01-18 21:16:33 +00001807
Chris Lattnerb5a13d42009-11-02 02:54:24 +00001808 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1809 if (IV.isOverdefined())
Chris Lattnere405ed92009-11-02 02:47:51 +00001810 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001811
Chris Lattnere405ed92009-11-02 02:47:51 +00001812 Constant *Const = IV.isConstant()
1813 ? IV.getConstant() : UndefValue::get(Inst->getType());
Nick Lewycky5cd95382013-06-26 00:30:18 +00001814 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst << '\n');
Chris Lattnere405ed92009-11-02 02:47:51 +00001815
1816 // Replaces all of the uses of a variable with uses of the
1817 // constant.
1818 Inst->replaceAllUsesWith(Const);
Jakub Staszak632a3552012-01-18 21:16:33 +00001819
Chris Lattnere405ed92009-11-02 02:47:51 +00001820 // Delete the instruction.
1821 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1822 Inst->eraseFromParent();
1823
1824 // Hey, we just changed something!
1825 MadeChanges = true;
1826 ++IPNumInstRemoved;
1827 }
1828 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001829
1830 // Now that all instructions in the function are constant folded, erase dead
1831 // blocks, because we can now use ConstantFoldTerminator to get rid of
1832 // in-edges.
1833 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1834 // If there are any PHI nodes in this successor, drop entries for BB now.
1835 BasicBlock *DeadBB = BlocksToErase[i];
Chandler Carruthcdf47882014-03-09 03:16:01 +00001836 for (Value::user_iterator UI = DeadBB->user_begin(),
1837 UE = DeadBB->user_end();
1838 UI != UE;) {
Dan Gohman1f522d92009-11-23 16:13:39 +00001839 // Grab the user and then increment the iterator early, as the user
1840 // will be deleted. Step past all adjacent uses from the same user.
1841 Instruction *I = dyn_cast<Instruction>(*UI);
1842 do { ++UI; } while (UI != UE && *UI == I);
1843
Dan Gohmand15302a2009-11-20 20:19:14 +00001844 // Ignore blockaddress users; BasicBlock's dtor will handle them.
Dan Gohmand15302a2009-11-20 20:19:14 +00001845 if (!I) continue;
1846
Chris Lattnerbae4b642004-12-10 22:29:08 +00001847 bool Folded = ConstantFoldTerminator(I->getParent());
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001848 if (!Folded) {
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001849 // The constant folder may not have been able to fold the terminator
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001850 // if this is a branch or switch on undef. Fold it manually as a
1851 // branch to the first successor.
Devang Patel45f1ae02008-11-21 01:52:59 +00001852#ifndef NDEBUG
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001853 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1854 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1855 "Branch should be foldable!");
1856 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1857 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1858 } else {
Torok Edwinfbcc6632009-07-14 16:55:14 +00001859 llvm_unreachable("Didn't fold away reference to block!");
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001860 }
Devang Patel45f1ae02008-11-21 01:52:59 +00001861#endif
Jakub Staszak632a3552012-01-18 21:16:33 +00001862
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001863 // Make this an uncond branch to the first successor.
1864 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greife9ecc682008-04-06 20:25:17 +00001865 BranchInst::Create(TI->getSuccessor(0), TI);
Jakub Staszak632a3552012-01-18 21:16:33 +00001866
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001867 // Remove entries in successor phi nodes to remove edges.
1868 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1869 TI->getSuccessor(i)->removePredecessor(TI->getParent());
Jakub Staszak632a3552012-01-18 21:16:33 +00001870
Chris Lattnerfe7b6ef2006-10-23 18:57:02 +00001871 // Remove the old terminator.
1872 TI->eraseFromParent();
1873 }
Chris Lattnerbae4b642004-12-10 22:29:08 +00001874 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001875
Chris Lattnerbae4b642004-12-10 22:29:08 +00001876 // Finally, delete the basic block.
1877 F->getBasicBlockList().erase(DeadBB);
1878 }
Chris Lattner37d400a2007-02-02 21:15:06 +00001879 BlocksToErase.clear();
Chris Lattnerb4394642004-12-10 08:02:06 +00001880 }
Chris Lattner99e12952004-12-11 02:53:57 +00001881
1882 // If we inferred constant or undef return values for a function, we replaced
1883 // all call uses with the inferred value. This means we don't need to bother
1884 // actually returning anything from the function. Replace all return
1885 // instructions with return undef.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001886 //
1887 // Do this in two stages: first identify the functions we should process, then
1888 // actually zap their returns. This is important because we can only do this
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001889 // if the address of the function isn't taken. In cases where a return is the
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001890 // last use of a function, the order of processing functions would affect
Chris Lattner2af7e3d2010-02-27 07:50:40 +00001891 // whether other functions are optimizable.
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001892 SmallVector<ReturnInst*, 8> ReturnsToZap;
Jakub Staszak632a3552012-01-18 21:16:33 +00001893
Devang Patele418de32008-03-11 17:32:05 +00001894 // TODO: Process multiple value ret instructions also.
Devang Patela7a20752008-03-11 05:46:42 +00001895 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Chris Lattner067d6072007-02-02 20:38:30 +00001896 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
Chris Lattnerfb141812009-11-03 03:42:51 +00001897 E = RV.end(); I != E; ++I) {
1898 Function *F = I->first;
1899 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1900 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001901
Chris Lattnerfb141812009-11-03 03:42:51 +00001902 // We can only do this if we know that nothing else can call the function.
Chris Lattner363226d2010-08-12 22:25:23 +00001903 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
Chris Lattnerfb141812009-11-03 03:42:51 +00001904 continue;
Jakub Staszak632a3552012-01-18 21:16:33 +00001905
Chris Lattnerfb141812009-11-03 03:42:51 +00001906 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1907 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1908 if (!isa<UndefValue>(RI->getOperand(0)))
Chris Lattnerd887f1d2010-02-27 00:07:42 +00001909 ReturnsToZap.push_back(RI);
1910 }
1911
1912 // Zap all returns which we've identified as zap to change.
1913 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1914 Function *F = ReturnsToZap[i]->getParent()->getParent();
1915 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
Chris Lattnerfb141812009-11-03 03:42:51 +00001916 }
Jakub Staszak632a3552012-01-18 21:16:33 +00001917
Chad Rosierbb2a6da2012-03-28 00:35:33 +00001918 // If we inferred constant or undef values for globals variables, we can
1919 // delete the global and any stores that remain to it.
Chris Lattner067d6072007-02-02 20:38:30 +00001920 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1921 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
Chris Lattner91dbae62004-12-11 05:15:59 +00001922 E = TG.end(); I != E; ++I) {
1923 GlobalVariable *GV = I->first;
1924 assert(!I->second.isOverdefined() &&
1925 "Overdefined values should have been taken out of the map!");
David Greene389fc3b2010-01-05 01:27:15 +00001926 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Chris Lattner91dbae62004-12-11 05:15:59 +00001927 while (!GV->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001928 StoreInst *SI = cast<StoreInst>(GV->user_back());
Chris Lattner91dbae62004-12-11 05:15:59 +00001929 SI->eraseFromParent();
1930 }
1931 M.getGlobalList().erase(GV);
Chris Lattner2f687fd2004-12-11 06:05:53 +00001932 ++IPNumGlobalConst;
Chris Lattner91dbae62004-12-11 05:15:59 +00001933 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001934
Chris Lattnerb4394642004-12-10 08:02:06 +00001935 return MadeChanges;
1936}
Davide Italianof54f2f02016-05-05 21:05:36 +00001937
1938PreservedAnalyses IPSCCPPass::run(Module &M, AnalysisManager<Module> &AM) {
1939 const DataLayout &DL = M.getDataLayout();
1940 auto &TLI = AM.getResult<TargetLibraryAnalysis>(M);
1941 if (!runIPSCCP(M, DL, &TLI))
1942 return PreservedAnalyses::all();
1943 return PreservedAnalyses::none();
1944}
1945
1946namespace {
1947//===--------------------------------------------------------------------===//
1948//
1949/// IPSCCP Class - This class implements interprocedural Sparse Conditional
1950/// Constant Propagation.
1951///
1952struct IPSCCPLegacyPass : public ModulePass {
1953 static char ID;
1954
1955 IPSCCPLegacyPass() : ModulePass(ID) {
1956 initializeIPSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1957 }
1958
1959 bool runOnModule(Module &M) override {
1960 if (skipModule(M))
1961 return false;
1962 const DataLayout &DL = M.getDataLayout();
1963 const TargetLibraryInfo *TLI =
1964 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1965 return runIPSCCP(M, DL, TLI);
1966 }
1967
1968 void getAnalysisUsage(AnalysisUsage &AU) const override {
1969 AU.addRequired<TargetLibraryInfoWrapperPass>();
1970 }
1971};
1972} // end anonymous namespace
1973
1974char IPSCCPLegacyPass::ID = 0;
1975INITIALIZE_PASS_BEGIN(IPSCCPLegacyPass, "ipsccp",
1976 "Interprocedural Sparse Conditional Constant Propagation",
1977 false, false)
1978INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1979INITIALIZE_PASS_END(IPSCCPLegacyPass, "ipsccp",
1980 "Interprocedural Sparse Conditional Constant Propagation",
1981 false, false)
1982
1983// createIPSCCPPass - This is the public interface to this file.
1984ModulePass *llvm::createIPSCCPPass() { return new IPSCCPLegacyPass(); }