blob: f58fead5197c37b303c9e6f0168d2b0cbb7acef3 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements sparse conditional constant propagation and merging:
11//
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
16// * Proves conditional branches to be unconditional
17//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "sccp"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Instructions.h"
26#include "llvm/Pass.h"
27#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohman856193b2008-06-20 01:15:44 +000029#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/Transforms/Utils/Local.h"
Chris Lattner0148bb22009-11-02 06:06:14 +000031#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000034#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000036#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000038#include "llvm/ADT/DenseSet.h"
Chris Lattner1eb405b2009-11-02 02:20:32 +000039#include "llvm/ADT/PointerIntPair.h"
Chris Lattnera5ffa7c2009-11-02 06:11:23 +000040#include "llvm/ADT/SmallPtrSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
44#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000045#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046using namespace llvm;
47
48STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
53STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
54
55namespace {
56/// 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 Lattnerfa2d1ba2009-09-02 06:11:42 +000059class LatticeVal {
Chris Lattner1eb405b2009-11-02 02:20:32 +000060 enum LatticeValueTy {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061 /// undefined - This LLVM Value has no known value yet.
62 undefined,
63
64 /// 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,
72
73 /// overdefined - This instruction is not known to be constant, and we know
74 /// it has a value.
75 overdefined
Chris Lattner1eb405b2009-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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
Chris Lattner1eb405b2009-11-02 02:20:32 +000082 LatticeValueTy getLatticeValue() const {
83 return Val.getInt();
84 }
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086public:
Chris Lattnerb52f7002009-11-02 03:03:42 +000087 LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088
Chris Lattnerb52f7002009-11-02 03:03:42 +000089 bool isUndefined() const { return getLatticeValue() == undefined; }
90 bool isConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000091 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
92 }
Chris Lattnerb52f7002009-11-02 03:03:42 +000093 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner1eb405b2009-11-02 02:20:32 +000094
Chris Lattnerb52f7002009-11-02 03:03:42 +000095 Constant *getConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000096 assert(isConstant() && "Cannot get the constant of a non-constant!");
97 return Val.getPointer();
98 }
99
100 /// markOverdefined - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000101 bool markOverdefined() {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000102 if (isOverdefined())
103 return false;
104
105 Val.setInt(overdefined);
106 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 }
108
Chris Lattner1eb405b2009-11-02 02:20:32 +0000109 /// markConstant - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000110 bool markConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000111 if (isConstant()) {
112 assert(getConstant() == V && "Marking constant with different value");
113 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 }
Chris Lattner1eb405b2009-11-02 02:20:32 +0000115
116 if (isUndefined()) {
117 Val.setInt(constant);
118 assert(V && "Marking constant with NULL");
119 Val.setPointer(V);
120 } else {
121 assert(getLatticeValue() == forcedconstant &&
122 "Cannot move from overdefined to constant!");
123 // Stay at forcedconstant if the constant is the same.
124 if (V == getConstant()) return false;
125
126 // 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;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 }
133
Chris Lattner220571c2009-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());
139 return 0;
140 }
141
Chris Lattnerb52f7002009-11-02 03:03:42 +0000142 void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000143 assert(isUndefined() && "Can't force a defined value!");
144 Val.setInt(forcedconstant);
145 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 }
147};
Chris Lattner14513dc2009-11-02 02:47:51 +0000148} // end anonymous namespace.
149
150
151namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153//===----------------------------------------------------------------------===//
154//
155/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
156/// Constant Propagation.
157///
158class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattner0148bb22009-11-02 06:06:14 +0000159 const TargetData *TD;
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000160 SmallPtrSet<BasicBlock*, 8> BBExecutable;// The BBs that are executable.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000161 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162
163 /// GlobalValue - If we are tracking any values for the contents of a global
164 /// variable, we keep a mapping from the constant accessor to the element of
165 /// the global, to the currently known value. If the value becomes
166 /// overdefined, it's entry is simply removed from this map.
167 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
168
Devang Pateladd320d2008-03-11 05:46:42 +0000169 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 /// value out of a function, it will have an entry in this map, indicating
171 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000172 DenseMap<Function*, LatticeVal> TrackedRetVals;
173
174 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
175 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000176 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177
Chris Lattnerb52f7002009-11-02 03:03:42 +0000178 /// The reason for two worklists is that overdefined is the lowest state
179 /// on the lattice, and moving things to overdefined as fast as possible
180 /// makes SCCP converge much faster.
181 ///
182 /// By having a separate worklist, we accomplish this because everything
183 /// possibly overdefined will become overdefined at the soonest possible
184 /// point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000185 SmallVector<Value*, 64> OverdefinedInstWorkList;
186 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187
188
Chris Lattnerd3123a72008-08-23 23:36:38 +0000189 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190
191 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
192 /// overdefined, despite the fact that the PHI node is overdefined.
193 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
194
195 /// KnownFeasibleEdges - Entries in this set are edges which have already had
196 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000197 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
198 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199public:
Chris Lattner0148bb22009-11-02 06:06:14 +0000200 SCCPSolver(const TargetData *td) : TD(td) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201
202 /// MarkBlockExecutable - This method can be used by clients to mark all of
203 /// the blocks that are known to be intrinsically live in the processed unit.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000204 ///
205 /// This returns true if the block was not considered live before.
206 bool MarkBlockExecutable(BasicBlock *BB) {
207 if (!BBExecutable.insert(BB)) return false;
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000208 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 BBWorkList.push_back(BB); // Add the block to the work list!
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000210 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 }
212
213 /// TrackValueOfGlobalVariable - Clients can use this method to
214 /// inform the SCCPSolver that it should track loads and stores to the
215 /// specified global variable if it can. This is only legal to call if
216 /// performing Interprocedural SCCP.
217 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
218 const Type *ElTy = GV->getType()->getElementType();
219 if (ElTy->isFirstClassType()) {
220 LatticeVal &IV = TrackedGlobals[GV];
221 if (!isa<UndefValue>(GV->getInitializer()))
222 IV.markConstant(GV->getInitializer());
223 }
224 }
225
226 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
227 /// and out of the specified function (which cannot have its address taken),
228 /// this method must be called.
229 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000230 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000232 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
233 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000234 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
235 LatticeVal()));
236 } else
237 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 }
239
240 /// Solve - Solve for constants and executable blocks.
241 ///
242 void Solve();
243
244 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
245 /// that branches on undef values cannot reach any of their successors.
246 /// However, this is not a safe assumption. After we solve dataflow, this
247 /// method should be use to handle this. If this returns true, the solver
248 /// should be rerun.
249 bool ResolvedUndefsIn(Function &F);
250
Chris Lattner317e6b62008-08-23 23:39:31 +0000251 bool isBlockExecutable(BasicBlock *BB) const {
252 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 }
254
Chris Lattnerc9edab82009-11-02 02:54:24 +0000255 LatticeVal getLatticeValueFor(Value *V) const {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000256 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
Chris Lattnerc9edab82009-11-02 02:54:24 +0000257 assert(I != ValueState.end() && "V is not in valuemap!");
258 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 }
260
Devang Pateladd320d2008-03-11 05:46:42 +0000261 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000263 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
264 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 }
266
267 /// getTrackedGlobals - Get and return the set of inferred initializers for
268 /// global variables.
269 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
270 return TrackedGlobals;
271 }
272
Chris Lattner220571c2009-11-02 03:21:36 +0000273 void markOverdefined(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 markOverdefined(ValueState[V], V);
275 }
276
277private:
278 // markConstant - Make a value be marked as "constant". If the value
279 // is not already a constant, add it to the instruction work list so that
280 // the users of the instruction are updated later.
281 //
Chris Lattnerb52f7002009-11-02 03:03:42 +0000282 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
283 if (!IV.markConstant(C)) return;
284 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
285 InstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 }
287
Chris Lattnerb52f7002009-11-02 03:03:42 +0000288 void markConstant(Value *V, Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 markConstant(ValueState[V], V, C);
290 }
291
Chris Lattner6367c3f2009-11-02 05:55:40 +0000292 void markForcedConstant(Value *V, Constant *C) {
293 ValueState[V].markForcedConstant(C);
294 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
295 InstWorkList.push_back(V);
296 }
297
298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299 // markOverdefined - Make a value be marked as "overdefined". If the
300 // value is not already overdefined, add it to the overdefined instruction
301 // work list so that the users of the instruction are updated later.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000302 void markOverdefined(LatticeVal &IV, Value *V) {
303 if (!IV.markOverdefined()) return;
304
305 DEBUG(errs() << "markOverdefined: ";
306 if (Function *F = dyn_cast<Function>(V))
307 errs() << "Function '" << F->getName() << "'\n";
308 else
309 errs() << *V << '\n');
310 // Only instructions go on the work list
311 OverdefinedInstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 }
313
Chris Lattner6367c3f2009-11-02 05:55:40 +0000314 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 if (IV.isOverdefined() || MergeWithV.isUndefined())
316 return; // Noop.
317 if (MergeWithV.isOverdefined())
318 markOverdefined(IV, V);
319 else if (IV.isUndefined())
320 markConstant(IV, V, MergeWithV.getConstant());
321 else if (IV.getConstant() != MergeWithV.getConstant())
322 markOverdefined(IV, V);
323 }
324
Chris Lattner6367c3f2009-11-02 05:55:40 +0000325 void mergeInValue(Value *V, LatticeVal MergeWithV) {
Chris Lattner220571c2009-11-02 03:21:36 +0000326 mergeInValue(ValueState[V], V, MergeWithV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 }
328
329
Chris Lattner6367c3f2009-11-02 05:55:40 +0000330 /// getValueState - Return the LatticeVal object that corresponds to the
331 /// value. This function handles the case when the value hasn't been seen yet
332 /// by properly seeding constants etc.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000333 LatticeVal &getValueState(Value *V) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000334 DenseMap<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 if (I != ValueState.end()) return I->second; // Common case, in the map
336
Chris Lattner220571c2009-11-02 03:21:36 +0000337 LatticeVal &LV = ValueState[V];
338
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner220571c2009-11-02 03:21:36 +0000340 // Undef values remain undefined.
341 if (!isa<UndefValue>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 LV.markConstant(C); // Constants are constant
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343 }
Chris Lattner220571c2009-11-02 03:21:36 +0000344
Chris Lattnerc8798002009-11-02 02:33:50 +0000345 // All others are underdefined by default.
Chris Lattner220571c2009-11-02 03:21:36 +0000346 return LV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 }
348
Chris Lattner6367c3f2009-11-02 05:55:40 +0000349 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
350 /// work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
352 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
353 return; // This edge is already known to be executable!
354
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000355 if (!MarkBlockExecutable(Dest)) {
356 // If the destination is already executable, we just made an *edge*
357 // feasible that wasn't before. Revisit the PHI nodes in the block
358 // because they have potentially new operands.
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000359 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
360 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361
Chris Lattnera5ffa7c2009-11-02 06:11:23 +0000362 PHINode *PN;
363 for (BasicBlock::iterator I = Dest->begin();
364 (PN = dyn_cast<PHINode>(I)); ++I)
365 visitPHINode(*PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 }
367 }
368
369 // getFeasibleSuccessors - Return a vector of booleans to indicate which
370 // successors are reachable from a given terminator instruction.
371 //
372 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
373
374 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000375 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 //
377 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
378
379 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000380 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 // information, we need to update the specified user of this instruction.
382 //
383 void OperandChangedState(User *U) {
384 // Only instructions use other variable values!
385 Instruction &I = cast<Instruction>(*U);
386 if (BBExecutable.count(I.getParent())) // Inst is executable?
387 visit(I);
388 }
389
390private:
391 friend class InstVisitor<SCCPSolver>;
392
Chris Lattnerc8798002009-11-02 02:33:50 +0000393 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 // operand made a transition, or the instruction is newly executable. Change
395 // the value type of I to reflect these changes if appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396 void visitPHINode(PHINode &I);
397
398 // Terminators
399 void visitReturnInst(ReturnInst &I);
400 void visitTerminatorInst(TerminatorInst &TI);
401
402 void visitCastInst(CastInst &I);
403 void visitSelectInst(SelectInst &I);
404 void visitBinaryOperator(Instruction &I);
405 void visitCmpInst(CmpInst &I);
406 void visitExtractElementInst(ExtractElementInst &I);
407 void visitInsertElementInst(InsertElementInst &I);
408 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000409 void visitExtractValueInst(ExtractValueInst &EVI);
410 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411
Chris Lattnerc8798002009-11-02 02:33:50 +0000412 // Instructions that cannot be folded away.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000413 void visitStoreInst (StoreInst &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 void visitLoadInst (LoadInst &I);
415 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000416 void visitCallInst (CallInst &I) {
417 if (isFreeCall(&I))
418 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000419 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000420 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 void visitInvokeInst (InvokeInst &II) {
422 visitCallSite(CallSite::get(&II));
423 visitTerminatorInst(II);
424 }
425 void visitCallSite (CallSite CS);
426 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
427 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000428 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
430 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431
432 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000433 // If a new instruction is added to LLVM that we don't handle.
Chris Lattner8a6411c2009-08-23 04:37:46 +0000434 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 markOverdefined(&I); // Just in case
436 }
437};
438
Duncan Sands40f67972007-07-20 08:56:21 +0000439} // end anonymous namespace
440
441
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442// getFeasibleSuccessors - Return a vector of booleans to indicate which
443// successors are reachable from a given terminator instruction.
444//
445void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
446 SmallVector<bool, 16> &Succs) {
447 Succs.resize(TI.getNumSuccessors());
448 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
449 if (BI->isUnconditional()) {
450 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000451 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000453
Chris Lattner6367c3f2009-11-02 05:55:40 +0000454 LatticeVal BCValue = getValueState(BI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000455 ConstantInt *CI = BCValue.getConstantInt();
456 if (CI == 0) {
Chris Lattneradaf7332009-11-02 02:30:06 +0000457 // Overdefined condition variables, and branches on unfoldable constant
458 // conditions, mean the branch could go either way.
Chris Lattner220571c2009-11-02 03:21:36 +0000459 if (!BCValue.isUndefined())
460 Succs[0] = Succs[1] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000461 return;
462 }
463
464 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000465 Succs[CI->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000466 return;
467 }
468
Chris Lattner220571c2009-11-02 03:21:36 +0000469 if (isa<InvokeInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 // Invoke instructions successors are always executable.
471 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000472 return;
473 }
474
475 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000476 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000477 ConstantInt *CI = SCValue.getConstantInt();
478
479 if (CI == 0) { // Overdefined or undefined condition?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000480 // All destinations are executable!
Chris Lattner220571c2009-11-02 03:21:36 +0000481 if (!SCValue.isUndefined())
482 Succs.assign(TI.getNumSuccessors(), true);
483 return;
484 }
485
486 Succs[SI->findCaseValue(CI)] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000487 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000489
490 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
491 if (isa<IndirectBrInst>(&TI)) {
492 // Just mark all destinations executable!
493 Succs.assign(TI.getNumSuccessors(), true);
494 return;
495 }
496
497#ifndef NDEBUG
498 errs() << "Unknown terminator instruction: " << TI << '\n';
499#endif
500 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501}
502
503
504// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000505// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506//
507bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
508 assert(BBExecutable.count(To) && "Dest should always be alive!");
509
510 // Make sure the source basic block is executable!!
511 if (!BBExecutable.count(From)) return false;
512
Chris Lattnerc8798002009-11-02 02:33:50 +0000513 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 TerminatorInst *TI = From->getTerminator();
515 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
516 if (BI->isUnconditional())
517 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000518
Chris Lattner6367c3f2009-11-02 05:55:40 +0000519 LatticeVal BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520
Chris Lattneradaf7332009-11-02 02:30:06 +0000521 // Overdefined condition variables mean the branch could go either way,
522 // undef conditions mean that neither edge is feasible yet.
Chris Lattner220571c2009-11-02 03:21:36 +0000523 ConstantInt *CI = BCValue.getConstantInt();
524 if (CI == 0)
525 return !BCValue.isUndefined();
Chris Lattneradaf7332009-11-02 02:30:06 +0000526
Chris Lattneradaf7332009-11-02 02:30:06 +0000527 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000528 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000529 }
530
531 // Invoke instructions successors are always executable.
532 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000534
535 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000536 LatticeVal SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000537 ConstantInt *CI = SCValue.getConstantInt();
538
539 if (CI == 0)
540 return !SCValue.isUndefined();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541
Chris Lattner220571c2009-11-02 03:21:36 +0000542 // Make sure to skip the "default value" which isn't a value
543 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
544 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
545 return SI->getSuccessor(i) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000546
Chris Lattner220571c2009-11-02 03:21:36 +0000547 // If the constant value is not equal to any of the branches, we must
548 // execute default branch.
549 return SI->getDefaultDest() == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000550 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000551
552 // Just mark all destinations executable!
553 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
554 if (isa<IndirectBrInst>(&TI))
555 return true;
556
557#ifndef NDEBUG
558 errs() << "Unknown terminator instruction: " << *TI << '\n';
559#endif
560 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561}
562
Chris Lattnerc8798002009-11-02 02:33:50 +0000563// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564// operand made a transition, or the instruction is newly executable. Change
565// the value type of I to reflect these changes if appropriate. This method
566// makes sure to do the following actions:
567//
568// 1. If a phi node merges two constants in, and has conflicting value coming
569// from different branches, or if the PHI node merges in an overdefined
570// value, then the PHI node becomes overdefined.
571// 2. If a phi node merges only constants in, and they all agree on value, the
572// PHI node becomes a constant value equal to that.
573// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
574// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
575// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
576// 6. If a conditional branch has a value that is constant, make the selected
577// destination executable
578// 7. If a conditional branch has a value that is overdefined, make all
579// successors executable.
580//
581void SCCPSolver::visitPHINode(PHINode &PN) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000582 if (getValueState(&PN).isOverdefined()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 // There may be instructions using this PHI node that are not overdefined
584 // themselves. If so, make sure that they know that the PHI node operand
585 // changed.
586 std::multimap<PHINode*, Instruction*>::iterator I, E;
587 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000588 if (I == E)
589 return;
590
591 SmallVector<Instruction*, 16> Users;
592 for (; I != E; ++I)
593 Users.push_back(I->second);
594 while (!Users.empty())
595 visit(Users.pop_back_val());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 return; // Quick exit
597 }
598
599 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
600 // and slow us down a lot. Just mark them overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000601 if (PN.getNumIncomingValues() > 64)
Chris Lattner6367c3f2009-11-02 05:55:40 +0000602 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603
604 // Look at all of the executable operands of the PHI node. If any of them
605 // are overdefined, the PHI becomes overdefined as well. If they are all
606 // constant, and they agree with each other, the PHI becomes the identical
607 // constant. If they are constant and don't agree, the PHI is overdefined.
608 // If there are no executable operands, the PHI remains undefined.
609 //
610 Constant *OperandVal = 0;
611 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000612 LatticeVal IV = getValueState(PN.getIncomingValue(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
614
Chris Lattnerb52f7002009-11-02 03:03:42 +0000615 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
616 continue;
617
618 if (IV.isOverdefined()) // PHI node becomes overdefined!
619 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620
Chris Lattnerb52f7002009-11-02 03:03:42 +0000621 if (OperandVal == 0) { // Grab the first value.
622 OperandVal = IV.getConstant();
623 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 }
Chris Lattnerb52f7002009-11-02 03:03:42 +0000625
626 // There is already a reachable operand. If we conflict with it,
627 // then the PHI node becomes overdefined. If we agree with it, we
628 // can continue on.
629
630 // Check to see if there are two different constants merging, if so, the PHI
631 // node is overdefined.
632 if (IV.getConstant() != OperandVal)
633 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 }
635
636 // If we exited the loop, this means that the PHI node only has constant
637 // arguments that agree with each other(and OperandVal is the constant) or
638 // OperandVal is null because there are no defined incoming arguments. If
639 // this is the case, the PHI remains undefined.
640 //
641 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000642 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643}
644
645void SCCPSolver::visitReturnInst(ReturnInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000646 if (I.getNumOperands() == 0) return; // ret void
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000648 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000649 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000650 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000651 return;
652
Chris Lattner6367c3f2009-11-02 05:55:40 +0000653 if (!TrackedRetVals.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000655 TrackedRetVals.find(F);
656 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000657 !TFRVI->second.isOverdefined()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000658 mergeInValue(TFRVI->second, F, getValueState(I.getOperand(0)));
Devang Pateladd320d2008-03-11 05:46:42 +0000659 return;
660 }
661 }
662
Chris Lattnercd73be02008-04-23 05:38:20 +0000663 // Handle functions that return multiple values.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000664 if (0 && !TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
Chris Lattnercd73be02008-04-23 05:38:20 +0000665 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000666 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000667 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
668 if (It == TrackedMultipleRetVals.end()) break;
669 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 }
Dan Gohman856193b2008-06-20 01:15:44 +0000671 } else if (!TrackedMultipleRetVals.empty() &&
Chris Lattner6367c3f2009-11-02 05:55:40 +0000672 /*I.getNumOperands() == 1 &&*/
Dan Gohman856193b2008-06-20 01:15:44 +0000673 isa<StructType>(I.getOperand(0)->getType())) {
674 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
675 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000676 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000677 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
678 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000679 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000680 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000681 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 }
683}
684
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
686 SmallVector<bool, 16> SuccFeasible;
687 getFeasibleSuccessors(TI, SuccFeasible);
688
689 BasicBlock *BB = TI.getParent();
690
Chris Lattnerc8798002009-11-02 02:33:50 +0000691 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
693 if (SuccFeasible[i])
694 markEdgeExecutable(BB, TI.getSuccessor(i));
695}
696
697void SCCPSolver::visitCastInst(CastInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000698 LatticeVal OpSt = getValueState(I.getOperand(0));
699 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 markOverdefined(&I);
Chris Lattner6367c3f2009-11-02 05:55:40 +0000701 else if (OpSt.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000702 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Chris Lattner6367c3f2009-11-02 05:55:40 +0000703 OpSt.getConstant(), I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704}
705
Dan Gohman856193b2008-06-20 01:15:44 +0000706void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000707 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000708
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000709 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000710 if (isa<UndefValue>(Aggr))
711 return;
712
713 // Currently only handle single-index extractvalues.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000714 if (EVI.getNumIndices() != 1)
715 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000716
717 Function *F = 0;
718 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
719 F = CI->getCalledFunction();
720 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
721 F = II->getCalledFunction();
722
723 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
724 // result back!
Chris Lattnerb52f7002009-11-02 03:03:42 +0000725 if (F == 0 || TrackedMultipleRetVals.empty())
726 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000727
Chris Lattnerd3123a72008-08-23 23:36:38 +0000728 // See if we are tracking the result of the callee. If not tracking this
729 // function (for example, it is a declaration) just move to overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000730 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin())))
731 return markOverdefined(&EVI);
Dan Gohman856193b2008-06-20 01:15:44 +0000732
733 // Otherwise, the value will be merged in here as a result of CallSite
734 // handling.
735}
736
737void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000738 Value *Aggr = IVI.getAggregateOperand();
739 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000740
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000741 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000742 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000743 return;
744
745 // Currently only handle single-index insertvalues.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000746 if (IVI.getNumIndices() != 1)
747 return markOverdefined(&IVI);
Dan Gohman78b2c392008-06-20 16:39:44 +0000748
749 // Currently only handle insertvalue instructions that are in a single-use
750 // chain that builds up a return value.
751 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
Chris Lattnerb52f7002009-11-02 03:03:42 +0000752 if (!TmpIVI->hasOneUse())
753 return markOverdefined(&IVI);
754
Dan Gohman78b2c392008-06-20 16:39:44 +0000755 const Value *V = *TmpIVI->use_begin();
756 if (isa<ReturnInst>(V))
757 break;
758 TmpIVI = dyn_cast<InsertValueInst>(V);
Chris Lattnerb52f7002009-11-02 03:03:42 +0000759 if (!TmpIVI)
760 return markOverdefined(&IVI);
Dan Gohman78b2c392008-06-20 16:39:44 +0000761 }
Dan Gohman856193b2008-06-20 01:15:44 +0000762
763 // See if we are tracking the result of the callee.
764 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000765 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000766 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
767
768 // Merge in the inserted member value.
769 if (It != TrackedMultipleRetVals.end())
770 mergeInValue(It->second, F, getValueState(Val));
771
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000772 // Mark the aggregate result of the IVI overdefined; any tracking that we do
773 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000774 markOverdefined(&IVI);
775}
776
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777void SCCPSolver::visitSelectInst(SelectInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000778 LatticeVal CondValue = getValueState(I.getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779 if (CondValue.isUndefined())
780 return;
Chris Lattner220571c2009-11-02 03:21:36 +0000781
782 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000783 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
784 mergeInValue(&I, getValueState(OpVal));
Chris Lattner220571c2009-11-02 03:21:36 +0000785 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 }
787
788 // Otherwise, the condition is overdefined or a constant we can't evaluate.
789 // See if we can produce something better than overdefined based on the T/F
790 // value.
Chris Lattner6367c3f2009-11-02 05:55:40 +0000791 LatticeVal TVal = getValueState(I.getTrueValue());
792 LatticeVal FVal = getValueState(I.getFalseValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793
794 // select ?, C, C -> C.
795 if (TVal.isConstant() && FVal.isConstant() &&
Chris Lattnerb52f7002009-11-02 03:03:42 +0000796 TVal.getConstant() == FVal.getConstant())
797 return markConstant(&I, FVal.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000798
Chris Lattner6367c3f2009-11-02 05:55:40 +0000799 if (TVal.isUndefined()) // select ?, undef, X -> X.
800 return mergeInValue(&I, FVal);
801 if (FVal.isUndefined()) // select ?, X, undef -> X.
802 return mergeInValue(&I, TVal);
803 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804}
805
Chris Lattner6367c3f2009-11-02 05:55:40 +0000806// Handle Binary Operators.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807void SCCPSolver::visitBinaryOperator(Instruction &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000808 LatticeVal V1State = getValueState(I.getOperand(0));
809 LatticeVal V2State = getValueState(I.getOperand(1));
810
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 LatticeVal &IV = ValueState[&I];
812 if (IV.isOverdefined()) return;
813
Chris Lattner6367c3f2009-11-02 05:55:40 +0000814 if (V1State.isConstant() && V2State.isConstant())
815 return markConstant(IV, &I,
816 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
817 V2State.getConstant()));
818
819 // If something is undef, wait for it to resolve.
820 if (!V1State.isOverdefined() && !V2State.isOverdefined())
821 return;
822
823 // Otherwise, one of our operands is overdefined. Try to produce something
824 // better than overdefined with some tricks.
825
826 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
827 // operand is overdefined.
828 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
829 LatticeVal *NonOverdefVal = 0;
830 if (!V1State.isOverdefined())
831 NonOverdefVal = &V1State;
832 else if (!V2State.isOverdefined())
833 NonOverdefVal = &V2State;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834
Chris Lattner6367c3f2009-11-02 05:55:40 +0000835 if (NonOverdefVal) {
836 if (NonOverdefVal->isUndefined()) {
837 // Could annihilate value.
838 if (I.getOpcode() == Instruction::And)
839 markConstant(IV, &I, Constant::getNullValue(I.getType()));
840 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
841 markConstant(IV, &I, Constant::getAllOnesValue(PT));
842 else
843 markConstant(IV, &I,
844 Constant::getAllOnesValue(I.getType()));
845 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000847
848 if (I.getOpcode() == Instruction::And) {
849 // X and 0 = 0
850 if (NonOverdefVal->getConstant()->isNullValue())
851 return markConstant(IV, &I, NonOverdefVal->getConstant());
852 } else {
853 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
854 if (CI->isAllOnesValue()) // X or -1 = -1
855 return markConstant(IV, &I, NonOverdefVal->getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 }
857 }
Chris Lattner6367c3f2009-11-02 05:55:40 +0000858 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859
860
Chris Lattner6367c3f2009-11-02 05:55:40 +0000861 // If both operands are PHI nodes, it is possible that this instruction has
862 // a constant value, despite the fact that the PHI node doesn't. Check for
863 // this condition now.
864 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
865 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
866 if (PN1->getParent() == PN2->getParent()) {
867 // Since the two PHI nodes are in the same basic block, they must have
868 // entries for the same predecessors. Walk the predecessor list, and
869 // if all of the incoming values are constants, and the result of
870 // evaluating this expression with all incoming value pairs is the
871 // same, then this expression is a constant even though the PHI node
872 // is not a constant!
873 LatticeVal Result;
874 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
875 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
876 BasicBlock *InBlock = PN1->getIncomingBlock(i);
877 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878
Chris Lattner6367c3f2009-11-02 05:55:40 +0000879 if (In1.isOverdefined() || In2.isOverdefined()) {
880 Result.markOverdefined();
881 break; // Cannot fold this operation over the PHI nodes!
882 }
883
884 if (In1.isConstant() && In2.isConstant()) {
885 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
886 In2.getConstant());
887 if (Result.isUndefined())
888 Result.markConstant(V);
889 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000891 break;
Chris Lattnerb52f7002009-11-02 03:03:42 +0000892 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 }
894 }
895
Chris Lattner6367c3f2009-11-02 05:55:40 +0000896 // If we found a constant value here, then we know the instruction is
897 // constant despite the fact that the PHI nodes are overdefined.
898 if (Result.isConstant()) {
899 markConstant(IV, &I, Result.getConstant());
900 // Remember that this instruction is virtually using the PHI node
901 // operands.
902 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
903 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
904 return;
905 }
906
907 if (Result.isUndefined())
908 return;
909
910 // Okay, this really is overdefined now. Since we might have
911 // speculatively thought that this was not overdefined before, and
912 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
913 // make sure to clean out any entries that we put there, for
914 // efficiency.
915 UsersOfOverdefinedPHIs.erase(PN1);
916 UsersOfOverdefinedPHIs.erase(PN2);
917 }
918
919 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920}
921
Chris Lattnerc8798002009-11-02 02:33:50 +0000922// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923void SCCPSolver::visitCmpInst(CmpInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +0000924 LatticeVal V1State = getValueState(I.getOperand(0));
925 LatticeVal V2State = getValueState(I.getOperand(1));
926
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 LatticeVal &IV = ValueState[&I];
928 if (IV.isOverdefined()) return;
929
Chris Lattner6367c3f2009-11-02 05:55:40 +0000930 if (V1State.isConstant() && V2State.isConstant())
931 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
932 V1State.getConstant(),
933 V2State.getConstant()));
934
935 // If operands are still undefined, wait for it to resolve.
936 if (!V1State.isOverdefined() && !V2State.isOverdefined())
937 return;
938
939 // If something is overdefined, use some tricks to avoid ending up and over
940 // defined if we can.
941
942 // If both operands are PHI nodes, it is possible that this instruction has
943 // a constant value, despite the fact that the PHI node doesn't. Check for
944 // this condition now.
945 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
946 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
947 if (PN1->getParent() == PN2->getParent()) {
948 // Since the two PHI nodes are in the same basic block, they must have
949 // entries for the same predecessors. Walk the predecessor list, and
950 // if all of the incoming values are constants, and the result of
951 // evaluating this expression with all incoming value pairs is the
952 // same, then this expression is a constant even though the PHI node
953 // is not a constant!
954 LatticeVal Result;
955 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
956 LatticeVal In1 = getValueState(PN1->getIncomingValue(i));
957 BasicBlock *InBlock = PN1->getIncomingBlock(i);
958 LatticeVal In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959
Chris Lattner6367c3f2009-11-02 05:55:40 +0000960 if (In1.isOverdefined() || In2.isOverdefined()) {
961 Result.markOverdefined();
962 break; // Cannot fold this operation over the PHI nodes!
963 }
964
965 if (In1.isConstant() && In2.isConstant()) {
966 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
967 In1.getConstant(),
968 In2.getConstant());
969 if (Result.isUndefined())
970 Result.markConstant(V);
971 else if (Result.isConstant() && Result.getConstant() != V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 Result.markOverdefined();
Chris Lattner6367c3f2009-11-02 05:55:40 +0000973 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 }
975 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 }
977
Chris Lattner6367c3f2009-11-02 05:55:40 +0000978 // If we found a constant value here, then we know the instruction is
979 // constant despite the fact that the PHI nodes are overdefined.
980 if (Result.isConstant()) {
981 markConstant(&I, Result.getConstant());
982 // Remember that this instruction is virtually using the PHI node
983 // operands.
984 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
985 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
986 return;
987 }
988
989 if (Result.isUndefined())
990 return;
991
992 // Okay, this really is overdefined now. Since we might have
993 // speculatively thought that this was not overdefined before, and
994 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
995 // make sure to clean out any entries that we put there, for
996 // efficiency.
997 UsersOfOverdefinedPHIs.erase(PN1);
998 UsersOfOverdefinedPHIs.erase(PN2);
999 }
1000
1001 markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002}
1003
1004void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1005 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001006 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001007
1008#if 0
1009 LatticeVal &ValState = getValueState(I.getOperand(0));
1010 LatticeVal &IdxState = getValueState(I.getOperand(1));
1011
1012 if (ValState.isOverdefined() || IdxState.isOverdefined())
1013 markOverdefined(&I);
1014 else if(ValState.isConstant() && IdxState.isConstant())
1015 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1016 IdxState.getConstant()));
1017#endif
1018}
1019
1020void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1021 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001022 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001023#if 0
1024 LatticeVal &ValState = getValueState(I.getOperand(0));
1025 LatticeVal &EltState = getValueState(I.getOperand(1));
1026 LatticeVal &IdxState = getValueState(I.getOperand(2));
1027
1028 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1029 IdxState.isOverdefined())
1030 markOverdefined(&I);
1031 else if(ValState.isConstant() && EltState.isConstant() &&
1032 IdxState.isConstant())
1033 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1034 EltState.getConstant(),
1035 IdxState.getConstant()));
1036 else if (ValState.isUndefined() && EltState.isConstant() &&
1037 IdxState.isConstant())
1038 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1039 EltState.getConstant(),
1040 IdxState.getConstant()));
1041#endif
1042}
1043
1044void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1045 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001046 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047#if 0
1048 LatticeVal &V1State = getValueState(I.getOperand(0));
1049 LatticeVal &V2State = getValueState(I.getOperand(1));
1050 LatticeVal &MaskState = getValueState(I.getOperand(2));
1051
1052 if (MaskState.isUndefined() ||
1053 (V1State.isUndefined() && V2State.isUndefined()))
1054 return; // Undefined output if mask or both inputs undefined.
1055
1056 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1057 MaskState.isOverdefined()) {
1058 markOverdefined(&I);
1059 } else {
1060 // A mix of constant/undef inputs.
1061 Constant *V1 = V1State.isConstant() ?
1062 V1State.getConstant() : UndefValue::get(I.getType());
1063 Constant *V2 = V2State.isConstant() ?
1064 V2State.getConstant() : UndefValue::get(I.getType());
1065 Constant *Mask = MaskState.isConstant() ?
1066 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1067 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1068 }
1069#endif
1070}
1071
Chris Lattnerc8798002009-11-02 02:33:50 +00001072// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073// can turn this into a getelementptr ConstantExpr.
1074//
1075void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1076 LatticeVal &IV = ValueState[&I];
1077 if (IV.isOverdefined()) return;
1078
1079 SmallVector<Constant*, 8> Operands;
1080 Operands.reserve(I.getNumOperands());
1081
1082 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001083 LatticeVal State = getValueState(I.getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001085 return; // Operands are not resolved yet.
1086
Chris Lattnerb52f7002009-11-02 03:03:42 +00001087 if (State.isOverdefined())
1088 return markOverdefined(IV, &I);
1089
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 assert(State.isConstant() && "Unknown state!");
1091 Operands.push_back(State.getConstant());
1092 }
1093
1094 Constant *Ptr = Operands[0];
Chris Lattner6367c3f2009-11-02 05:55:40 +00001095 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0]+1,
1096 Operands.size()-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097}
1098
Chris Lattner6367c3f2009-11-02 05:55:40 +00001099void SCCPSolver::visitStoreInst(StoreInst &SI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1101 return;
Chris Lattner6367c3f2009-11-02 05:55:40 +00001102
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1104 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1105 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1106
Chris Lattner6367c3f2009-11-02 05:55:40 +00001107 // Get the value we are storing into the global, then merge it.
1108 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109 if (I->second.isOverdefined())
1110 TrackedGlobals.erase(I); // No need to keep tracking this!
1111}
1112
1113
1114// Handle load instructions. If the operand is a constant pointer to a constant
1115// global, we can replace the load with the loaded constant value!
1116void SCCPSolver::visitLoadInst(LoadInst &I) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001117 LatticeVal PtrVal = getValueState(I.getOperand(0));
Chris Lattner0148bb22009-11-02 06:06:14 +00001118 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
Chris Lattner6367c3f2009-11-02 05:55:40 +00001119
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 LatticeVal &IV = ValueState[&I];
1121 if (IV.isOverdefined()) return;
1122
Chris Lattner6367c3f2009-11-02 05:55:40 +00001123 if (!PtrVal.isConstant() || I.isVolatile())
1124 return markOverdefined(IV, &I);
1125
Chris Lattner0148bb22009-11-02 06:06:14 +00001126 Constant *Ptr = PtrVal.getConstant();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127
Chris Lattner6367c3f2009-11-02 05:55:40 +00001128 // load null -> null
1129 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1130 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1131
1132 // Transform load (constant global) into the value loaded.
1133 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001134 if (!TrackedGlobals.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001135 // If we are tracking this global, merge in the known value for it.
1136 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1137 TrackedGlobals.find(GV);
1138 if (It != TrackedGlobals.end()) {
1139 mergeInValue(IV, &I, It->second);
1140 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 }
1142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 }
1144
Chris Lattner0148bb22009-11-02 06:06:14 +00001145 // Transform load from a constant into a constant if possible.
1146 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1147 return markConstant(IV, &I, C);
Chris Lattner6367c3f2009-11-02 05:55:40 +00001148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149 // Otherwise we cannot say for certain what value this load will produce.
1150 // Bail out.
1151 markOverdefined(IV, &I);
1152}
1153
1154void SCCPSolver::visitCallSite(CallSite CS) {
1155 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001157
1158 // The common case is that we aren't tracking the callee, either because we
1159 // are not doing interprocedural analysis or the callee is indirect, or is
1160 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001161 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001162CallOverdefined:
1163 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001164 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001165
1166 // Otherwise, if we have a single return value case, and if the function is
1167 // a declaration, maybe we can constant fold it.
1168 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1169 canConstantFoldCallTo(F)) {
1170
1171 SmallVector<Constant*, 8> Operands;
1172 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1173 AI != E; ++AI) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001174 LatticeVal State = getValueState(*AI);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001175
Chris Lattnercd73be02008-04-23 05:38:20 +00001176 if (State.isUndefined())
1177 return; // Operands are not resolved yet.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001178 if (State.isOverdefined())
1179 return markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001180 assert(State.isConstant() && "Unknown state!");
1181 Operands.push_back(State.getConstant());
1182 }
1183
1184 // If we can constant fold this, mark the result of the call as a
1185 // constant.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001186 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1187 return markConstant(I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001189
1190 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001191 return markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001192 }
1193
Chris Lattnercd73be02008-04-23 05:38:20 +00001194 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001195 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1196 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001197 // If so, propagate the return value of the callee into this call result.
1198 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001199 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001200 // Check to see if we're tracking this callee, if not, handle it in the
1201 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001202 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1203 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001204 if (TMRVI == TrackedMultipleRetVals.end())
1205 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001206
1207 // Need to mark as overdefined, otherwise it stays undefined which
1208 // creates extractvalue undef, <idx>
1209 markOverdefined(I);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001210
Chris Lattnercd73be02008-04-23 05:38:20 +00001211 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001212 // into this call site. We do this by walking all the uses. Single-index
1213 // ExtractValueInst uses can be tracked; anything more complicated is
1214 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001215 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1216 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001217 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1218 if (EVI->getNumIndices() == 1) {
1219 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001220 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001221 continue;
1222 }
1223 }
1224 // The aggregate value is used in a way not handled here. Assume nothing.
1225 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001226 }
Dan Gohman856193b2008-06-20 01:15:44 +00001227 } else {
1228 // Otherwise we're not tracking this callee, so handle it in the
1229 // common path above.
1230 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001231 }
1232
1233 // Finally, if this is the first call to the function hit, mark its entry
1234 // block executable.
Chris Lattnera5ffa7c2009-11-02 06:11:23 +00001235 MarkBlockExecutable(F->begin());
Chris Lattnercd73be02008-04-23 05:38:20 +00001236
1237 // Propagate information from this call site into the callee.
1238 CallSite::arg_iterator CAI = CS.arg_begin();
1239 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1240 AI != E; ++AI, ++CAI) {
Edwin Török129b2d12009-09-24 18:33:42 +00001241 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001242 markOverdefined(AI);
Edwin Törökd5435372009-09-24 09:47:18 +00001243 continue;
1244 }
Chris Lattner6367c3f2009-11-02 05:55:40 +00001245
1246 mergeInValue(AI, getValueState(*CAI));
Chris Lattnercd73be02008-04-23 05:38:20 +00001247 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248}
1249
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250void SCCPSolver::Solve() {
1251 // Process the work lists until they are empty!
1252 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1253 !OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001254 // Process the overdefined instruction's work list first, which drives other
1255 // things to overdefined more quickly.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001256 while (!OverdefinedInstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001257 Value *I = OverdefinedInstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258
Dan Gohmandff8d172009-08-17 15:25:05 +00001259 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260
1261 // "I" got into the work list because it either made the transition from
1262 // bottom to constant
1263 //
1264 // Anything on this worklist that is overdefined need not be visited
1265 // since all of its users will have already been marked as overdefined
Chris Lattnerc8798002009-11-02 02:33:50 +00001266 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 //
1268 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1269 UI != E; ++UI)
1270 OperandChangedState(*UI);
1271 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001272
1273 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 while (!InstWorkList.empty()) {
Chris Lattner6367c3f2009-11-02 05:55:40 +00001275 Value *I = InstWorkList.pop_back_val();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276
Dan Gohmandff8d172009-08-17 15:25:05 +00001277 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278
Chris Lattner6367c3f2009-11-02 05:55:40 +00001279 // "I" got into the work list because it made the transition from undef to
1280 // constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 //
1282 // Anything on this worklist that is overdefined need not be visited
1283 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001284 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 //
1286 if (!getValueState(I).isOverdefined())
1287 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1288 UI != E; ++UI)
1289 OperandChangedState(*UI);
1290 }
1291
Chris Lattnerc8798002009-11-02 02:33:50 +00001292 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 while (!BBWorkList.empty()) {
1294 BasicBlock *BB = BBWorkList.back();
1295 BBWorkList.pop_back();
1296
Dan Gohmandff8d172009-08-17 15:25:05 +00001297 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298
1299 // Notify all instructions in this basic block that they are newly
1300 // executable.
1301 visit(BB);
1302 }
1303 }
1304}
1305
1306/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1307/// that branches on undef values cannot reach any of their successors.
1308/// However, this is not a safe assumption. After we solve dataflow, this
1309/// method should be use to handle this. If this returns true, the solver
1310/// should be rerun.
1311///
1312/// This method handles this by finding an unresolved branch and marking it one
1313/// of the edges from the block as being feasible, even though the condition
1314/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1315/// CFG and only slightly pessimizes the analysis results (by marking one,
1316/// potentially infeasible, edge feasible). This cannot usefully modify the
1317/// constraints on the condition of the branch, as that would impact other users
1318/// of the value.
1319///
1320/// This scan also checks for values that use undefs, whose results are actually
1321/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1322/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1323/// even if X isn't defined.
1324bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1325 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1326 if (!BBExecutable.count(BB))
1327 continue;
1328
1329 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1330 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001331 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332
1333 LatticeVal &LV = getValueState(I);
1334 if (!LV.isUndefined()) continue;
1335
1336 // Get the lattice values of the first two operands for use below.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001337 LatticeVal Op0LV = getValueState(I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 LatticeVal Op1LV;
1339 if (I->getNumOperands() == 2) {
1340 // If this is a two-operand instruction, and if both operands are
1341 // undefs, the result stays undef.
1342 Op1LV = getValueState(I->getOperand(1));
1343 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1344 continue;
1345 }
1346
1347 // If this is an instructions whose result is defined even if the input is
1348 // not fully defined, propagate the information.
1349 const Type *ITy = I->getType();
1350 switch (I->getOpcode()) {
1351 default: break; // Leave the instruction as an undef.
1352 case Instruction::ZExt:
1353 // After a zero extend, we know the top part is zero. SExt doesn't have
1354 // to be handled here, because we don't know whether the top part is 1's
1355 // or 0's.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001356 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 return true;
1358 case Instruction::Mul:
1359 case Instruction::And:
1360 // undef * X -> 0. X could be zero.
1361 // undef & X -> 0. X could be zero.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001362 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 return true;
1364
1365 case Instruction::Or:
1366 // undef | X -> -1. X could be -1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001367 markForcedConstant(I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 return true;
1369
1370 case Instruction::SDiv:
1371 case Instruction::UDiv:
1372 case Instruction::SRem:
1373 case Instruction::URem:
1374 // X / undef -> undef. No change.
1375 // X % undef -> undef. No change.
1376 if (Op1LV.isUndefined()) break;
1377
1378 // undef / X -> 0. X could be maxint.
1379 // undef % X -> 0. X could be 1.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001380 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 return true;
1382
1383 case Instruction::AShr:
1384 // undef >>s X -> undef. No change.
1385 if (Op0LV.isUndefined()) break;
1386
1387 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1388 if (Op0LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001389 markForcedConstant(I, Op0LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001391 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 return true;
1393 case Instruction::LShr:
1394 case Instruction::Shl:
1395 // undef >> X -> undef. No change.
1396 // undef << X -> undef. No change.
1397 if (Op0LV.isUndefined()) break;
1398
1399 // X >> undef -> 0. X could be 0.
1400 // X << undef -> 0. X could be 0.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001401 markForcedConstant(I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 return true;
1403 case Instruction::Select:
1404 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1405 if (Op0LV.isUndefined()) {
1406 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1407 Op1LV = getValueState(I->getOperand(2));
1408 } else if (Op1LV.isUndefined()) {
1409 // c ? undef : undef -> undef. No change.
1410 Op1LV = getValueState(I->getOperand(2));
1411 if (Op1LV.isUndefined())
1412 break;
1413 // Otherwise, c ? undef : x -> x.
1414 } else {
1415 // Leave Op1LV as Operand(1)'s LatticeValue.
1416 }
1417
1418 if (Op1LV.isConstant())
Chris Lattner6367c3f2009-11-02 05:55:40 +00001419 markForcedConstant(I, Op1LV.getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420 else
Chris Lattner6367c3f2009-11-02 05:55:40 +00001421 markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001423 case Instruction::Call:
1424 // If a call has an undef result, it is because it is constant foldable
1425 // but one of the inputs was undef. Just force the result to
1426 // overdefined.
Chris Lattner6367c3f2009-11-02 05:55:40 +00001427 markOverdefined(I);
Chris Lattner9110ac92008-05-24 03:59:33 +00001428 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 }
1430 }
1431
1432 TerminatorInst *TI = BB->getTerminator();
1433 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1434 if (!BI->isConditional()) continue;
1435 if (!getValueState(BI->getCondition()).isUndefined())
1436 continue;
1437 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001438 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001439 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 if (!getValueState(SI->getCondition()).isUndefined())
1441 continue;
1442 } else {
1443 continue;
1444 }
1445
Chris Lattner6186e8c2008-01-28 00:32:30 +00001446 // If the edge to the second successor isn't thought to be feasible yet,
1447 // mark it so now. We pick the second one so that this goes to some
1448 // enumerated value in a switch instead of going to the default destination.
1449 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 continue;
1451
1452 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1453 // and return. This will make other blocks reachable, which will allow new
1454 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001455 markEdgeExecutable(BB, TI->getSuccessor(1));
1456
1457 // This must be a conditional branch of switch on undef. At this point,
1458 // force the old terminator to branch to the first successor. This is
1459 // required because we are now influencing the dataflow of the function with
1460 // the assumption that this edge is taken. If we leave the branch condition
1461 // as undef, then further analysis could think the undef went another way
1462 // leading to an inconsistent set of conclusions.
1463 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001464 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001465 } else {
1466 SwitchInst *SI = cast<SwitchInst>(TI);
1467 SI->setCondition(SI->getCaseValue(1));
1468 }
1469
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 return true;
1471 }
1472
1473 return false;
1474}
1475
1476
1477namespace {
1478 //===--------------------------------------------------------------------===//
1479 //
1480 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1481 /// Sparse Conditional Constant Propagator.
1482 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001483 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001485 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001486
1487 // runOnFunction - Run the Sparse Conditional Constant Propagation
1488 // algorithm, and return true if the function was modified.
1489 //
1490 bool runOnFunction(Function &F);
1491
1492 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1493 AU.setPreservesCFG();
1494 }
1495 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496} // end anonymous namespace
1497
Dan Gohman089efff2008-05-13 00:00:25 +00001498char SCCP::ID = 0;
1499static RegisterPass<SCCP>
1500X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501
Chris Lattnerc8798002009-11-02 02:33:50 +00001502// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503FunctionPass *llvm::createSCCPPass() {
1504 return new SCCP();
1505}
1506
Chris Lattner14513dc2009-11-02 02:47:51 +00001507static void DeleteInstructionInBlock(BasicBlock *BB) {
1508 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1509 ++NumDeadBlocks;
1510
1511 // Delete the instructions backwards, as it has a reduced likelihood of
1512 // having to update as many def-use and use-def chains.
1513 while (!isa<TerminatorInst>(BB->begin())) {
1514 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1515
1516 if (!I->use_empty())
1517 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1518 BB->getInstList().erase(I);
1519 ++NumInstRemoved;
1520 }
1521}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522
1523// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1524// and return true if the function was modified.
1525//
1526bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001527 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Chris Lattner0148bb22009-11-02 06:06:14 +00001528 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529
1530 // Mark the first block of the function as being executable.
1531 Solver.MarkBlockExecutable(F.begin());
1532
1533 // Mark all arguments to the function as being overdefined.
1534 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1535 Solver.markOverdefined(AI);
1536
1537 // Solve for constants.
1538 bool ResolvedUndefs = true;
1539 while (ResolvedUndefs) {
1540 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001541 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1543 }
1544
1545 bool MadeChanges = false;
1546
1547 // If we decided that there are basic blocks that are dead in this function,
1548 // delete their contents now. Note that we cannot actually delete the blocks,
1549 // as we cannot modify the CFG of the function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550
Chris Lattner14513dc2009-11-02 02:47:51 +00001551 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001552 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001553 DeleteInstructionInBlock(BB);
1554 MadeChanges = true;
1555 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001557
1558 // Iterate over all of the instructions in a function, replacing them with
1559 // constants if we have found them to be of constant values.
1560 //
1561 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1562 Instruction *Inst = BI++;
1563 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1564 continue;
1565
Chris Lattnerc9edab82009-11-02 02:54:24 +00001566 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1567 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001568 continue;
1569
1570 Constant *Const = IV.isConstant()
1571 ? IV.getConstant() : UndefValue::get(Inst->getType());
1572 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1573
1574 // Replaces all of the uses of a variable with uses of the constant.
1575 Inst->replaceAllUsesWith(Const);
1576
1577 // Delete the instruction.
1578 Inst->eraseFromParent();
1579
1580 // Hey, we just changed something!
1581 MadeChanges = true;
1582 ++NumInstRemoved;
1583 }
1584 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585
1586 return MadeChanges;
1587}
1588
1589namespace {
1590 //===--------------------------------------------------------------------===//
1591 //
1592 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1593 /// Constant Propagation.
1594 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001595 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001597 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598 bool runOnModule(Module &M);
1599 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001600} // end anonymous namespace
1601
Dan Gohman089efff2008-05-13 00:00:25 +00001602char IPSCCP::ID = 0;
1603static RegisterPass<IPSCCP>
1604Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1605
Chris Lattnerc8798002009-11-02 02:33:50 +00001606// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607ModulePass *llvm::createIPSCCPPass() {
1608 return new IPSCCP();
1609}
1610
1611
1612static bool AddressIsTaken(GlobalValue *GV) {
1613 // Delete any dead constantexpr klingons.
1614 GV->removeDeadConstantUsers();
1615
1616 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1617 UI != E; ++UI)
1618 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1619 if (SI->getOperand(0) == GV || SI->isVolatile())
1620 return true; // Storing addr of GV.
1621 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1622 // Make sure we are calling the function, not passing the address.
Chris Lattner2f487502009-11-01 06:11:53 +00001623 if (UI.getOperandNo() != 0)
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001624 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1626 if (LI->isVolatile())
1627 return true;
Chris Lattner2f487502009-11-01 06:11:53 +00001628 } else if (isa<BlockAddress>(*UI)) {
1629 // blockaddress doesn't take the address of the function, it takes addr
1630 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631 } else {
1632 return true;
1633 }
1634 return false;
1635}
1636
1637bool IPSCCP::runOnModule(Module &M) {
Chris Lattner0148bb22009-11-02 06:06:14 +00001638 SCCPSolver Solver(getAnalysisIfAvailable<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639
1640 // Loop over all functions, marking arguments to those with their addresses
1641 // taken or that are external as overdefined.
1642 //
1643 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001644 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 if (!F->isDeclaration())
1646 Solver.MarkBlockExecutable(F->begin());
1647 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1648 AI != E; ++AI)
1649 Solver.markOverdefined(AI);
1650 } else {
1651 Solver.AddTrackedFunction(F);
1652 }
1653
1654 // Loop over global variables. We inform the solver about any internal global
1655 // variables that do not have their 'addresses taken'. If they don't have
1656 // their addresses taken, we can propagate constants through them.
1657 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1658 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001659 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 Solver.TrackValueOfGlobalVariable(G);
1661
1662 // Solve for constants.
1663 bool ResolvedUndefs = true;
1664 while (ResolvedUndefs) {
1665 Solver.Solve();
1666
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001667 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668 ResolvedUndefs = false;
1669 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1670 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1671 }
1672
1673 bool MadeChanges = false;
1674
1675 // Iterate over all of the instructions in the module, replacing them with
1676 // constants if we have found them to be of constant values.
1677 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001678 SmallVector<BasicBlock*, 512> BlocksToErase;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679
1680 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
Chris Lattner84388f12009-11-02 03:25:55 +00001681 if (Solver.isBlockExecutable(F->begin())) {
1682 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1683 AI != E; ++AI) {
1684 if (AI->use_empty()) continue;
1685
1686 LatticeVal IV = Solver.getLatticeValueFor(AI);
1687 if (IV.isOverdefined()) continue;
1688
1689 Constant *CST = IV.isConstant() ?
1690 IV.getConstant() : UndefValue::get(AI->getType());
1691 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1692
1693 // Replaces all of the uses of a variable with uses of the
1694 // constant.
1695 AI->replaceAllUsesWith(CST);
1696 ++IPNumArgsElimed;
1697 }
Chris Lattnerc9edab82009-11-02 02:54:24 +00001698 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001699
Chris Lattner14513dc2009-11-02 02:47:51 +00001700 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001701 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001702 DeleteInstructionInBlock(BB);
1703 MadeChanges = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1707 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001708 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001709 TI->getSuccessor(i)->removePredecessor(BB);
1710 }
1711 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001712 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner14513dc2009-11-02 02:47:51 +00001713 TI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714
1715 if (&*BB != &F->front())
1716 BlocksToErase.push_back(BB);
1717 else
Owen Anderson35b47072009-08-13 21:58:54 +00001718 new UnreachableInst(M.getContext(), BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001719 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001721
1722 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1723 Instruction *Inst = BI++;
1724 if (Inst->getType()->isVoidTy())
1725 continue;
1726
Chris Lattnerc9edab82009-11-02 02:54:24 +00001727 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1728 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001729 continue;
1730
1731 Constant *Const = IV.isConstant()
1732 ? IV.getConstant() : UndefValue::get(Inst->getType());
1733 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1734
1735 // Replaces all of the uses of a variable with uses of the
1736 // constant.
1737 Inst->replaceAllUsesWith(Const);
1738
1739 // Delete the instruction.
1740 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1741 Inst->eraseFromParent();
1742
1743 // Hey, we just changed something!
1744 MadeChanges = true;
1745 ++IPNumInstRemoved;
1746 }
1747 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001748
1749 // Now that all instructions in the function are constant folded, erase dead
1750 // blocks, because we can now use ConstantFoldTerminator to get rid of
1751 // in-edges.
1752 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1753 // If there are any PHI nodes in this successor, drop entries for BB now.
1754 BasicBlock *DeadBB = BlocksToErase[i];
1755 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001756 Instruction *I = cast<Instruction>(DeadBB->use_back());
1757 bool Folded = ConstantFoldTerminator(I->getParent());
1758 if (!Folded) {
1759 // The constant folder may not have been able to fold the terminator
1760 // if this is a branch or switch on undef. Fold it manually as a
1761 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001762#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1764 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1765 "Branch should be foldable!");
1766 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1767 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1768 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001769 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770 }
Devang Patele92c16d2008-11-21 01:52:59 +00001771#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772
1773 // Make this an uncond branch to the first successor.
1774 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001775 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776
1777 // Remove entries in successor phi nodes to remove edges.
1778 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1779 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1780
1781 // Remove the old terminator.
1782 TI->eraseFromParent();
1783 }
1784 }
1785
1786 // Finally, delete the basic block.
1787 F->getBasicBlockList().erase(DeadBB);
1788 }
1789 BlocksToErase.clear();
1790 }
1791
1792 // If we inferred constant or undef return values for a function, we replaced
1793 // all call uses with the inferred value. This means we don't need to bother
1794 // actually returning anything from the function. Replace all return
1795 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001796 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001797 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1799 E = RV.end(); I != E; ++I)
1800 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001801 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 Function *F = I->first;
1803 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1804 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1805 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001806 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807 }
1808
1809 // If we infered constant or undef values for globals variables, we can delete
1810 // the global and any stores that remain to it.
1811 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1812 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1813 E = TG.end(); I != E; ++I) {
1814 GlobalVariable *GV = I->first;
1815 assert(!I->second.isOverdefined() &&
1816 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001817 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001818 while (!GV->use_empty()) {
1819 StoreInst *SI = cast<StoreInst>(GV->use_back());
1820 SI->eraseFromParent();
1821 }
1822 M.getGlobalList().erase(GV);
1823 ++IPNumGlobalConst;
1824 }
1825
1826 return MadeChanges;
1827}