blob: 016d018d73bac6f6f2392bfba5553cdac824e0cf [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"
31#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000035#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000037#include "llvm/ADT/DenseSet.h"
Chris Lattner1eb405b2009-11-02 02:20:32 +000038#include "llvm/ADT/PointerIntPair.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
42#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000043#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044using namespace llvm;
45
46STATISTIC(NumInstRemoved, "Number of instructions removed");
47STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
48
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000049STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
51STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
52
53namespace {
54/// LatticeVal class - This class represents the different lattice values that
55/// an LLVM value may occupy. It is a simple class with value semantics.
56///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000057class LatticeVal {
Chris Lattner1eb405b2009-11-02 02:20:32 +000058 enum LatticeValueTy {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 /// undefined - This LLVM Value has no known value yet.
60 undefined,
61
62 /// constant - This LLVM Value has a specific constant value.
63 constant,
64
65 /// forcedconstant - This LLVM Value was thought to be undef until
66 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
67 /// with another (different) constant, it goes to overdefined, instead of
68 /// asserting.
69 forcedconstant,
70
71 /// overdefined - This instruction is not known to be constant, and we know
72 /// it has a value.
73 overdefined
Chris Lattner1eb405b2009-11-02 02:20:32 +000074 };
75
76 /// Val: This stores the current lattice value along with the Constant* for
77 /// the constant if this is a 'constant' or 'forcedconstant' value.
78 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079
Chris Lattner1eb405b2009-11-02 02:20:32 +000080 LatticeValueTy getLatticeValue() const {
81 return Val.getInt();
82 }
83
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084public:
Chris Lattnerb52f7002009-11-02 03:03:42 +000085 LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
Chris Lattnerb52f7002009-11-02 03:03:42 +000087 bool isUndefined() const { return getLatticeValue() == undefined; }
88 bool isConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000089 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
90 }
Chris Lattnerb52f7002009-11-02 03:03:42 +000091 bool isOverdefined() const { return getLatticeValue() == overdefined; }
Chris Lattner1eb405b2009-11-02 02:20:32 +000092
Chris Lattnerb52f7002009-11-02 03:03:42 +000093 Constant *getConstant() const {
Chris Lattner1eb405b2009-11-02 02:20:32 +000094 assert(isConstant() && "Cannot get the constant of a non-constant!");
95 return Val.getPointer();
96 }
97
98 /// markOverdefined - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +000099 bool markOverdefined() {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000100 if (isOverdefined())
101 return false;
102
103 Val.setInt(overdefined);
104 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105 }
106
Chris Lattner1eb405b2009-11-02 02:20:32 +0000107 /// markConstant - Return true if this is a change in status.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000108 bool markConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000109 if (isConstant()) {
110 assert(getConstant() == V && "Marking constant with different value");
111 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000112 }
Chris Lattner1eb405b2009-11-02 02:20:32 +0000113
114 if (isUndefined()) {
115 Val.setInt(constant);
116 assert(V && "Marking constant with NULL");
117 Val.setPointer(V);
118 } else {
119 assert(getLatticeValue() == forcedconstant &&
120 "Cannot move from overdefined to constant!");
121 // Stay at forcedconstant if the constant is the same.
122 if (V == getConstant()) return false;
123
124 // Otherwise, we go to overdefined. Assumptions made based on the
125 // forced value are possibly wrong. Assuming this is another constant
126 // could expose a contradiction.
127 Val.setInt(overdefined);
128 }
129 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 }
131
Chris Lattner220571c2009-11-02 03:21:36 +0000132 /// getConstantInt - If this is a constant with a ConstantInt value, return it
133 /// otherwise return null.
134 ConstantInt *getConstantInt() const {
135 if (isConstant())
136 return dyn_cast<ConstantInt>(getConstant());
137 return 0;
138 }
139
Chris Lattnerb52f7002009-11-02 03:03:42 +0000140 void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000141 assert(isUndefined() && "Can't force a defined value!");
142 Val.setInt(forcedconstant);
143 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145};
Chris Lattner14513dc2009-11-02 02:47:51 +0000146} // end anonymous namespace.
147
148
149namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151//===----------------------------------------------------------------------===//
152//
153/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
154/// Constant Propagation.
155///
156class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000157 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000158 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159
160 /// GlobalValue - If we are tracking any values for the contents of a global
161 /// variable, we keep a mapping from the constant accessor to the element of
162 /// the global, to the currently known value. If the value becomes
163 /// overdefined, it's entry is simply removed from this map.
164 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
165
Devang Pateladd320d2008-03-11 05:46:42 +0000166 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 /// value out of a function, it will have an entry in this map, indicating
168 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000169 DenseMap<Function*, LatticeVal> TrackedRetVals;
170
171 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
172 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000173 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
Chris Lattnerb52f7002009-11-02 03:03:42 +0000175 /// The reason for two worklists is that overdefined is the lowest state
176 /// on the lattice, and moving things to overdefined as fast as possible
177 /// makes SCCP converge much faster.
178 ///
179 /// By having a separate worklist, we accomplish this because everything
180 /// possibly overdefined will become overdefined at the soonest possible
181 /// point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000182 SmallVector<Value*, 64> OverdefinedInstWorkList;
183 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184
185
Chris Lattnerd3123a72008-08-23 23:36:38 +0000186 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187
188 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
189 /// overdefined, despite the fact that the PHI node is overdefined.
190 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
191
192 /// KnownFeasibleEdges - Entries in this set are edges which have already had
193 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000194 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
195 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196public:
197
198 /// MarkBlockExecutable - This method can be used by clients to mark all of
199 /// the blocks that are known to be intrinsically live in the processed unit.
200 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000201 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 BBExecutable.insert(BB); // Basic block is executable!
203 BBWorkList.push_back(BB); // Add the block to the work list!
204 }
205
206 /// TrackValueOfGlobalVariable - Clients can use this method to
207 /// inform the SCCPSolver that it should track loads and stores to the
208 /// specified global variable if it can. This is only legal to call if
209 /// performing Interprocedural SCCP.
210 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
211 const Type *ElTy = GV->getType()->getElementType();
212 if (ElTy->isFirstClassType()) {
213 LatticeVal &IV = TrackedGlobals[GV];
214 if (!isa<UndefValue>(GV->getInitializer()))
215 IV.markConstant(GV->getInitializer());
216 }
217 }
218
219 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
220 /// and out of the specified function (which cannot have its address taken),
221 /// this method must be called.
222 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000223 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000225 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
226 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000227 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
228 LatticeVal()));
229 } else
230 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 }
232
233 /// Solve - Solve for constants and executable blocks.
234 ///
235 void Solve();
236
237 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
238 /// that branches on undef values cannot reach any of their successors.
239 /// However, this is not a safe assumption. After we solve dataflow, this
240 /// method should be use to handle this. If this returns true, the solver
241 /// should be rerun.
242 bool ResolvedUndefsIn(Function &F);
243
Chris Lattner317e6b62008-08-23 23:39:31 +0000244 bool isBlockExecutable(BasicBlock *BB) const {
245 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 }
247
Chris Lattnerc9edab82009-11-02 02:54:24 +0000248 LatticeVal getLatticeValueFor(Value *V) const {
249 std::map<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
250 assert(I != ValueState.end() && "V is not in valuemap!");
251 return I->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 }
253
Devang Pateladd320d2008-03-11 05:46:42 +0000254 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000256 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
257 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 }
259
260 /// getTrackedGlobals - Get and return the set of inferred initializers for
261 /// global variables.
262 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
263 return TrackedGlobals;
264 }
265
Chris Lattner220571c2009-11-02 03:21:36 +0000266 void markOverdefined(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 markOverdefined(ValueState[V], V);
268 }
269
270private:
271 // markConstant - Make a value be marked as "constant". If the value
272 // is not already a constant, add it to the instruction work list so that
273 // the users of the instruction are updated later.
274 //
Chris Lattnerb52f7002009-11-02 03:03:42 +0000275 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
276 if (!IV.markConstant(C)) return;
277 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
278 InstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 }
280
Chris Lattnerb52f7002009-11-02 03:03:42 +0000281 void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 IV.markForcedConstant(C);
Dan Gohmandff8d172009-08-17 15:25:05 +0000283 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 InstWorkList.push_back(V);
285 }
286
Chris Lattnerb52f7002009-11-02 03:03:42 +0000287 void markConstant(Value *V, Constant *C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 markConstant(ValueState[V], V, C);
289 }
290
291 // markOverdefined - Make a value be marked as "overdefined". If the
292 // value is not already overdefined, add it to the overdefined instruction
293 // work list so that the users of the instruction are updated later.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000294 void markOverdefined(LatticeVal &IV, Value *V) {
295 if (!IV.markOverdefined()) return;
296
297 DEBUG(errs() << "markOverdefined: ";
298 if (Function *F = dyn_cast<Function>(V))
299 errs() << "Function '" << F->getName() << "'\n";
300 else
301 errs() << *V << '\n');
302 // Only instructions go on the work list
303 OverdefinedInstWorkList.push_back(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 }
305
Chris Lattnerb52f7002009-11-02 03:03:42 +0000306 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 if (IV.isOverdefined() || MergeWithV.isUndefined())
308 return; // Noop.
309 if (MergeWithV.isOverdefined())
310 markOverdefined(IV, V);
311 else if (IV.isUndefined())
312 markConstant(IV, V, MergeWithV.getConstant());
313 else if (IV.getConstant() != MergeWithV.getConstant())
314 markOverdefined(IV, V);
315 }
316
Chris Lattnerb52f7002009-11-02 03:03:42 +0000317 void mergeInValue(Value *V, LatticeVal &MergeWithV) {
Chris Lattner220571c2009-11-02 03:21:36 +0000318 mergeInValue(ValueState[V], V, MergeWithV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 }
320
321
322 // getValueState - Return the LatticeVal object that corresponds to the value.
323 // This function is necessary because not all values should start out in the
Chris Lattnerc8798002009-11-02 02:33:50 +0000324 // underdefined state. Argument's should be overdefined, and
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 // constants should be marked as constants. If a value is not known to be an
326 // Instruction object, then use this accessor to get its value from the map.
327 //
Chris Lattnerb52f7002009-11-02 03:03:42 +0000328 LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000329 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 if (I != ValueState.end()) return I->second; // Common case, in the map
331
Chris Lattner220571c2009-11-02 03:21:36 +0000332 LatticeVal &LV = ValueState[V];
333
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattner220571c2009-11-02 03:21:36 +0000335 // Undef values remain undefined.
336 if (!isa<UndefValue>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 LV.markConstant(C); // Constants are constant
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 }
Chris Lattner220571c2009-11-02 03:21:36 +0000339
Chris Lattnerc8798002009-11-02 02:33:50 +0000340 // All others are underdefined by default.
Chris Lattner220571c2009-11-02 03:21:36 +0000341 return LV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 }
343
344 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattnerc8798002009-11-02 02:33:50 +0000345 // work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 //
347 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
348 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
349 return; // This edge is already known to be executable!
350
351 if (BBExecutable.count(Dest)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000352 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
353 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354
355 // The destination is already executable, but we just made an edge
356 // feasible that wasn't before. Revisit the PHI nodes in the block
357 // because they have potentially new operands.
358 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
359 visitPHINode(*cast<PHINode>(I));
360
361 } else {
362 MarkBlockExecutable(Dest);
363 }
364 }
365
366 // getFeasibleSuccessors - Return a vector of booleans to indicate which
367 // successors are reachable from a given terminator instruction.
368 //
369 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
370
371 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000372 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000373 //
374 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
375
376 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000377 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 // information, we need to update the specified user of this instruction.
379 //
380 void OperandChangedState(User *U) {
381 // Only instructions use other variable values!
382 Instruction &I = cast<Instruction>(*U);
383 if (BBExecutable.count(I.getParent())) // Inst is executable?
384 visit(I);
385 }
386
387private:
388 friend class InstVisitor<SCCPSolver>;
389
Chris Lattnerc8798002009-11-02 02:33:50 +0000390 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 // operand made a transition, or the instruction is newly executable. Change
392 // the value type of I to reflect these changes if appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393 void visitPHINode(PHINode &I);
394
395 // Terminators
396 void visitReturnInst(ReturnInst &I);
397 void visitTerminatorInst(TerminatorInst &TI);
398
399 void visitCastInst(CastInst &I);
400 void visitSelectInst(SelectInst &I);
401 void visitBinaryOperator(Instruction &I);
402 void visitCmpInst(CmpInst &I);
403 void visitExtractElementInst(ExtractElementInst &I);
404 void visitInsertElementInst(InsertElementInst &I);
405 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000406 void visitExtractValueInst(ExtractValueInst &EVI);
407 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408
Chris Lattnerc8798002009-11-02 02:33:50 +0000409 // Instructions that cannot be folded away.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000410 void visitStoreInst (Instruction &I);
411 void visitLoadInst (LoadInst &I);
412 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000413 void visitCallInst (CallInst &I) {
414 if (isFreeCall(&I))
415 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000416 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000417 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 void visitInvokeInst (InvokeInst &II) {
419 visitCallSite(CallSite::get(&II));
420 visitTerminatorInst(II);
421 }
422 void visitCallSite (CallSite CS);
423 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
424 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000425 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
427 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428
429 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000430 // If a new instruction is added to LLVM that we don't handle.
Chris Lattner8a6411c2009-08-23 04:37:46 +0000431 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 markOverdefined(&I); // Just in case
433 }
434};
435
Duncan Sands40f67972007-07-20 08:56:21 +0000436} // end anonymous namespace
437
438
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439// getFeasibleSuccessors - Return a vector of booleans to indicate which
440// successors are reachable from a given terminator instruction.
441//
442void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
443 SmallVector<bool, 16> &Succs) {
444 Succs.resize(TI.getNumSuccessors());
445 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
446 if (BI->isUnconditional()) {
447 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000448 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000450
451 LatticeVal &BCValue = getValueState(BI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000452 ConstantInt *CI = BCValue.getConstantInt();
453 if (CI == 0) {
Chris Lattneradaf7332009-11-02 02:30:06 +0000454 // Overdefined condition variables, and branches on unfoldable constant
455 // conditions, mean the branch could go either way.
Chris Lattner220571c2009-11-02 03:21:36 +0000456 if (!BCValue.isUndefined())
457 Succs[0] = Succs[1] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000458 return;
459 }
460
461 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000462 Succs[CI->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000463 return;
464 }
465
Chris Lattner220571c2009-11-02 03:21:36 +0000466 if (isa<InvokeInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467 // Invoke instructions successors are always executable.
468 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000469 return;
470 }
471
472 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000474 ConstantInt *CI = SCValue.getConstantInt();
475
476 if (CI == 0) { // Overdefined or undefined condition?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 // All destinations are executable!
Chris Lattner220571c2009-11-02 03:21:36 +0000478 if (!SCValue.isUndefined())
479 Succs.assign(TI.getNumSuccessors(), true);
480 return;
481 }
482
483 Succs[SI->findCaseValue(CI)] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000484 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000485 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000486
487 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
488 if (isa<IndirectBrInst>(&TI)) {
489 // Just mark all destinations executable!
490 Succs.assign(TI.getNumSuccessors(), true);
491 return;
492 }
493
494#ifndef NDEBUG
495 errs() << "Unknown terminator instruction: " << TI << '\n';
496#endif
497 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000498}
499
500
501// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000502// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503//
504bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
505 assert(BBExecutable.count(To) && "Dest should always be alive!");
506
507 // Make sure the source basic block is executable!!
508 if (!BBExecutable.count(From)) return false;
509
Chris Lattnerc8798002009-11-02 02:33:50 +0000510 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 TerminatorInst *TI = From->getTerminator();
512 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
513 if (BI->isUnconditional())
514 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000515
516 LatticeVal &BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517
Chris Lattneradaf7332009-11-02 02:30:06 +0000518 // Overdefined condition variables mean the branch could go either way,
519 // undef conditions mean that neither edge is feasible yet.
Chris Lattner220571c2009-11-02 03:21:36 +0000520 ConstantInt *CI = BCValue.getConstantInt();
521 if (CI == 0)
522 return !BCValue.isUndefined();
Chris Lattneradaf7332009-11-02 02:30:06 +0000523
Chris Lattneradaf7332009-11-02 02:30:06 +0000524 // Constant condition variables mean the branch can only go a single way.
Chris Lattner220571c2009-11-02 03:21:36 +0000525 return BI->getSuccessor(CI->isZero()) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000526 }
527
528 // Invoke instructions successors are always executable.
529 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000530 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000531
532 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 LatticeVal &SCValue = getValueState(SI->getCondition());
Chris Lattner220571c2009-11-02 03:21:36 +0000534 ConstantInt *CI = SCValue.getConstantInt();
535
536 if (CI == 0)
537 return !SCValue.isUndefined();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538
Chris Lattner220571c2009-11-02 03:21:36 +0000539 // Make sure to skip the "default value" which isn't a value
540 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
541 if (SI->getSuccessorValue(i) == CI) // Found the taken branch.
542 return SI->getSuccessor(i) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543
Chris Lattner220571c2009-11-02 03:21:36 +0000544 // If the constant value is not equal to any of the branches, we must
545 // execute default branch.
546 return SI->getDefaultDest() == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000548
549 // Just mark all destinations executable!
550 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
551 if (isa<IndirectBrInst>(&TI))
552 return true;
553
554#ifndef NDEBUG
555 errs() << "Unknown terminator instruction: " << *TI << '\n';
556#endif
557 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558}
559
Chris Lattnerc8798002009-11-02 02:33:50 +0000560// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561// operand made a transition, or the instruction is newly executable. Change
562// the value type of I to reflect these changes if appropriate. This method
563// makes sure to do the following actions:
564//
565// 1. If a phi node merges two constants in, and has conflicting value coming
566// from different branches, or if the PHI node merges in an overdefined
567// value, then the PHI node becomes overdefined.
568// 2. If a phi node merges only constants in, and they all agree on value, the
569// PHI node becomes a constant value equal to that.
570// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
571// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
572// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
573// 6. If a conditional branch has a value that is constant, make the selected
574// destination executable
575// 7. If a conditional branch has a value that is overdefined, make all
576// successors executable.
577//
578void SCCPSolver::visitPHINode(PHINode &PN) {
579 LatticeVal &PNIV = getValueState(&PN);
580 if (PNIV.isOverdefined()) {
581 // There may be instructions using this PHI node that are not overdefined
582 // themselves. If so, make sure that they know that the PHI node operand
583 // changed.
584 std::multimap<PHINode*, Instruction*>::iterator I, E;
585 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
586 if (I != E) {
587 SmallVector<Instruction*, 16> Users;
588 for (; I != E; ++I) Users.push_back(I->second);
589 while (!Users.empty()) {
590 visit(Users.back());
591 Users.pop_back();
592 }
593 }
594 return; // Quick exit
595 }
596
597 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
598 // and slow us down a lot. Just mark them overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +0000599 if (PN.getNumIncomingValues() > 64)
600 return markOverdefined(PNIV, &PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601
602 // Look at all of the executable operands of the PHI node. If any of them
603 // are overdefined, the PHI becomes overdefined as well. If they are all
604 // constant, and they agree with each other, the PHI becomes the identical
605 // constant. If they are constant and don't agree, the PHI is overdefined.
606 // If there are no executable operands, the PHI remains undefined.
607 //
608 Constant *OperandVal = 0;
609 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
610 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
611 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
612
Chris Lattnerb52f7002009-11-02 03:03:42 +0000613 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
614 continue;
615
616 if (IV.isOverdefined()) // PHI node becomes overdefined!
617 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618
Chris Lattnerb52f7002009-11-02 03:03:42 +0000619 if (OperandVal == 0) { // Grab the first value.
620 OperandVal = IV.getConstant();
621 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622 }
Chris Lattnerb52f7002009-11-02 03:03:42 +0000623
624 // There is already a reachable operand. If we conflict with it,
625 // then the PHI node becomes overdefined. If we agree with it, we
626 // can continue on.
627
628 // Check to see if there are two different constants merging, if so, the PHI
629 // node is overdefined.
630 if (IV.getConstant() != OperandVal)
631 return markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 }
633
634 // If we exited the loop, this means that the PHI node only has constant
635 // arguments that agree with each other(and OperandVal is the constant) or
636 // OperandVal is null because there are no defined incoming arguments. If
637 // this is the case, the PHI remains undefined.
638 //
639 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000640 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641}
642
643void SCCPSolver::visitReturnInst(ReturnInst &I) {
644 if (I.getNumOperands() == 0) return; // Ret void
645
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000647 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000648 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000649 return;
650
Chris Lattnercd73be02008-04-23 05:38:20 +0000651 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000653 TrackedRetVals.find(F);
654 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 !TFRVI->second.isOverdefined()) {
656 LatticeVal &IV = getValueState(I.getOperand(0));
657 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000658 return;
659 }
660 }
661
Chris Lattnercd73be02008-04-23 05:38:20 +0000662 // Handle functions that return multiple values.
663 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
664 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000665 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000666 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
667 if (It == TrackedMultipleRetVals.end()) break;
668 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
Dan Gohman856193b2008-06-20 01:15:44 +0000670 } else if (!TrackedMultipleRetVals.empty() &&
671 I.getNumOperands() == 1 &&
672 isa<StructType>(I.getOperand(0)->getType())) {
673 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
674 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000675 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000676 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
677 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000678 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000679 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000680 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 }
682}
683
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
685 SmallVector<bool, 16> SuccFeasible;
686 getFeasibleSuccessors(TI, SuccFeasible);
687
688 BasicBlock *BB = TI.getParent();
689
Chris Lattnerc8798002009-11-02 02:33:50 +0000690 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
692 if (SuccFeasible[i])
693 markEdgeExecutable(BB, TI.getSuccessor(i));
694}
695
696void SCCPSolver::visitCastInst(CastInst &I) {
697 Value *V = I.getOperand(0);
698 LatticeVal &VState = getValueState(V);
699 if (VState.isOverdefined()) // Inherit overdefinedness of operand
700 markOverdefined(&I);
701 else if (VState.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000702 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000703 VState.getConstant(), I.getType()));
704}
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) {
778 LatticeVal &CondValue = getValueState(I.getCondition());
779 if (CondValue.isUndefined())
780 return;
Chris Lattner220571c2009-11-02 03:21:36 +0000781
782 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
783 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 : I.getFalseValue()));
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.
791 LatticeVal &TVal = getValueState(I.getTrueValue());
792 LatticeVal &FVal = getValueState(I.getFalseValue());
793
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
799 if (TVal.isUndefined()) { // select ?, undef, X -> X.
800 mergeInValue(&I, FVal);
801 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
802 mergeInValue(&I, TVal);
803 } else {
804 markOverdefined(&I);
805 }
806}
807
Chris Lattnerc8798002009-11-02 02:33:50 +0000808// Handle BinaryOperators and Shift Instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809void SCCPSolver::visitBinaryOperator(Instruction &I) {
810 LatticeVal &IV = ValueState[&I];
811 if (IV.isOverdefined()) return;
812
813 LatticeVal &V1State = getValueState(I.getOperand(0));
814 LatticeVal &V2State = getValueState(I.getOperand(1));
815
816 if (V1State.isOverdefined() || V2State.isOverdefined()) {
817 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
818 // operand is overdefined.
819 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
820 LatticeVal *NonOverdefVal = 0;
821 if (!V1State.isOverdefined()) {
822 NonOverdefVal = &V1State;
823 } else if (!V2State.isOverdefined()) {
824 NonOverdefVal = &V2State;
825 }
826
827 if (NonOverdefVal) {
828 if (NonOverdefVal->isUndefined()) {
829 // Could annihilate value.
830 if (I.getOpcode() == Instruction::And)
Owen Andersonaac28372009-07-31 20:28:14 +0000831 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersonaac28372009-07-31 20:28:14 +0000833 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 else
Owen Andersonfa089ab2009-07-03 19:42:02 +0000835 markConstant(IV, &I,
Owen Andersonaac28372009-07-31 20:28:14 +0000836 Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 return;
838 } else {
839 if (I.getOpcode() == Instruction::And) {
Chris Lattnerb52f7002009-11-02 03:03:42 +0000840 // X and 0 = 0
841 if (NonOverdefVal->getConstant()->isNullValue())
842 return markConstant(IV, &I, NonOverdefVal->getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 } else {
Chris Lattner220571c2009-11-02 03:21:36 +0000844 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
Chris Lattnerb52f7002009-11-02 03:03:42 +0000845 if (CI->isAllOnesValue()) // X or -1 = -1
846 return markConstant(IV, &I, NonOverdefVal->getConstant());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 }
848 }
849 }
850 }
851
852
853 // If both operands are PHI nodes, it is possible that this instruction has
854 // a constant value, despite the fact that the PHI node doesn't. Check for
855 // this condition now.
856 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
857 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
858 if (PN1->getParent() == PN2->getParent()) {
859 // Since the two PHI nodes are in the same basic block, they must have
860 // entries for the same predecessors. Walk the predecessor list, and
861 // if all of the incoming values are constants, and the result of
862 // evaluating this expression with all incoming value pairs is the
863 // same, then this expression is a constant even though the PHI node
864 // is not a constant!
865 LatticeVal Result;
866 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
867 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
868 BasicBlock *InBlock = PN1->getIncomingBlock(i);
869 LatticeVal &In2 =
870 getValueState(PN2->getIncomingValueForBlock(InBlock));
871
872 if (In1.isOverdefined() || In2.isOverdefined()) {
873 Result.markOverdefined();
874 break; // Cannot fold this operation over the PHI nodes!
Chris Lattnerb52f7002009-11-02 03:03:42 +0000875 }
876
877 if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000878 Constant *V =
Owen Anderson02b48c32009-07-29 18:55:55 +0000879 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 In2.getConstant());
881 if (Result.isUndefined())
882 Result.markConstant(V);
883 else if (Result.isConstant() && Result.getConstant() != V) {
884 Result.markOverdefined();
885 break;
886 }
887 }
888 }
889
890 // If we found a constant value here, then we know the instruction is
891 // constant despite the fact that the PHI nodes are overdefined.
892 if (Result.isConstant()) {
893 markConstant(IV, &I, Result.getConstant());
894 // Remember that this instruction is virtually using the PHI node
895 // operands.
896 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
897 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
898 return;
899 } else if (Result.isUndefined()) {
900 return;
901 }
902
903 // Okay, this really is overdefined now. Since we might have
904 // speculatively thought that this was not overdefined before, and
905 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
906 // make sure to clean out any entries that we put there, for
907 // efficiency.
908 std::multimap<PHINode*, Instruction*>::iterator It, E;
909 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
910 while (It != E) {
911 if (It->second == &I) {
912 UsersOfOverdefinedPHIs.erase(It++);
913 } else
914 ++It;
915 }
916 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
917 while (It != E) {
918 if (It->second == &I) {
919 UsersOfOverdefinedPHIs.erase(It++);
920 } else
921 ++It;
922 }
923 }
924
925 markOverdefined(IV, &I);
926 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000927 markConstant(IV, &I,
Owen Anderson02b48c32009-07-29 18:55:55 +0000928 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 V2State.getConstant()));
930 }
931}
932
Chris Lattnerc8798002009-11-02 02:33:50 +0000933// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934void SCCPSolver::visitCmpInst(CmpInst &I) {
935 LatticeVal &IV = ValueState[&I];
936 if (IV.isOverdefined()) return;
937
938 LatticeVal &V1State = getValueState(I.getOperand(0));
939 LatticeVal &V2State = getValueState(I.getOperand(1));
940
941 if (V1State.isOverdefined() || V2State.isOverdefined()) {
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 =
959 getValueState(PN2->getIncomingValueForBlock(InBlock));
960
961 if (In1.isOverdefined() || In2.isOverdefined()) {
962 Result.markOverdefined();
963 break; // Cannot fold this operation over the PHI nodes!
964 } else if (In1.isConstant() && In2.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000965 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 In1.getConstant(),
967 In2.getConstant());
968 if (Result.isUndefined())
969 Result.markConstant(V);
970 else if (Result.isConstant() && Result.getConstant() != V) {
971 Result.markOverdefined();
972 break;
973 }
974 }
975 }
976
977 // If we found a constant value here, then we know the instruction is
978 // constant despite the fact that the PHI nodes are overdefined.
979 if (Result.isConstant()) {
980 markConstant(IV, &I, Result.getConstant());
981 // Remember that this instruction is virtually using the PHI node
982 // operands.
983 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
984 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
985 return;
986 } else if (Result.isUndefined()) {
987 return;
988 }
989
990 // Okay, this really is overdefined now. Since we might have
991 // speculatively thought that this was not overdefined before, and
992 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
993 // make sure to clean out any entries that we put there, for
994 // efficiency.
995 std::multimap<PHINode*, Instruction*>::iterator It, E;
996 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
997 while (It != E) {
998 if (It->second == &I) {
999 UsersOfOverdefinedPHIs.erase(It++);
1000 } else
1001 ++It;
1002 }
1003 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1004 while (It != E) {
1005 if (It->second == &I) {
1006 UsersOfOverdefinedPHIs.erase(It++);
1007 } else
1008 ++It;
1009 }
1010 }
1011
1012 markOverdefined(IV, &I);
1013 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00001014 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 V1State.getConstant(),
1016 V2State.getConstant()));
1017 }
1018}
1019
1020void SCCPSolver::visitExtractElementInst(ExtractElementInst &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
1024#if 0
1025 LatticeVal &ValState = getValueState(I.getOperand(0));
1026 LatticeVal &IdxState = getValueState(I.getOperand(1));
1027
1028 if (ValState.isOverdefined() || IdxState.isOverdefined())
1029 markOverdefined(&I);
1030 else if(ValState.isConstant() && IdxState.isConstant())
1031 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1032 IdxState.getConstant()));
1033#endif
1034}
1035
1036void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1037 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001038 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039#if 0
1040 LatticeVal &ValState = getValueState(I.getOperand(0));
1041 LatticeVal &EltState = getValueState(I.getOperand(1));
1042 LatticeVal &IdxState = getValueState(I.getOperand(2));
1043
1044 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1045 IdxState.isOverdefined())
1046 markOverdefined(&I);
1047 else if(ValState.isConstant() && EltState.isConstant() &&
1048 IdxState.isConstant())
1049 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1050 EltState.getConstant(),
1051 IdxState.getConstant()));
1052 else if (ValState.isUndefined() && EltState.isConstant() &&
1053 IdxState.isConstant())
1054 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1055 EltState.getConstant(),
1056 IdxState.getConstant()));
1057#endif
1058}
1059
1060void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1061 // FIXME : SCCP does not handle vectors properly.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001062 return markOverdefined(&I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001063#if 0
1064 LatticeVal &V1State = getValueState(I.getOperand(0));
1065 LatticeVal &V2State = getValueState(I.getOperand(1));
1066 LatticeVal &MaskState = getValueState(I.getOperand(2));
1067
1068 if (MaskState.isUndefined() ||
1069 (V1State.isUndefined() && V2State.isUndefined()))
1070 return; // Undefined output if mask or both inputs undefined.
1071
1072 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1073 MaskState.isOverdefined()) {
1074 markOverdefined(&I);
1075 } else {
1076 // A mix of constant/undef inputs.
1077 Constant *V1 = V1State.isConstant() ?
1078 V1State.getConstant() : UndefValue::get(I.getType());
1079 Constant *V2 = V2State.isConstant() ?
1080 V2State.getConstant() : UndefValue::get(I.getType());
1081 Constant *Mask = MaskState.isConstant() ?
1082 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1083 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1084 }
1085#endif
1086}
1087
Chris Lattnerc8798002009-11-02 02:33:50 +00001088// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089// can turn this into a getelementptr ConstantExpr.
1090//
1091void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1092 LatticeVal &IV = ValueState[&I];
1093 if (IV.isOverdefined()) return;
1094
1095 SmallVector<Constant*, 8> Operands;
1096 Operands.reserve(I.getNumOperands());
1097
1098 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1099 LatticeVal &State = getValueState(I.getOperand(i));
1100 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001101 return; // Operands are not resolved yet.
1102
Chris Lattnerb52f7002009-11-02 03:03:42 +00001103 if (State.isOverdefined())
1104 return markOverdefined(IV, &I);
1105
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106 assert(State.isConstant() && "Unknown state!");
1107 Operands.push_back(State.getConstant());
1108 }
1109
1110 Constant *Ptr = Operands[0];
Chris Lattnerc8798002009-11-02 02:33:50 +00001111 Operands.erase(Operands.begin()); // Erase the pointer from idx list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112
Owen Anderson02b48c32009-07-29 18:55:55 +00001113 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 Operands.size()));
1115}
1116
1117void SCCPSolver::visitStoreInst(Instruction &SI) {
1118 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1119 return;
1120 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1121 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1122 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1123
1124 // Get the value we are storing into the global.
1125 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1126
1127 mergeInValue(I->second, GV, PtrVal);
1128 if (I->second.isOverdefined())
1129 TrackedGlobals.erase(I); // No need to keep tracking this!
1130}
1131
1132
1133// Handle load instructions. If the operand is a constant pointer to a constant
1134// global, we can replace the load with the loaded constant value!
1135void SCCPSolver::visitLoadInst(LoadInst &I) {
1136 LatticeVal &IV = ValueState[&I];
1137 if (IV.isOverdefined()) return;
1138
1139 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1140 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1141 if (PtrVal.isConstant() && !I.isVolatile()) {
1142 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001143 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +00001144 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145 // load null -> null
Chris Lattnerb52f7002009-11-02 03:03:42 +00001146 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 }
1148
1149 // Transform load (constant global) into the value loaded.
1150 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1151 if (GV->isConstant()) {
Chris Lattnerb52f7002009-11-02 03:03:42 +00001152 if (GV->hasDefinitiveInitializer())
1153 return markConstant(IV, &I, GV->getInitializer());
1154
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 } else if (!TrackedGlobals.empty()) {
1156 // If we are tracking this global, merge in the known value for it.
1157 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1158 TrackedGlobals.find(GV);
1159 if (It != TrackedGlobals.end()) {
1160 mergeInValue(IV, &I, It->second);
1161 return;
1162 }
1163 }
1164 }
1165
1166 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1167 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1168 if (CE->getOpcode() == Instruction::GetElementPtr)
1169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +00001170 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171 if (Constant *V =
Chris Lattnerb52f7002009-11-02 03:03:42 +00001172 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
1173 return markConstant(IV, &I, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 }
1175
1176 // Otherwise we cannot say for certain what value this load will produce.
1177 // Bail out.
1178 markOverdefined(IV, &I);
1179}
1180
1181void SCCPSolver::visitCallSite(CallSite CS) {
1182 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001183 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001184
1185 // The common case is that we aren't tracking the callee, either because we
1186 // are not doing interprocedural analysis or the callee is indirect, or is
1187 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001188 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001189CallOverdefined:
1190 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001191 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001192
1193 // Otherwise, if we have a single return value case, and if the function is
1194 // a declaration, maybe we can constant fold it.
1195 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1196 canConstantFoldCallTo(F)) {
1197
1198 SmallVector<Constant*, 8> Operands;
1199 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1200 AI != E; ++AI) {
1201 LatticeVal &State = getValueState(*AI);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001202
Chris Lattnercd73be02008-04-23 05:38:20 +00001203 if (State.isUndefined())
1204 return; // Operands are not resolved yet.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001205 if (State.isOverdefined())
1206 return markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001207 assert(State.isConstant() && "Unknown state!");
1208 Operands.push_back(State.getConstant());
1209 }
1210
1211 // If we can constant fold this, mark the result of the call as a
1212 // constant.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001213 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size()))
1214 return markConstant(I, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001216
1217 // Otherwise, we don't know anything about this call, mark it overdefined.
Chris Lattnerb52f7002009-11-02 03:03:42 +00001218 return markOverdefined(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 }
1220
Chris Lattnercd73be02008-04-23 05:38:20 +00001221 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001222 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1223 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001224 // If so, propagate the return value of the callee into this call result.
1225 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001226 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001227 // Check to see if we're tracking this callee, if not, handle it in the
1228 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001229 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1230 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001231 if (TMRVI == TrackedMultipleRetVals.end())
1232 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001233
1234 // Need to mark as overdefined, otherwise it stays undefined which
1235 // creates extractvalue undef, <idx>
1236 markOverdefined(I);
Chris Lattnerb52f7002009-11-02 03:03:42 +00001237
Chris Lattnercd73be02008-04-23 05:38:20 +00001238 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001239 // into this call site. We do this by walking all the uses. Single-index
1240 // ExtractValueInst uses can be tracked; anything more complicated is
1241 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001242 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1243 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001244 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1245 if (EVI->getNumIndices() == 1) {
1246 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001247 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001248 continue;
1249 }
1250 }
1251 // The aggregate value is used in a way not handled here. Assume nothing.
1252 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001253 }
Dan Gohman856193b2008-06-20 01:15:44 +00001254 } else {
1255 // Otherwise we're not tracking this callee, so handle it in the
1256 // common path above.
1257 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001258 }
1259
1260 // Finally, if this is the first call to the function hit, mark its entry
1261 // block executable.
1262 if (!BBExecutable.count(F->begin()))
1263 MarkBlockExecutable(F->begin());
1264
1265 // Propagate information from this call site into the callee.
1266 CallSite::arg_iterator CAI = CS.arg_begin();
1267 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1268 AI != E; ++AI, ++CAI) {
1269 LatticeVal &IV = ValueState[AI];
Edwin Török129b2d12009-09-24 18:33:42 +00001270 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Edwin Törökd5435372009-09-24 09:47:18 +00001271 IV.markOverdefined();
1272 continue;
1273 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001274 if (!IV.isOverdefined())
1275 mergeInValue(IV, AI, getValueState(*CAI));
1276 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277}
1278
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279void SCCPSolver::Solve() {
1280 // Process the work lists until they are empty!
1281 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1282 !OverdefinedInstWorkList.empty()) {
Chris Lattnerc8798002009-11-02 02:33:50 +00001283 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 while (!OverdefinedInstWorkList.empty()) {
1285 Value *I = OverdefinedInstWorkList.back();
1286 OverdefinedInstWorkList.pop_back();
1287
Dan Gohmandff8d172009-08-17 15:25:05 +00001288 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289
1290 // "I" got into the work list because it either made the transition from
1291 // bottom to constant
1292 //
1293 // Anything on this worklist that is overdefined need not be visited
1294 // since all of its users will have already been marked as overdefined
Chris Lattnerc8798002009-11-02 02:33:50 +00001295 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 //
1297 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1298 UI != E; ++UI)
1299 OperandChangedState(*UI);
1300 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001301
1302 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 while (!InstWorkList.empty()) {
1304 Value *I = InstWorkList.back();
1305 InstWorkList.pop_back();
1306
Dan Gohmandff8d172009-08-17 15:25:05 +00001307 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001308
1309 // "I" got into the work list because it either made the transition from
1310 // bottom to constant
1311 //
1312 // Anything on this worklist that is overdefined need not be visited
1313 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001314 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 //
1316 if (!getValueState(I).isOverdefined())
1317 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1318 UI != E; ++UI)
1319 OperandChangedState(*UI);
1320 }
1321
Chris Lattnerc8798002009-11-02 02:33:50 +00001322 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 while (!BBWorkList.empty()) {
1324 BasicBlock *BB = BBWorkList.back();
1325 BBWorkList.pop_back();
1326
Dan Gohmandff8d172009-08-17 15:25:05 +00001327 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328
1329 // Notify all instructions in this basic block that they are newly
1330 // executable.
1331 visit(BB);
1332 }
1333 }
1334}
1335
1336/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1337/// that branches on undef values cannot reach any of their successors.
1338/// However, this is not a safe assumption. After we solve dataflow, this
1339/// method should be use to handle this. If this returns true, the solver
1340/// should be rerun.
1341///
1342/// This method handles this by finding an unresolved branch and marking it one
1343/// of the edges from the block as being feasible, even though the condition
1344/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1345/// CFG and only slightly pessimizes the analysis results (by marking one,
1346/// potentially infeasible, edge feasible). This cannot usefully modify the
1347/// constraints on the condition of the branch, as that would impact other users
1348/// of the value.
1349///
1350/// This scan also checks for values that use undefs, whose results are actually
1351/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1352/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1353/// even if X isn't defined.
1354bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1355 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1356 if (!BBExecutable.count(BB))
1357 continue;
1358
1359 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1360 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001361 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001362
1363 LatticeVal &LV = getValueState(I);
1364 if (!LV.isUndefined()) continue;
1365
1366 // Get the lattice values of the first two operands for use below.
1367 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1368 LatticeVal Op1LV;
1369 if (I->getNumOperands() == 2) {
1370 // If this is a two-operand instruction, and if both operands are
1371 // undefs, the result stays undef.
1372 Op1LV = getValueState(I->getOperand(1));
1373 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1374 continue;
1375 }
1376
1377 // If this is an instructions whose result is defined even if the input is
1378 // not fully defined, propagate the information.
1379 const Type *ITy = I->getType();
1380 switch (I->getOpcode()) {
1381 default: break; // Leave the instruction as an undef.
1382 case Instruction::ZExt:
1383 // After a zero extend, we know the top part is zero. SExt doesn't have
1384 // to be handled here, because we don't know whether the top part is 1's
1385 // or 0's.
1386 assert(Op0LV.isUndefined());
Owen Andersonaac28372009-07-31 20:28:14 +00001387 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001388 return true;
1389 case Instruction::Mul:
1390 case Instruction::And:
1391 // undef * X -> 0. X could be zero.
1392 // undef & X -> 0. X could be zero.
Owen Andersonaac28372009-07-31 20:28:14 +00001393 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 return true;
1395
1396 case Instruction::Or:
1397 // undef | X -> -1. X could be -1.
1398 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001399 markForcedConstant(LV, I,
Owen Andersonaac28372009-07-31 20:28:14 +00001400 Constant::getAllOnesValue(PTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001401 else
Owen Andersonaac28372009-07-31 20:28:14 +00001402 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 return true;
1404
1405 case Instruction::SDiv:
1406 case Instruction::UDiv:
1407 case Instruction::SRem:
1408 case Instruction::URem:
1409 // X / undef -> undef. No change.
1410 // X % undef -> undef. No change.
1411 if (Op1LV.isUndefined()) break;
1412
1413 // undef / X -> 0. X could be maxint.
1414 // undef % X -> 0. X could be 1.
Owen Andersonaac28372009-07-31 20:28:14 +00001415 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001416 return true;
1417
1418 case Instruction::AShr:
1419 // undef >>s X -> undef. No change.
1420 if (Op0LV.isUndefined()) break;
1421
1422 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1423 if (Op0LV.isConstant())
1424 markForcedConstant(LV, I, Op0LV.getConstant());
1425 else
1426 markOverdefined(LV, I);
1427 return true;
1428 case Instruction::LShr:
1429 case Instruction::Shl:
1430 // undef >> X -> undef. No change.
1431 // undef << X -> undef. No change.
1432 if (Op0LV.isUndefined()) break;
1433
1434 // X >> undef -> 0. X could be 0.
1435 // X << undef -> 0. X could be 0.
Owen Andersonaac28372009-07-31 20:28:14 +00001436 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001437 return true;
1438 case Instruction::Select:
1439 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1440 if (Op0LV.isUndefined()) {
1441 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1442 Op1LV = getValueState(I->getOperand(2));
1443 } else if (Op1LV.isUndefined()) {
1444 // c ? undef : undef -> undef. No change.
1445 Op1LV = getValueState(I->getOperand(2));
1446 if (Op1LV.isUndefined())
1447 break;
1448 // Otherwise, c ? undef : x -> x.
1449 } else {
1450 // Leave Op1LV as Operand(1)'s LatticeValue.
1451 }
1452
1453 if (Op1LV.isConstant())
1454 markForcedConstant(LV, I, Op1LV.getConstant());
1455 else
1456 markOverdefined(LV, I);
1457 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001458 case Instruction::Call:
1459 // If a call has an undef result, it is because it is constant foldable
1460 // but one of the inputs was undef. Just force the result to
1461 // overdefined.
1462 markOverdefined(LV, I);
1463 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 }
1465 }
1466
1467 TerminatorInst *TI = BB->getTerminator();
1468 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1469 if (!BI->isConditional()) continue;
1470 if (!getValueState(BI->getCondition()).isUndefined())
1471 continue;
1472 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001473 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001474 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 if (!getValueState(SI->getCondition()).isUndefined())
1476 continue;
1477 } else {
1478 continue;
1479 }
1480
Chris Lattner6186e8c2008-01-28 00:32:30 +00001481 // If the edge to the second successor isn't thought to be feasible yet,
1482 // mark it so now. We pick the second one so that this goes to some
1483 // enumerated value in a switch instead of going to the default destination.
1484 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485 continue;
1486
1487 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1488 // and return. This will make other blocks reachable, which will allow new
1489 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001490 markEdgeExecutable(BB, TI->getSuccessor(1));
1491
1492 // This must be a conditional branch of switch on undef. At this point,
1493 // force the old terminator to branch to the first successor. This is
1494 // required because we are now influencing the dataflow of the function with
1495 // the assumption that this edge is taken. If we leave the branch condition
1496 // as undef, then further analysis could think the undef went another way
1497 // leading to an inconsistent set of conclusions.
1498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001499 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001500 } else {
1501 SwitchInst *SI = cast<SwitchInst>(TI);
1502 SI->setCondition(SI->getCaseValue(1));
1503 }
1504
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 return true;
1506 }
1507
1508 return false;
1509}
1510
1511
1512namespace {
1513 //===--------------------------------------------------------------------===//
1514 //
1515 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1516 /// Sparse Conditional Constant Propagator.
1517 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001518 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001519 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001520 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521
1522 // runOnFunction - Run the Sparse Conditional Constant Propagation
1523 // algorithm, and return true if the function was modified.
1524 //
1525 bool runOnFunction(Function &F);
1526
1527 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1528 AU.setPreservesCFG();
1529 }
1530 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001531} // end anonymous namespace
1532
Dan Gohman089efff2008-05-13 00:00:25 +00001533char SCCP::ID = 0;
1534static RegisterPass<SCCP>
1535X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001536
Chris Lattnerc8798002009-11-02 02:33:50 +00001537// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538FunctionPass *llvm::createSCCPPass() {
1539 return new SCCP();
1540}
1541
Chris Lattner14513dc2009-11-02 02:47:51 +00001542static void DeleteInstructionInBlock(BasicBlock *BB) {
1543 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1544 ++NumDeadBlocks;
1545
1546 // Delete the instructions backwards, as it has a reduced likelihood of
1547 // having to update as many def-use and use-def chains.
1548 while (!isa<TerminatorInst>(BB->begin())) {
1549 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1550
1551 if (!I->use_empty())
1552 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1553 BB->getInstList().erase(I);
1554 ++NumInstRemoved;
1555 }
1556}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557
1558// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1559// and return true if the function was modified.
1560//
1561bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001562 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563 SCCPSolver Solver;
1564
1565 // Mark the first block of the function as being executable.
1566 Solver.MarkBlockExecutable(F.begin());
1567
1568 // Mark all arguments to the function as being overdefined.
1569 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1570 Solver.markOverdefined(AI);
1571
1572 // Solve for constants.
1573 bool ResolvedUndefs = true;
1574 while (ResolvedUndefs) {
1575 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001576 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1578 }
1579
1580 bool MadeChanges = false;
1581
1582 // If we decided that there are basic blocks that are dead in this function,
1583 // delete their contents now. Note that we cannot actually delete the blocks,
1584 // as we cannot modify the CFG of the function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585
Chris Lattner14513dc2009-11-02 02:47:51 +00001586 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001587 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001588 DeleteInstructionInBlock(BB);
1589 MadeChanges = true;
1590 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001592
1593 // Iterate over all of the instructions in a function, replacing them with
1594 // constants if we have found them to be of constant values.
1595 //
1596 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1597 Instruction *Inst = BI++;
1598 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1599 continue;
1600
Chris Lattnerc9edab82009-11-02 02:54:24 +00001601 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1602 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001603 continue;
1604
1605 Constant *Const = IV.isConstant()
1606 ? IV.getConstant() : UndefValue::get(Inst->getType());
1607 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1608
1609 // Replaces all of the uses of a variable with uses of the constant.
1610 Inst->replaceAllUsesWith(Const);
1611
1612 // Delete the instruction.
1613 Inst->eraseFromParent();
1614
1615 // Hey, we just changed something!
1616 MadeChanges = true;
1617 ++NumInstRemoved;
1618 }
1619 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001620
1621 return MadeChanges;
1622}
1623
1624namespace {
1625 //===--------------------------------------------------------------------===//
1626 //
1627 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1628 /// Constant Propagation.
1629 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001630 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001632 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633 bool runOnModule(Module &M);
1634 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001635} // end anonymous namespace
1636
Dan Gohman089efff2008-05-13 00:00:25 +00001637char IPSCCP::ID = 0;
1638static RegisterPass<IPSCCP>
1639Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1640
Chris Lattnerc8798002009-11-02 02:33:50 +00001641// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642ModulePass *llvm::createIPSCCPPass() {
1643 return new IPSCCP();
1644}
1645
1646
1647static bool AddressIsTaken(GlobalValue *GV) {
1648 // Delete any dead constantexpr klingons.
1649 GV->removeDeadConstantUsers();
1650
1651 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1652 UI != E; ++UI)
1653 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1654 if (SI->getOperand(0) == GV || SI->isVolatile())
1655 return true; // Storing addr of GV.
1656 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1657 // Make sure we are calling the function, not passing the address.
Chris Lattner2f487502009-11-01 06:11:53 +00001658 if (UI.getOperandNo() != 0)
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001659 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1661 if (LI->isVolatile())
1662 return true;
Chris Lattner2f487502009-11-01 06:11:53 +00001663 } else if (isa<BlockAddress>(*UI)) {
1664 // blockaddress doesn't take the address of the function, it takes addr
1665 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 } else {
1667 return true;
1668 }
1669 return false;
1670}
1671
1672bool IPSCCP::runOnModule(Module &M) {
1673 SCCPSolver Solver;
1674
1675 // Loop over all functions, marking arguments to those with their addresses
1676 // taken or that are external as overdefined.
1677 //
1678 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001679 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 if (!F->isDeclaration())
1681 Solver.MarkBlockExecutable(F->begin());
1682 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1683 AI != E; ++AI)
1684 Solver.markOverdefined(AI);
1685 } else {
1686 Solver.AddTrackedFunction(F);
1687 }
1688
1689 // Loop over global variables. We inform the solver about any internal global
1690 // variables that do not have their 'addresses taken'. If they don't have
1691 // their addresses taken, we can propagate constants through them.
1692 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1693 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001694 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001695 Solver.TrackValueOfGlobalVariable(G);
1696
1697 // Solve for constants.
1698 bool ResolvedUndefs = true;
1699 while (ResolvedUndefs) {
1700 Solver.Solve();
1701
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001702 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 ResolvedUndefs = false;
1704 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1705 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1706 }
1707
1708 bool MadeChanges = false;
1709
1710 // Iterate over all of the instructions in the module, replacing them with
1711 // constants if we have found them to be of constant values.
1712 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001713 SmallVector<BasicBlock*, 512> BlocksToErase;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714
1715 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1716 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
Chris Lattnerc9edab82009-11-02 02:54:24 +00001717 AI != E; ++AI) {
1718 if (AI->use_empty()) continue;
1719
1720 LatticeVal IV = Solver.getLatticeValueFor(AI);
1721 if (IV.isOverdefined()) continue;
1722
1723 Constant *CST = IV.isConstant() ?
1724 IV.getConstant() : UndefValue::get(AI->getType());
1725 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1726
1727 // Replaces all of the uses of a variable with uses of the
1728 // constant.
1729 AI->replaceAllUsesWith(CST);
1730 ++IPNumArgsElimed;
1731 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001732
Chris Lattner14513dc2009-11-02 02:47:51 +00001733 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001734 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001735 DeleteInstructionInBlock(BB);
1736 MadeChanges = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1740 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001741 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001742 TI->getSuccessor(i)->removePredecessor(BB);
1743 }
1744 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001745 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner14513dc2009-11-02 02:47:51 +00001746 TI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747
1748 if (&*BB != &F->front())
1749 BlocksToErase.push_back(BB);
1750 else
Owen Anderson35b47072009-08-13 21:58:54 +00001751 new UnreachableInst(M.getContext(), BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001752 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001753 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001754
1755 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1756 Instruction *Inst = BI++;
1757 if (Inst->getType()->isVoidTy())
1758 continue;
1759
Chris Lattnerc9edab82009-11-02 02:54:24 +00001760 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1761 if (IV.isOverdefined())
Chris Lattner14513dc2009-11-02 02:47:51 +00001762 continue;
1763
1764 Constant *Const = IV.isConstant()
1765 ? IV.getConstant() : UndefValue::get(Inst->getType());
1766 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1767
1768 // Replaces all of the uses of a variable with uses of the
1769 // constant.
1770 Inst->replaceAllUsesWith(Const);
1771
1772 // Delete the instruction.
1773 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1774 Inst->eraseFromParent();
1775
1776 // Hey, we just changed something!
1777 MadeChanges = true;
1778 ++IPNumInstRemoved;
1779 }
1780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781
1782 // Now that all instructions in the function are constant folded, erase dead
1783 // blocks, because we can now use ConstantFoldTerminator to get rid of
1784 // in-edges.
1785 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1786 // If there are any PHI nodes in this successor, drop entries for BB now.
1787 BasicBlock *DeadBB = BlocksToErase[i];
1788 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001789 Instruction *I = cast<Instruction>(DeadBB->use_back());
1790 bool Folded = ConstantFoldTerminator(I->getParent());
1791 if (!Folded) {
1792 // The constant folder may not have been able to fold the terminator
1793 // if this is a branch or switch on undef. Fold it manually as a
1794 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001795#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1797 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1798 "Branch should be foldable!");
1799 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1800 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1801 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001802 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001803 }
Devang Patele92c16d2008-11-21 01:52:59 +00001804#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805
1806 // Make this an uncond branch to the first successor.
1807 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001808 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809
1810 // Remove entries in successor phi nodes to remove edges.
1811 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1812 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1813
1814 // Remove the old terminator.
1815 TI->eraseFromParent();
1816 }
1817 }
1818
1819 // Finally, delete the basic block.
1820 F->getBasicBlockList().erase(DeadBB);
1821 }
1822 BlocksToErase.clear();
1823 }
1824
1825 // If we inferred constant or undef return values for a function, we replaced
1826 // all call uses with the inferred value. This means we don't need to bother
1827 // actually returning anything from the function. Replace all return
1828 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001829 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001830 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1832 E = RV.end(); I != E; ++I)
1833 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001834 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 Function *F = I->first;
1836 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1837 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1838 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001839 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001840 }
1841
1842 // If we infered constant or undef values for globals variables, we can delete
1843 // the global and any stores that remain to it.
1844 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1845 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1846 E = TG.end(); I != E; ++I) {
1847 GlobalVariable *GV = I->first;
1848 assert(!I->second.isOverdefined() &&
1849 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001850 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851 while (!GV->use_empty()) {
1852 StoreInst *SI = cast<StoreInst>(GV->use_back());
1853 SI->eraseFromParent();
1854 }
1855 M.getGlobalList().erase(GV);
1856 ++IPNumGlobalConst;
1857 }
1858
1859 return MadeChanges;
1860}