blob: e931c379894e6376821f0de7186edbb9838b3089 [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 Lattner1eb405b2009-11-02 02:20:32 +000085 inline LatticeVal() : Val(0, undefined) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
Chris Lattner1eb405b2009-11-02 02:20:32 +000087 inline bool isUndefined() const { return getLatticeValue() == undefined; }
88 inline bool isConstant() const {
89 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
90 }
91 inline bool isOverdefined() const { return getLatticeValue() == overdefined; }
92
93 inline Constant *getConstant() const {
94 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099 inline 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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108 inline 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
132 inline void markForcedConstant(Constant *V) {
Chris Lattner1eb405b2009-11-02 02:20:32 +0000133 assert(isUndefined() && "Can't force a defined value!");
134 Val.setInt(forcedconstant);
135 Val.setPointer(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 }
137};
Chris Lattner14513dc2009-11-02 02:47:51 +0000138} // end anonymous namespace.
139
140
141namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143//===----------------------------------------------------------------------===//
144//
145/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
146/// Constant Propagation.
147///
148class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000149 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000150 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151
152 /// GlobalValue - If we are tracking any values for the contents of a global
153 /// variable, we keep a mapping from the constant accessor to the element of
154 /// the global, to the currently known value. If the value becomes
155 /// overdefined, it's entry is simply removed from this map.
156 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
157
Devang Pateladd320d2008-03-11 05:46:42 +0000158 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 /// value out of a function, it will have an entry in this map, indicating
160 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000161 DenseMap<Function*, LatticeVal> TrackedRetVals;
162
163 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
164 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000165 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166
167 // The reason for two worklists is that overdefined is the lowest state
168 // on the lattice, and moving things to overdefined as fast as possible
169 // makes SCCP converge much faster.
170 // By having a separate worklist, we accomplish this because everything
171 // possibly overdefined will become overdefined at the soonest possible
172 // point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000173 SmallVector<Value*, 64> OverdefinedInstWorkList;
174 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175
176
Chris Lattnerd3123a72008-08-23 23:36:38 +0000177 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178
179 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
180 /// overdefined, despite the fact that the PHI node is overdefined.
181 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
182
183 /// KnownFeasibleEdges - Entries in this set are edges which have already had
184 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000185 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
186 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187public:
188
189 /// MarkBlockExecutable - This method can be used by clients to mark all of
190 /// the blocks that are known to be intrinsically live in the processed unit.
191 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000192 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 BBExecutable.insert(BB); // Basic block is executable!
194 BBWorkList.push_back(BB); // Add the block to the work list!
195 }
196
197 /// TrackValueOfGlobalVariable - Clients can use this method to
198 /// inform the SCCPSolver that it should track loads and stores to the
199 /// specified global variable if it can. This is only legal to call if
200 /// performing Interprocedural SCCP.
201 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
202 const Type *ElTy = GV->getType()->getElementType();
203 if (ElTy->isFirstClassType()) {
204 LatticeVal &IV = TrackedGlobals[GV];
205 if (!isa<UndefValue>(GV->getInitializer()))
206 IV.markConstant(GV->getInitializer());
207 }
208 }
209
210 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
211 /// and out of the specified function (which cannot have its address taken),
212 /// this method must be called.
213 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000214 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000216 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
217 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000218 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
219 LatticeVal()));
220 } else
221 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 }
223
224 /// Solve - Solve for constants and executable blocks.
225 ///
226 void Solve();
227
228 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
229 /// that branches on undef values cannot reach any of their successors.
230 /// However, this is not a safe assumption. After we solve dataflow, this
231 /// method should be use to handle this. If this returns true, the solver
232 /// should be rerun.
233 bool ResolvedUndefsIn(Function &F);
234
Chris Lattner317e6b62008-08-23 23:39:31 +0000235 bool isBlockExecutable(BasicBlock *BB) const {
236 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 }
238
239 /// getValueMapping - Once we have solved for constants, return the mapping of
240 /// LLVM values to LatticeVals.
Bill Wendling03488ae2008-08-14 23:05:24 +0000241 std::map<Value*, LatticeVal> &getValueMapping() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 return ValueState;
243 }
244
Devang Pateladd320d2008-03-11 05:46:42 +0000245 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000247 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
248 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 }
250
251 /// getTrackedGlobals - Get and return the set of inferred initializers for
252 /// global variables.
253 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
254 return TrackedGlobals;
255 }
256
257 inline void markOverdefined(Value *V) {
258 markOverdefined(ValueState[V], V);
259 }
260
261private:
262 // markConstant - Make a value be marked as "constant". If the value
263 // is not already a constant, add it to the instruction work list so that
264 // the users of the instruction are updated later.
265 //
266 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
267 if (IV.markConstant(C)) {
Dan Gohmandff8d172009-08-17 15:25:05 +0000268 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 InstWorkList.push_back(V);
270 }
271 }
272
273 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
274 IV.markForcedConstant(C);
Dan Gohmandff8d172009-08-17 15:25:05 +0000275 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 InstWorkList.push_back(V);
277 }
278
279 inline void markConstant(Value *V, Constant *C) {
280 markConstant(ValueState[V], V, C);
281 }
282
283 // markOverdefined - Make a value be marked as "overdefined". If the
284 // value is not already overdefined, add it to the overdefined instruction
285 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 inline void markOverdefined(LatticeVal &IV, Value *V) {
287 if (IV.markOverdefined()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +0000288 DEBUG(errs() << "markOverdefined: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbar005975c2009-07-25 00:23:56 +0000290 errs() << "Function '" << F->getName() << "'\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 else
Dan Gohmandff8d172009-08-17 15:25:05 +0000292 errs() << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 // Only instructions go on the work list
294 OverdefinedInstWorkList.push_back(V);
295 }
296 }
297
298 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
299 if (IV.isOverdefined() || MergeWithV.isUndefined())
300 return; // Noop.
301 if (MergeWithV.isOverdefined())
302 markOverdefined(IV, V);
303 else if (IV.isUndefined())
304 markConstant(IV, V, MergeWithV.getConstant());
305 else if (IV.getConstant() != MergeWithV.getConstant())
306 markOverdefined(IV, V);
307 }
308
309 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
310 return mergeInValue(ValueState[V], V, MergeWithV);
311 }
312
313
314 // getValueState - Return the LatticeVal object that corresponds to the value.
315 // This function is necessary because not all values should start out in the
Chris Lattnerc8798002009-11-02 02:33:50 +0000316 // underdefined state. Argument's should be overdefined, and
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 // constants should be marked as constants. If a value is not known to be an
318 // Instruction object, then use this accessor to get its value from the map.
319 //
320 inline LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000321 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 if (I != ValueState.end()) return I->second; // Common case, in the map
323
324 if (Constant *C = dyn_cast<Constant>(V)) {
325 if (isa<UndefValue>(V)) {
326 // Nothing to do, remain undefined.
327 } else {
328 LatticeVal &LV = ValueState[C];
329 LV.markConstant(C); // Constants are constant
330 return LV;
331 }
332 }
Chris Lattnerc8798002009-11-02 02:33:50 +0000333 // All others are underdefined by default.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 return ValueState[V];
335 }
336
337 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattnerc8798002009-11-02 02:33:50 +0000338 // work list if it is not already executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 //
340 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
341 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
342 return; // This edge is already known to be executable!
343
344 if (BBExecutable.count(Dest)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000345 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
346 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347
348 // The destination is already executable, but we just made an edge
349 // feasible that wasn't before. Revisit the PHI nodes in the block
350 // because they have potentially new operands.
351 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
352 visitPHINode(*cast<PHINode>(I));
353
354 } else {
355 MarkBlockExecutable(Dest);
356 }
357 }
358
359 // getFeasibleSuccessors - Return a vector of booleans to indicate which
360 // successors are reachable from a given terminator instruction.
361 //
362 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
363
364 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000365 // block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 //
367 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
368
369 // OperandChangedState - This method is invoked on all of the users of an
Chris Lattnerc8798002009-11-02 02:33:50 +0000370 // instruction that was just changed state somehow. Based on this
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 // information, we need to update the specified user of this instruction.
372 //
373 void OperandChangedState(User *U) {
374 // Only instructions use other variable values!
375 Instruction &I = cast<Instruction>(*U);
376 if (BBExecutable.count(I.getParent())) // Inst is executable?
377 visit(I);
378 }
379
380private:
381 friend class InstVisitor<SCCPSolver>;
382
Chris Lattnerc8798002009-11-02 02:33:50 +0000383 // visit implementations - Something changed in this instruction. Either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 // operand made a transition, or the instruction is newly executable. Change
385 // the value type of I to reflect these changes if appropriate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 void visitPHINode(PHINode &I);
387
388 // Terminators
389 void visitReturnInst(ReturnInst &I);
390 void visitTerminatorInst(TerminatorInst &TI);
391
392 void visitCastInst(CastInst &I);
393 void visitSelectInst(SelectInst &I);
394 void visitBinaryOperator(Instruction &I);
395 void visitCmpInst(CmpInst &I);
396 void visitExtractElementInst(ExtractElementInst &I);
397 void visitInsertElementInst(InsertElementInst &I);
398 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000399 void visitExtractValueInst(ExtractValueInst &EVI);
400 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401
Chris Lattnerc8798002009-11-02 02:33:50 +0000402 // Instructions that cannot be folded away.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 void visitStoreInst (Instruction &I);
404 void visitLoadInst (LoadInst &I);
405 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000406 void visitCallInst (CallInst &I) {
407 if (isFreeCall(&I))
408 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000409 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 void visitInvokeInst (InvokeInst &II) {
412 visitCallSite(CallSite::get(&II));
413 visitTerminatorInst(II);
414 }
415 void visitCallSite (CallSite CS);
416 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
417 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000418 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
420 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421
422 void visitInstruction(Instruction &I) {
Chris Lattnerc8798002009-11-02 02:33:50 +0000423 // If a new instruction is added to LLVM that we don't handle.
Chris Lattner8a6411c2009-08-23 04:37:46 +0000424 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 markOverdefined(&I); // Just in case
426 }
427};
428
Duncan Sands40f67972007-07-20 08:56:21 +0000429} // end anonymous namespace
430
431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432// getFeasibleSuccessors - Return a vector of booleans to indicate which
433// successors are reachable from a given terminator instruction.
434//
435void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
436 SmallVector<bool, 16> &Succs) {
437 Succs.resize(TI.getNumSuccessors());
438 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
439 if (BI->isUnconditional()) {
440 Succs[0] = true;
Chris Lattneradaf7332009-11-02 02:30:06 +0000441 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 }
Chris Lattneradaf7332009-11-02 02:30:06 +0000443
444 LatticeVal &BCValue = getValueState(BI->getCondition());
445 if (BCValue.isOverdefined() ||
446 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
447 // Overdefined condition variables, and branches on unfoldable constant
448 // conditions, mean the branch could go either way.
449 Succs[0] = Succs[1] = true;
450 return;
451 }
452
453 // Constant condition variables mean the branch can only go a single way.
Chris Lattnere9474d52009-11-02 02:48:17 +0000454 if (BCValue.isConstant())
455 Succs[cast<ConstantInt>(BCValue.getConstant())->isZero()] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000456 return;
457 }
458
459 if (isa<InvokeInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 // Invoke instructions successors are always executable.
461 Succs[0] = Succs[1] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000462 return;
463 }
464
465 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 LatticeVal &SCValue = getValueState(SI->getCondition());
467 if (SCValue.isOverdefined() || // Overdefined condition?
468 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
469 // All destinations are executable!
470 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner81335532008-05-10 23:56:54 +0000471 } else if (SCValue.isConstant())
472 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000473 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000475
476 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
477 if (isa<IndirectBrInst>(&TI)) {
478 // Just mark all destinations executable!
479 Succs.assign(TI.getNumSuccessors(), true);
480 return;
481 }
482
483#ifndef NDEBUG
484 errs() << "Unknown terminator instruction: " << TI << '\n';
485#endif
486 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487}
488
489
490// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
Chris Lattnerc8798002009-11-02 02:33:50 +0000491// block to the 'To' basic block is currently feasible.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492//
493bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
494 assert(BBExecutable.count(To) && "Dest should always be alive!");
495
496 // Make sure the source basic block is executable!!
497 if (!BBExecutable.count(From)) return false;
498
Chris Lattnerc8798002009-11-02 02:33:50 +0000499 // Check to make sure this edge itself is actually feasible now.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 TerminatorInst *TI = From->getTerminator();
501 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
502 if (BI->isUnconditional())
503 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000504
505 LatticeVal &BCValue = getValueState(BI->getCondition());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000506
Chris Lattneradaf7332009-11-02 02:30:06 +0000507 // Overdefined condition variables mean the branch could go either way,
508 // undef conditions mean that neither edge is feasible yet.
509 if (!BCValue.isConstant())
510 return BCValue.isOverdefined();
511
512 // Not branching on an evaluatable constant?
513 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
514
515 // Constant condition variables mean the branch can only go a single way.
516 bool CondIsFalse = cast<ConstantInt>(BCValue.getConstant())->isZero();
517 return BI->getSuccessor(CondIsFalse) == To;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000518 }
519
520 // Invoke instructions successors are always executable.
521 if (isa<InvokeInst>(TI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000522 return true;
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000523
524 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 LatticeVal &SCValue = getValueState(SI->getCondition());
526 if (SCValue.isOverdefined()) { // Overdefined condition?
527 // All destinations are executable!
528 return true;
529 } else if (SCValue.isConstant()) {
530 Constant *CPV = SCValue.getConstant();
531 if (!isa<ConstantInt>(CPV))
532 return true; // not a foldable constant?
533
534 // Make sure to skip the "default value" which isn't a value
535 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
Chris Lattnerc8798002009-11-02 02:33:50 +0000536 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 return SI->getSuccessor(i) == To;
538
Chris Lattnerc8798002009-11-02 02:33:50 +0000539 // If the constant value is not equal to any of the branches, we must
540 // execute default branch.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 return SI->getDefaultDest() == To;
542 }
543 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 }
Chris Lattnerff1a8e52009-10-29 01:21:20 +0000545
546 // Just mark all destinations executable!
547 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
548 if (isa<IndirectBrInst>(&TI))
549 return true;
550
551#ifndef NDEBUG
552 errs() << "Unknown terminator instruction: " << *TI << '\n';
553#endif
554 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000555}
556
Chris Lattnerc8798002009-11-02 02:33:50 +0000557// visit Implementations - Something changed in this instruction, either an
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558// operand made a transition, or the instruction is newly executable. Change
559// the value type of I to reflect these changes if appropriate. This method
560// makes sure to do the following actions:
561//
562// 1. If a phi node merges two constants in, and has conflicting value coming
563// from different branches, or if the PHI node merges in an overdefined
564// value, then the PHI node becomes overdefined.
565// 2. If a phi node merges only constants in, and they all agree on value, the
566// PHI node becomes a constant value equal to that.
567// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
568// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
569// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
570// 6. If a conditional branch has a value that is constant, make the selected
571// destination executable
572// 7. If a conditional branch has a value that is overdefined, make all
573// successors executable.
574//
575void SCCPSolver::visitPHINode(PHINode &PN) {
576 LatticeVal &PNIV = getValueState(&PN);
577 if (PNIV.isOverdefined()) {
578 // There may be instructions using this PHI node that are not overdefined
579 // themselves. If so, make sure that they know that the PHI node operand
580 // changed.
581 std::multimap<PHINode*, Instruction*>::iterator I, E;
582 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
583 if (I != E) {
584 SmallVector<Instruction*, 16> Users;
585 for (; I != E; ++I) Users.push_back(I->second);
586 while (!Users.empty()) {
587 visit(Users.back());
588 Users.pop_back();
589 }
590 }
591 return; // Quick exit
592 }
593
594 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
595 // and slow us down a lot. Just mark them overdefined.
596 if (PN.getNumIncomingValues() > 64) {
597 markOverdefined(PNIV, &PN);
598 return;
599 }
600
601 // Look at all of the executable operands of the PHI node. If any of them
602 // are overdefined, the PHI becomes overdefined as well. If they are all
603 // constant, and they agree with each other, the PHI becomes the identical
604 // constant. If they are constant and don't agree, the PHI is overdefined.
605 // If there are no executable operands, the PHI remains undefined.
606 //
607 Constant *OperandVal = 0;
608 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
609 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
610 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
611
612 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
613 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnerd3123a72008-08-23 23:36:38 +0000614 markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615 return;
616 }
617
Chris Lattnerc8798002009-11-02 02:33:50 +0000618 if (OperandVal == 0) { // Grab the first value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000619 OperandVal = IV.getConstant();
620 } else { // Another value is being merged in!
621 // There is already a reachable operand. If we conflict with it,
622 // then the PHI node becomes overdefined. If we agree with it, we
623 // can continue on.
624
Chris Lattnerc8798002009-11-02 02:33:50 +0000625 // Check to see if there are two different constants merging.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 if (IV.getConstant() != OperandVal) {
627 // Yes there is. This means the PHI node is not constant.
628 // You must be overdefined poor PHI.
629 //
Chris Lattnerd3123a72008-08-23 23:36:38 +0000630 markOverdefined(&PN); // The PHI node now becomes overdefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 return; // I'm done analyzing you
632 }
633 }
634 }
635 }
636
637 // If we exited the loop, this means that the PHI node only has constant
638 // arguments that agree with each other(and OperandVal is the constant) or
639 // OperandVal is null because there are no defined incoming arguments. If
640 // this is the case, the PHI remains undefined.
641 //
642 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000643 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644}
645
646void SCCPSolver::visitReturnInst(ReturnInst &I) {
647 if (I.getNumOperands() == 0) return; // Ret void
648
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000650 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000651 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000652 return;
653
Chris Lattnercd73be02008-04-23 05:38:20 +0000654 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000656 TrackedRetVals.find(F);
657 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 !TFRVI->second.isOverdefined()) {
659 LatticeVal &IV = getValueState(I.getOperand(0));
660 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000661 return;
662 }
663 }
664
Chris Lattnercd73be02008-04-23 05:38:20 +0000665 // Handle functions that return multiple values.
666 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
667 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000668 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000669 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
670 if (It == TrackedMultipleRetVals.end()) break;
671 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000672 }
Dan Gohman856193b2008-06-20 01:15:44 +0000673 } else if (!TrackedMultipleRetVals.empty() &&
674 I.getNumOperands() == 1 &&
675 isa<StructType>(I.getOperand(0)->getType())) {
676 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
677 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000678 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000679 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
680 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000681 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000682 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000683 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 }
685}
686
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
688 SmallVector<bool, 16> SuccFeasible;
689 getFeasibleSuccessors(TI, SuccFeasible);
690
691 BasicBlock *BB = TI.getParent();
692
Chris Lattnerc8798002009-11-02 02:33:50 +0000693 // Mark all feasible successors executable.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
695 if (SuccFeasible[i])
696 markEdgeExecutable(BB, TI.getSuccessor(i));
697}
698
699void SCCPSolver::visitCastInst(CastInst &I) {
700 Value *V = I.getOperand(0);
701 LatticeVal &VState = getValueState(V);
702 if (VState.isOverdefined()) // Inherit overdefinedness of operand
703 markOverdefined(&I);
704 else if (VState.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000705 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 VState.getConstant(), I.getType()));
707}
708
Dan Gohman856193b2008-06-20 01:15:44 +0000709void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000710 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000711
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000712 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000713 if (isa<UndefValue>(Aggr))
714 return;
715
716 // Currently only handle single-index extractvalues.
717 if (EVI.getNumIndices() != 1) {
718 markOverdefined(&EVI);
719 return;
720 }
721
722 Function *F = 0;
723 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
724 F = CI->getCalledFunction();
725 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
726 F = II->getCalledFunction();
727
728 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
729 // result back!
730 if (F == 0 || TrackedMultipleRetVals.empty()) {
731 markOverdefined(&EVI);
732 return;
733 }
734
Chris Lattnerd3123a72008-08-23 23:36:38 +0000735 // See if we are tracking the result of the callee. If not tracking this
736 // function (for example, it is a declaration) just move to overdefined.
737 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohman856193b2008-06-20 01:15:44 +0000738 markOverdefined(&EVI);
739 return;
740 }
741
742 // Otherwise, the value will be merged in here as a result of CallSite
743 // handling.
744}
745
746void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000747 Value *Aggr = IVI.getAggregateOperand();
748 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000749
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000750 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000751 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000752 return;
753
754 // Currently only handle single-index insertvalues.
755 if (IVI.getNumIndices() != 1) {
756 markOverdefined(&IVI);
757 return;
758 }
Dan Gohman78b2c392008-06-20 16:39:44 +0000759
760 // Currently only handle insertvalue instructions that are in a single-use
761 // chain that builds up a return value.
762 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
763 if (!TmpIVI->hasOneUse()) {
764 markOverdefined(&IVI);
765 return;
766 }
767 const Value *V = *TmpIVI->use_begin();
768 if (isa<ReturnInst>(V))
769 break;
770 TmpIVI = dyn_cast<InsertValueInst>(V);
771 if (!TmpIVI) {
772 markOverdefined(&IVI);
773 return;
774 }
775 }
Dan Gohman856193b2008-06-20 01:15:44 +0000776
777 // See if we are tracking the result of the callee.
778 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000779 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000780 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
781
782 // Merge in the inserted member value.
783 if (It != TrackedMultipleRetVals.end())
784 mergeInValue(It->second, F, getValueState(Val));
785
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000786 // Mark the aggregate result of the IVI overdefined; any tracking that we do
787 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000788 markOverdefined(&IVI);
789}
790
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000791void SCCPSolver::visitSelectInst(SelectInst &I) {
792 LatticeVal &CondValue = getValueState(I.getCondition());
793 if (CondValue.isUndefined())
794 return;
795 if (CondValue.isConstant()) {
796 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
797 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
798 : I.getFalseValue()));
799 return;
800 }
801 }
802
803 // Otherwise, the condition is overdefined or a constant we can't evaluate.
804 // See if we can produce something better than overdefined based on the T/F
805 // value.
806 LatticeVal &TVal = getValueState(I.getTrueValue());
807 LatticeVal &FVal = getValueState(I.getFalseValue());
808
809 // select ?, C, C -> C.
810 if (TVal.isConstant() && FVal.isConstant() &&
811 TVal.getConstant() == FVal.getConstant()) {
812 markConstant(&I, FVal.getConstant());
813 return;
814 }
815
816 if (TVal.isUndefined()) { // select ?, undef, X -> X.
817 mergeInValue(&I, FVal);
818 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
819 mergeInValue(&I, TVal);
820 } else {
821 markOverdefined(&I);
822 }
823}
824
Chris Lattnerc8798002009-11-02 02:33:50 +0000825// Handle BinaryOperators and Shift Instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826void SCCPSolver::visitBinaryOperator(Instruction &I) {
827 LatticeVal &IV = ValueState[&I];
828 if (IV.isOverdefined()) return;
829
830 LatticeVal &V1State = getValueState(I.getOperand(0));
831 LatticeVal &V2State = getValueState(I.getOperand(1));
832
833 if (V1State.isOverdefined() || V2State.isOverdefined()) {
834 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
835 // operand is overdefined.
836 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
837 LatticeVal *NonOverdefVal = 0;
838 if (!V1State.isOverdefined()) {
839 NonOverdefVal = &V1State;
840 } else if (!V2State.isOverdefined()) {
841 NonOverdefVal = &V2State;
842 }
843
844 if (NonOverdefVal) {
845 if (NonOverdefVal->isUndefined()) {
846 // Could annihilate value.
847 if (I.getOpcode() == Instruction::And)
Owen Andersonaac28372009-07-31 20:28:14 +0000848 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersonaac28372009-07-31 20:28:14 +0000850 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 else
Owen Andersonfa089ab2009-07-03 19:42:02 +0000852 markConstant(IV, &I,
Owen Andersonaac28372009-07-31 20:28:14 +0000853 Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 return;
855 } else {
856 if (I.getOpcode() == Instruction::And) {
857 if (NonOverdefVal->getConstant()->isNullValue()) {
858 markConstant(IV, &I, NonOverdefVal->getConstant());
859 return; // X and 0 = 0
860 }
861 } else {
862 if (ConstantInt *CI =
863 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
864 if (CI->isAllOnesValue()) {
865 markConstant(IV, &I, NonOverdefVal->getConstant());
866 return; // X or -1 = -1
867 }
868 }
869 }
870 }
871 }
872
873
874 // If both operands are PHI nodes, it is possible that this instruction has
875 // a constant value, despite the fact that the PHI node doesn't. Check for
876 // this condition now.
877 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
878 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
879 if (PN1->getParent() == PN2->getParent()) {
880 // Since the two PHI nodes are in the same basic block, they must have
881 // entries for the same predecessors. Walk the predecessor list, and
882 // if all of the incoming values are constants, and the result of
883 // evaluating this expression with all incoming value pairs is the
884 // same, then this expression is a constant even though the PHI node
885 // is not a constant!
886 LatticeVal Result;
887 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
888 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
889 BasicBlock *InBlock = PN1->getIncomingBlock(i);
890 LatticeVal &In2 =
891 getValueState(PN2->getIncomingValueForBlock(InBlock));
892
893 if (In1.isOverdefined() || In2.isOverdefined()) {
894 Result.markOverdefined();
895 break; // Cannot fold this operation over the PHI nodes!
896 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000897 Constant *V =
Owen Anderson02b48c32009-07-29 18:55:55 +0000898 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 In2.getConstant());
900 if (Result.isUndefined())
901 Result.markConstant(V);
902 else if (Result.isConstant() && Result.getConstant() != V) {
903 Result.markOverdefined();
904 break;
905 }
906 }
907 }
908
909 // If we found a constant value here, then we know the instruction is
910 // constant despite the fact that the PHI nodes are overdefined.
911 if (Result.isConstant()) {
912 markConstant(IV, &I, Result.getConstant());
913 // Remember that this instruction is virtually using the PHI node
914 // operands.
915 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
916 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
917 return;
918 } else if (Result.isUndefined()) {
919 return;
920 }
921
922 // Okay, this really is overdefined now. Since we might have
923 // speculatively thought that this was not overdefined before, and
924 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
925 // make sure to clean out any entries that we put there, for
926 // efficiency.
927 std::multimap<PHINode*, Instruction*>::iterator It, E;
928 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
929 while (It != E) {
930 if (It->second == &I) {
931 UsersOfOverdefinedPHIs.erase(It++);
932 } else
933 ++It;
934 }
935 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
936 while (It != E) {
937 if (It->second == &I) {
938 UsersOfOverdefinedPHIs.erase(It++);
939 } else
940 ++It;
941 }
942 }
943
944 markOverdefined(IV, &I);
945 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000946 markConstant(IV, &I,
Owen Anderson02b48c32009-07-29 18:55:55 +0000947 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 V2State.getConstant()));
949 }
950}
951
Chris Lattnerc8798002009-11-02 02:33:50 +0000952// Handle ICmpInst instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953void SCCPSolver::visitCmpInst(CmpInst &I) {
954 LatticeVal &IV = ValueState[&I];
955 if (IV.isOverdefined()) return;
956
957 LatticeVal &V1State = getValueState(I.getOperand(0));
958 LatticeVal &V2State = getValueState(I.getOperand(1));
959
960 if (V1State.isOverdefined() || V2State.isOverdefined()) {
961 // If both operands are PHI nodes, it is possible that this instruction has
962 // a constant value, despite the fact that the PHI node doesn't. Check for
963 // this condition now.
964 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
965 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
966 if (PN1->getParent() == PN2->getParent()) {
967 // Since the two PHI nodes are in the same basic block, they must have
968 // entries for the same predecessors. Walk the predecessor list, and
969 // if all of the incoming values are constants, and the result of
970 // evaluating this expression with all incoming value pairs is the
971 // same, then this expression is a constant even though the PHI node
972 // is not a constant!
973 LatticeVal Result;
974 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
975 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
976 BasicBlock *InBlock = PN1->getIncomingBlock(i);
977 LatticeVal &In2 =
978 getValueState(PN2->getIncomingValueForBlock(InBlock));
979
980 if (In1.isOverdefined() || In2.isOverdefined()) {
981 Result.markOverdefined();
982 break; // Cannot fold this operation over the PHI nodes!
983 } else if (In1.isConstant() && In2.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000984 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 In1.getConstant(),
986 In2.getConstant());
987 if (Result.isUndefined())
988 Result.markConstant(V);
989 else if (Result.isConstant() && Result.getConstant() != V) {
990 Result.markOverdefined();
991 break;
992 }
993 }
994 }
995
996 // If we found a constant value here, then we know the instruction is
997 // constant despite the fact that the PHI nodes are overdefined.
998 if (Result.isConstant()) {
999 markConstant(IV, &I, Result.getConstant());
1000 // Remember that this instruction is virtually using the PHI node
1001 // operands.
1002 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
1003 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
1004 return;
1005 } else if (Result.isUndefined()) {
1006 return;
1007 }
1008
1009 // Okay, this really is overdefined now. Since we might have
1010 // speculatively thought that this was not overdefined before, and
1011 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
1012 // make sure to clean out any entries that we put there, for
1013 // efficiency.
1014 std::multimap<PHINode*, Instruction*>::iterator It, E;
1015 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
1016 while (It != E) {
1017 if (It->second == &I) {
1018 UsersOfOverdefinedPHIs.erase(It++);
1019 } else
1020 ++It;
1021 }
1022 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
1023 while (It != E) {
1024 if (It->second == &I) {
1025 UsersOfOverdefinedPHIs.erase(It++);
1026 } else
1027 ++It;
1028 }
1029 }
1030
1031 markOverdefined(IV, &I);
1032 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00001033 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 V1State.getConstant(),
1035 V2State.getConstant()));
1036 }
1037}
1038
1039void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1040 // FIXME : SCCP does not handle vectors properly.
1041 markOverdefined(&I);
1042 return;
1043
1044#if 0
1045 LatticeVal &ValState = getValueState(I.getOperand(0));
1046 LatticeVal &IdxState = getValueState(I.getOperand(1));
1047
1048 if (ValState.isOverdefined() || IdxState.isOverdefined())
1049 markOverdefined(&I);
1050 else if(ValState.isConstant() && IdxState.isConstant())
1051 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1052 IdxState.getConstant()));
1053#endif
1054}
1055
1056void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1057 // FIXME : SCCP does not handle vectors properly.
1058 markOverdefined(&I);
1059 return;
1060#if 0
1061 LatticeVal &ValState = getValueState(I.getOperand(0));
1062 LatticeVal &EltState = getValueState(I.getOperand(1));
1063 LatticeVal &IdxState = getValueState(I.getOperand(2));
1064
1065 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1066 IdxState.isOverdefined())
1067 markOverdefined(&I);
1068 else if(ValState.isConstant() && EltState.isConstant() &&
1069 IdxState.isConstant())
1070 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1071 EltState.getConstant(),
1072 IdxState.getConstant()));
1073 else if (ValState.isUndefined() && EltState.isConstant() &&
1074 IdxState.isConstant())
1075 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1076 EltState.getConstant(),
1077 IdxState.getConstant()));
1078#endif
1079}
1080
1081void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1082 // FIXME : SCCP does not handle vectors properly.
1083 markOverdefined(&I);
1084 return;
1085#if 0
1086 LatticeVal &V1State = getValueState(I.getOperand(0));
1087 LatticeVal &V2State = getValueState(I.getOperand(1));
1088 LatticeVal &MaskState = getValueState(I.getOperand(2));
1089
1090 if (MaskState.isUndefined() ||
1091 (V1State.isUndefined() && V2State.isUndefined()))
1092 return; // Undefined output if mask or both inputs undefined.
1093
1094 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1095 MaskState.isOverdefined()) {
1096 markOverdefined(&I);
1097 } else {
1098 // A mix of constant/undef inputs.
1099 Constant *V1 = V1State.isConstant() ?
1100 V1State.getConstant() : UndefValue::get(I.getType());
1101 Constant *V2 = V2State.isConstant() ?
1102 V2State.getConstant() : UndefValue::get(I.getType());
1103 Constant *Mask = MaskState.isConstant() ?
1104 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1105 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1106 }
1107#endif
1108}
1109
Chris Lattnerc8798002009-11-02 02:33:50 +00001110// Handle getelementptr instructions. If all operands are constants then we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111// can turn this into a getelementptr ConstantExpr.
1112//
1113void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1114 LatticeVal &IV = ValueState[&I];
1115 if (IV.isOverdefined()) return;
1116
1117 SmallVector<Constant*, 8> Operands;
1118 Operands.reserve(I.getNumOperands());
1119
1120 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1121 LatticeVal &State = getValueState(I.getOperand(i));
1122 if (State.isUndefined())
Chris Lattnerc8798002009-11-02 02:33:50 +00001123 return; // Operands are not resolved yet.
1124
1125 if (State.isOverdefined()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 markOverdefined(IV, &I);
1127 return;
1128 }
1129 assert(State.isConstant() && "Unknown state!");
1130 Operands.push_back(State.getConstant());
1131 }
1132
1133 Constant *Ptr = Operands[0];
Chris Lattnerc8798002009-11-02 02:33:50 +00001134 Operands.erase(Operands.begin()); // Erase the pointer from idx list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001135
Owen Anderson02b48c32009-07-29 18:55:55 +00001136 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 Operands.size()));
1138}
1139
1140void SCCPSolver::visitStoreInst(Instruction &SI) {
1141 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1142 return;
1143 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1144 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1145 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1146
1147 // Get the value we are storing into the global.
1148 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1149
1150 mergeInValue(I->second, GV, PtrVal);
1151 if (I->second.isOverdefined())
1152 TrackedGlobals.erase(I); // No need to keep tracking this!
1153}
1154
1155
1156// Handle load instructions. If the operand is a constant pointer to a constant
1157// global, we can replace the load with the loaded constant value!
1158void SCCPSolver::visitLoadInst(LoadInst &I) {
1159 LatticeVal &IV = ValueState[&I];
1160 if (IV.isOverdefined()) return;
1161
1162 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1163 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1164 if (PtrVal.isConstant() && !I.isVolatile()) {
1165 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001166 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +00001167 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 // load null -> null
Owen Andersonaac28372009-07-31 20:28:14 +00001169 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 return;
1171 }
1172
1173 // Transform load (constant global) into the value loaded.
1174 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1175 if (GV->isConstant()) {
Duncan Sands54e70f62009-03-21 21:27:31 +00001176 if (GV->hasDefinitiveInitializer()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177 markConstant(IV, &I, GV->getInitializer());
1178 return;
1179 }
1180 } else if (!TrackedGlobals.empty()) {
1181 // If we are tracking this global, merge in the known value for it.
1182 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1183 TrackedGlobals.find(GV);
1184 if (It != TrackedGlobals.end()) {
1185 mergeInValue(IV, &I, It->second);
1186 return;
1187 }
1188 }
1189 }
1190
1191 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1192 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1193 if (CE->getOpcode() == Instruction::GetElementPtr)
1194 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +00001195 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 if (Constant *V =
Dan Gohmanf49f7b02009-10-05 16:36:26 +00001197 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 markConstant(IV, &I, V);
1199 return;
1200 }
1201 }
1202
1203 // Otherwise we cannot say for certain what value this load will produce.
1204 // Bail out.
1205 markOverdefined(IV, &I);
1206}
1207
1208void SCCPSolver::visitCallSite(CallSite CS) {
1209 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001211
1212 // The common case is that we aren't tracking the callee, either because we
1213 // are not doing interprocedural analysis or the callee is indirect, or is
1214 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001215 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001216CallOverdefined:
1217 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001218 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001219
1220 // Otherwise, if we have a single return value case, and if the function is
1221 // a declaration, maybe we can constant fold it.
1222 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1223 canConstantFoldCallTo(F)) {
1224
1225 SmallVector<Constant*, 8> Operands;
1226 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1227 AI != E; ++AI) {
1228 LatticeVal &State = getValueState(*AI);
1229 if (State.isUndefined())
1230 return; // Operands are not resolved yet.
1231 else if (State.isOverdefined()) {
1232 markOverdefined(I);
1233 return;
1234 }
1235 assert(State.isConstant() && "Unknown state!");
1236 Operands.push_back(State.getConstant());
1237 }
1238
1239 // If we can constant fold this, mark the result of the call as a
1240 // constant.
Nick Lewyckye9279352009-05-28 04:08:10 +00001241 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001242 markConstant(I, C);
1243 return;
1244 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001246
1247 // Otherwise, we don't know anything about this call, mark it overdefined.
1248 markOverdefined(I);
1249 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 }
1251
Chris Lattnercd73be02008-04-23 05:38:20 +00001252 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001253 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1254 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001255 // If so, propagate the return value of the callee into this call result.
1256 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001257 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001258 // Check to see if we're tracking this callee, if not, handle it in the
1259 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001260 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1261 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001262 if (TMRVI == TrackedMultipleRetVals.end())
1263 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001264
1265 // Need to mark as overdefined, otherwise it stays undefined which
1266 // creates extractvalue undef, <idx>
1267 markOverdefined(I);
Chris Lattnercd73be02008-04-23 05:38:20 +00001268 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001269 // into this call site. We do this by walking all the uses. Single-index
1270 // ExtractValueInst uses can be tracked; anything more complicated is
1271 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001272 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1273 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001274 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1275 if (EVI->getNumIndices() == 1) {
1276 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001277 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001278 continue;
1279 }
1280 }
1281 // The aggregate value is used in a way not handled here. Assume nothing.
1282 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001283 }
Dan Gohman856193b2008-06-20 01:15:44 +00001284 } else {
1285 // Otherwise we're not tracking this callee, so handle it in the
1286 // common path above.
1287 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001288 }
1289
1290 // Finally, if this is the first call to the function hit, mark its entry
1291 // block executable.
1292 if (!BBExecutable.count(F->begin()))
1293 MarkBlockExecutable(F->begin());
1294
1295 // Propagate information from this call site into the callee.
1296 CallSite::arg_iterator CAI = CS.arg_begin();
1297 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1298 AI != E; ++AI, ++CAI) {
1299 LatticeVal &IV = ValueState[AI];
Edwin Török129b2d12009-09-24 18:33:42 +00001300 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
Edwin Törökd5435372009-09-24 09:47:18 +00001301 IV.markOverdefined();
1302 continue;
1303 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001304 if (!IV.isOverdefined())
1305 mergeInValue(IV, AI, getValueState(*CAI));
1306 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307}
1308
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309void SCCPSolver::Solve() {
1310 // Process the work lists until they are empty!
1311 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1312 !OverdefinedInstWorkList.empty()) {
Chris Lattnerc8798002009-11-02 02:33:50 +00001313 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 while (!OverdefinedInstWorkList.empty()) {
1315 Value *I = OverdefinedInstWorkList.back();
1316 OverdefinedInstWorkList.pop_back();
1317
Dan Gohmandff8d172009-08-17 15:25:05 +00001318 DEBUG(errs() << "\nPopped off OI-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319
1320 // "I" got into the work list because it either made the transition from
1321 // bottom to constant
1322 //
1323 // Anything on this worklist that is overdefined need not be visited
1324 // since all of its users will have already been marked as overdefined
Chris Lattnerc8798002009-11-02 02:33:50 +00001325 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326 //
1327 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1328 UI != E; ++UI)
1329 OperandChangedState(*UI);
1330 }
Chris Lattnerc8798002009-11-02 02:33:50 +00001331
1332 // Process the instruction work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 while (!InstWorkList.empty()) {
1334 Value *I = InstWorkList.back();
1335 InstWorkList.pop_back();
1336
Dan Gohmandff8d172009-08-17 15:25:05 +00001337 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338
1339 // "I" got into the work list because it either made the transition from
1340 // bottom to constant
1341 //
1342 // Anything on this worklist that is overdefined need not be visited
1343 // since all of its users will have already been marked as overdefined.
Chris Lattnerc8798002009-11-02 02:33:50 +00001344 // Update all of the users of this instruction's value.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 //
1346 if (!getValueState(I).isOverdefined())
1347 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1348 UI != E; ++UI)
1349 OperandChangedState(*UI);
1350 }
1351
Chris Lattnerc8798002009-11-02 02:33:50 +00001352 // Process the basic block work list.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 while (!BBWorkList.empty()) {
1354 BasicBlock *BB = BBWorkList.back();
1355 BBWorkList.pop_back();
1356
Dan Gohmandff8d172009-08-17 15:25:05 +00001357 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358
1359 // Notify all instructions in this basic block that they are newly
1360 // executable.
1361 visit(BB);
1362 }
1363 }
1364}
1365
1366/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1367/// that branches on undef values cannot reach any of their successors.
1368/// However, this is not a safe assumption. After we solve dataflow, this
1369/// method should be use to handle this. If this returns true, the solver
1370/// should be rerun.
1371///
1372/// This method handles this by finding an unresolved branch and marking it one
1373/// of the edges from the block as being feasible, even though the condition
1374/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1375/// CFG and only slightly pessimizes the analysis results (by marking one,
1376/// potentially infeasible, edge feasible). This cannot usefully modify the
1377/// constraints on the condition of the branch, as that would impact other users
1378/// of the value.
1379///
1380/// This scan also checks for values that use undefs, whose results are actually
1381/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1382/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1383/// even if X isn't defined.
1384bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1385 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1386 if (!BBExecutable.count(BB))
1387 continue;
1388
1389 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1390 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001391 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392
1393 LatticeVal &LV = getValueState(I);
1394 if (!LV.isUndefined()) continue;
1395
1396 // Get the lattice values of the first two operands for use below.
1397 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1398 LatticeVal Op1LV;
1399 if (I->getNumOperands() == 2) {
1400 // If this is a two-operand instruction, and if both operands are
1401 // undefs, the result stays undef.
1402 Op1LV = getValueState(I->getOperand(1));
1403 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1404 continue;
1405 }
1406
1407 // If this is an instructions whose result is defined even if the input is
1408 // not fully defined, propagate the information.
1409 const Type *ITy = I->getType();
1410 switch (I->getOpcode()) {
1411 default: break; // Leave the instruction as an undef.
1412 case Instruction::ZExt:
1413 // After a zero extend, we know the top part is zero. SExt doesn't have
1414 // to be handled here, because we don't know whether the top part is 1's
1415 // or 0's.
1416 assert(Op0LV.isUndefined());
Owen Andersonaac28372009-07-31 20:28:14 +00001417 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 return true;
1419 case Instruction::Mul:
1420 case Instruction::And:
1421 // undef * X -> 0. X could be zero.
1422 // undef & X -> 0. X could be zero.
Owen Andersonaac28372009-07-31 20:28:14 +00001423 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 return true;
1425
1426 case Instruction::Or:
1427 // undef | X -> -1. X could be -1.
1428 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001429 markForcedConstant(LV, I,
Owen Andersonaac28372009-07-31 20:28:14 +00001430 Constant::getAllOnesValue(PTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 else
Owen Andersonaac28372009-07-31 20:28:14 +00001432 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 return true;
1434
1435 case Instruction::SDiv:
1436 case Instruction::UDiv:
1437 case Instruction::SRem:
1438 case Instruction::URem:
1439 // X / undef -> undef. No change.
1440 // X % undef -> undef. No change.
1441 if (Op1LV.isUndefined()) break;
1442
1443 // undef / X -> 0. X could be maxint.
1444 // undef % X -> 0. X could be 1.
Owen Andersonaac28372009-07-31 20:28:14 +00001445 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 return true;
1447
1448 case Instruction::AShr:
1449 // undef >>s X -> undef. No change.
1450 if (Op0LV.isUndefined()) break;
1451
1452 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1453 if (Op0LV.isConstant())
1454 markForcedConstant(LV, I, Op0LV.getConstant());
1455 else
1456 markOverdefined(LV, I);
1457 return true;
1458 case Instruction::LShr:
1459 case Instruction::Shl:
1460 // undef >> X -> undef. No change.
1461 // undef << X -> undef. No change.
1462 if (Op0LV.isUndefined()) break;
1463
1464 // X >> undef -> 0. X could be 0.
1465 // X << undef -> 0. X could be 0.
Owen Andersonaac28372009-07-31 20:28:14 +00001466 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 return true;
1468 case Instruction::Select:
1469 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1470 if (Op0LV.isUndefined()) {
1471 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1472 Op1LV = getValueState(I->getOperand(2));
1473 } else if (Op1LV.isUndefined()) {
1474 // c ? undef : undef -> undef. No change.
1475 Op1LV = getValueState(I->getOperand(2));
1476 if (Op1LV.isUndefined())
1477 break;
1478 // Otherwise, c ? undef : x -> x.
1479 } else {
1480 // Leave Op1LV as Operand(1)'s LatticeValue.
1481 }
1482
1483 if (Op1LV.isConstant())
1484 markForcedConstant(LV, I, Op1LV.getConstant());
1485 else
1486 markOverdefined(LV, I);
1487 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001488 case Instruction::Call:
1489 // If a call has an undef result, it is because it is constant foldable
1490 // but one of the inputs was undef. Just force the result to
1491 // overdefined.
1492 markOverdefined(LV, I);
1493 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 }
1495 }
1496
1497 TerminatorInst *TI = BB->getTerminator();
1498 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1499 if (!BI->isConditional()) continue;
1500 if (!getValueState(BI->getCondition()).isUndefined())
1501 continue;
1502 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001503 if (SI->getNumSuccessors() < 2) // no cases
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001504 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 if (!getValueState(SI->getCondition()).isUndefined())
1506 continue;
1507 } else {
1508 continue;
1509 }
1510
Chris Lattner6186e8c2008-01-28 00:32:30 +00001511 // If the edge to the second successor isn't thought to be feasible yet,
1512 // mark it so now. We pick the second one so that this goes to some
1513 // enumerated value in a switch instead of going to the default destination.
1514 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 continue;
1516
1517 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1518 // and return. This will make other blocks reachable, which will allow new
1519 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001520 markEdgeExecutable(BB, TI->getSuccessor(1));
1521
1522 // This must be a conditional branch of switch on undef. At this point,
1523 // force the old terminator to branch to the first successor. This is
1524 // required because we are now influencing the dataflow of the function with
1525 // the assumption that this edge is taken. If we leave the branch condition
1526 // as undef, then further analysis could think the undef went another way
1527 // leading to an inconsistent set of conclusions.
1528 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattneradaf7332009-11-02 02:30:06 +00001529 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001530 } else {
1531 SwitchInst *SI = cast<SwitchInst>(TI);
1532 SI->setCondition(SI->getCaseValue(1));
1533 }
1534
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535 return true;
1536 }
1537
1538 return false;
1539}
1540
1541
1542namespace {
1543 //===--------------------------------------------------------------------===//
1544 //
1545 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1546 /// Sparse Conditional Constant Propagator.
1547 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001548 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001550 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551
1552 // runOnFunction - Run the Sparse Conditional Constant Propagation
1553 // algorithm, and return true if the function was modified.
1554 //
1555 bool runOnFunction(Function &F);
1556
1557 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1558 AU.setPreservesCFG();
1559 }
1560 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001561} // end anonymous namespace
1562
Dan Gohman089efff2008-05-13 00:00:25 +00001563char SCCP::ID = 0;
1564static RegisterPass<SCCP>
1565X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566
Chris Lattnerc8798002009-11-02 02:33:50 +00001567// createSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001568FunctionPass *llvm::createSCCPPass() {
1569 return new SCCP();
1570}
1571
Chris Lattner14513dc2009-11-02 02:47:51 +00001572static void DeleteInstructionInBlock(BasicBlock *BB) {
1573 DEBUG(errs() << " BasicBlock Dead:" << *BB);
1574 ++NumDeadBlocks;
1575
1576 // Delete the instructions backwards, as it has a reduced likelihood of
1577 // having to update as many def-use and use-def chains.
1578 while (!isa<TerminatorInst>(BB->begin())) {
1579 Instruction *I = --BasicBlock::iterator(BB->getTerminator());
1580
1581 if (!I->use_empty())
1582 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1583 BB->getInstList().erase(I);
1584 ++NumInstRemoved;
1585 }
1586}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001587
1588// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1589// and return true if the function was modified.
1590//
1591bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001592 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593 SCCPSolver Solver;
1594
1595 // Mark the first block of the function as being executable.
1596 Solver.MarkBlockExecutable(F.begin());
1597
1598 // Mark all arguments to the function as being overdefined.
1599 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1600 Solver.markOverdefined(AI);
1601
1602 // Solve for constants.
1603 bool ResolvedUndefs = true;
1604 while (ResolvedUndefs) {
1605 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001606 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1608 }
1609
1610 bool MadeChanges = false;
1611
1612 // If we decided that there are basic blocks that are dead in this function,
1613 // delete their contents now. Note that we cannot actually delete the blocks,
1614 // as we cannot modify the CFG of the function.
1615 //
Bill Wendling03488ae2008-08-14 23:05:24 +00001616 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617
Chris Lattner14513dc2009-11-02 02:47:51 +00001618 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001619 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001620 DeleteInstructionInBlock(BB);
1621 MadeChanges = true;
1622 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001624
1625 // Iterate over all of the instructions in a function, replacing them with
1626 // constants if we have found them to be of constant values.
1627 //
1628 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1629 Instruction *Inst = BI++;
1630 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1631 continue;
1632
1633 LatticeVal &IV = Values[Inst];
1634 if (!IV.isConstant() && !IV.isUndefined())
1635 continue;
1636
1637 Constant *Const = IV.isConstant()
1638 ? IV.getConstant() : UndefValue::get(Inst->getType());
1639 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1640
1641 // Replaces all of the uses of a variable with uses of the constant.
1642 Inst->replaceAllUsesWith(Const);
1643
1644 // Delete the instruction.
1645 Inst->eraseFromParent();
1646
1647 // Hey, we just changed something!
1648 MadeChanges = true;
1649 ++NumInstRemoved;
1650 }
1651 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652
1653 return MadeChanges;
1654}
1655
1656namespace {
1657 //===--------------------------------------------------------------------===//
1658 //
1659 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1660 /// Constant Propagation.
1661 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001662 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001664 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 bool runOnModule(Module &M);
1666 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667} // end anonymous namespace
1668
Dan Gohman089efff2008-05-13 00:00:25 +00001669char IPSCCP::ID = 0;
1670static RegisterPass<IPSCCP>
1671Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1672
Chris Lattnerc8798002009-11-02 02:33:50 +00001673// createIPSCCPPass - This is the public interface to this file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674ModulePass *llvm::createIPSCCPPass() {
1675 return new IPSCCP();
1676}
1677
1678
1679static bool AddressIsTaken(GlobalValue *GV) {
1680 // Delete any dead constantexpr klingons.
1681 GV->removeDeadConstantUsers();
1682
1683 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1684 UI != E; ++UI)
1685 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1686 if (SI->getOperand(0) == GV || SI->isVolatile())
1687 return true; // Storing addr of GV.
1688 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1689 // Make sure we are calling the function, not passing the address.
Chris Lattner2f487502009-11-01 06:11:53 +00001690 if (UI.getOperandNo() != 0)
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001691 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001692 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1693 if (LI->isVolatile())
1694 return true;
Chris Lattner2f487502009-11-01 06:11:53 +00001695 } else if (isa<BlockAddress>(*UI)) {
1696 // blockaddress doesn't take the address of the function, it takes addr
1697 // of label.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 } else {
1699 return true;
1700 }
1701 return false;
1702}
1703
1704bool IPSCCP::runOnModule(Module &M) {
1705 SCCPSolver Solver;
1706
1707 // Loop over all functions, marking arguments to those with their addresses
1708 // taken or that are external as overdefined.
1709 //
1710 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001711 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 if (!F->isDeclaration())
1713 Solver.MarkBlockExecutable(F->begin());
1714 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1715 AI != E; ++AI)
1716 Solver.markOverdefined(AI);
1717 } else {
1718 Solver.AddTrackedFunction(F);
1719 }
1720
1721 // Loop over global variables. We inform the solver about any internal global
1722 // variables that do not have their 'addresses taken'. If they don't have
1723 // their addresses taken, we can propagate constants through them.
1724 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1725 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001726 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 Solver.TrackValueOfGlobalVariable(G);
1728
1729 // Solve for constants.
1730 bool ResolvedUndefs = true;
1731 while (ResolvedUndefs) {
1732 Solver.Solve();
1733
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001734 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001735 ResolvedUndefs = false;
1736 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1737 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1738 }
1739
1740 bool MadeChanges = false;
1741
1742 // Iterate over all of the instructions in the module, replacing them with
1743 // constants if we have found them to be of constant values.
1744 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001745 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling03488ae2008-08-14 23:05:24 +00001746 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747
1748 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1749 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1750 AI != E; ++AI)
1751 if (!AI->use_empty()) {
1752 LatticeVal &IV = Values[AI];
1753 if (IV.isConstant() || IV.isUndefined()) {
1754 Constant *CST = IV.isConstant() ?
Owen Andersonb99ecca2009-07-30 23:03:37 +00001755 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001756 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757
1758 // Replaces all of the uses of a variable with uses of the
1759 // constant.
1760 AI->replaceAllUsesWith(CST);
1761 ++IPNumArgsElimed;
1762 }
1763 }
1764
Chris Lattner14513dc2009-11-02 02:47:51 +00001765 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
Chris Lattner317e6b62008-08-23 23:39:31 +00001766 if (!Solver.isBlockExecutable(BB)) {
Chris Lattner14513dc2009-11-02 02:47:51 +00001767 DeleteInstructionInBlock(BB);
1768 MadeChanges = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770 TerminatorInst *TI = BB->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001771 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1772 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001773 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001774 TI->getSuccessor(i)->removePredecessor(BB);
1775 }
1776 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001777 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Chris Lattner14513dc2009-11-02 02:47:51 +00001778 TI->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779
1780 if (&*BB != &F->front())
1781 BlocksToErase.push_back(BB);
1782 else
Owen Anderson35b47072009-08-13 21:58:54 +00001783 new UnreachableInst(M.getContext(), BB);
Chris Lattner14513dc2009-11-02 02:47:51 +00001784 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 }
Chris Lattner14513dc2009-11-02 02:47:51 +00001786
1787 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1788 Instruction *Inst = BI++;
1789 if (Inst->getType()->isVoidTy())
1790 continue;
1791
1792 LatticeVal &IV = Values[Inst];
1793 if (!IV.isConstant() && !IV.isUndefined())
1794 continue;
1795
1796 Constant *Const = IV.isConstant()
1797 ? IV.getConstant() : UndefValue::get(Inst->getType());
1798 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
1799
1800 // Replaces all of the uses of a variable with uses of the
1801 // constant.
1802 Inst->replaceAllUsesWith(Const);
1803
1804 // Delete the instruction.
1805 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1806 Inst->eraseFromParent();
1807
1808 // Hey, we just changed something!
1809 MadeChanges = true;
1810 ++IPNumInstRemoved;
1811 }
1812 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813
1814 // Now that all instructions in the function are constant folded, erase dead
1815 // blocks, because we can now use ConstantFoldTerminator to get rid of
1816 // in-edges.
1817 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1818 // If there are any PHI nodes in this successor, drop entries for BB now.
1819 BasicBlock *DeadBB = BlocksToErase[i];
1820 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821 Instruction *I = cast<Instruction>(DeadBB->use_back());
1822 bool Folded = ConstantFoldTerminator(I->getParent());
1823 if (!Folded) {
1824 // The constant folder may not have been able to fold the terminator
1825 // if this is a branch or switch on undef. Fold it manually as a
1826 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001827#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1829 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1830 "Branch should be foldable!");
1831 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1832 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1833 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001834 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 }
Devang Patele92c16d2008-11-21 01:52:59 +00001836#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001837
1838 // Make this an uncond branch to the first successor.
1839 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001840 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001841
1842 // Remove entries in successor phi nodes to remove edges.
1843 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1844 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1845
1846 // Remove the old terminator.
1847 TI->eraseFromParent();
1848 }
1849 }
1850
1851 // Finally, delete the basic block.
1852 F->getBasicBlockList().erase(DeadBB);
1853 }
1854 BlocksToErase.clear();
1855 }
1856
1857 // If we inferred constant or undef return values for a function, we replaced
1858 // all call uses with the inferred value. This means we don't need to bother
1859 // actually returning anything from the function. Replace all return
1860 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001861 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001862 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1864 E = RV.end(); I != E; ++I)
1865 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001866 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867 Function *F = I->first;
1868 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1869 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1870 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001871 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872 }
1873
1874 // If we infered constant or undef values for globals variables, we can delete
1875 // the global and any stores that remain to it.
1876 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1877 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1878 E = TG.end(); I != E; ++I) {
1879 GlobalVariable *GV = I->first;
1880 assert(!I->second.isOverdefined() &&
1881 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001882 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 while (!GV->use_empty()) {
1884 StoreInst *SI = cast<StoreInst>(GV->use_back());
1885 SI->eraseFromParent();
1886 }
1887 M.getGlobalList().erase(GV);
1888 ++IPNumGlobalConst;
1889 }
1890
1891 return MadeChanges;
1892}