blob: 4701d2f740564217f3f7a29686d1ff8765fdd892 [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//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
24#define DEBUG_TYPE "sccp"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/IPO.h"
27#include "llvm/Constants.h"
28#include "llvm/DerivedTypes.h"
29#include "llvm/Instructions.h"
Owen Andersonfa089ab2009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000031#include "llvm/Pass.h"
32#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000033#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohman856193b2008-06-20 01:15:44 +000034#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include "llvm/Transforms/Utils/Local.h"
36#include "llvm/Support/CallSite.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/Support/InstVisitor.h"
Daniel Dunbar005975c2009-07-25 00:23:56 +000040#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000042#include "llvm/ADT/DenseSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043#include "llvm/ADT/SmallSet.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/STLExtras.h"
47#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000048#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049using namespace llvm;
50
51STATISTIC(NumInstRemoved, "Number of instructions removed");
52STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
53
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000054STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
56STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
57STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
58
59namespace {
60/// LatticeVal class - This class represents the different lattice values that
61/// an LLVM value may occupy. It is a simple class with value semantics.
62///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +000063class LatticeVal {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064 enum {
65 /// undefined - This LLVM Value has no known value yet.
66 undefined,
67
68 /// constant - This LLVM Value has a specific constant value.
69 constant,
70
71 /// forcedconstant - This LLVM Value was thought to be undef until
72 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
73 /// with another (different) constant, it goes to overdefined, instead of
74 /// asserting.
75 forcedconstant,
76
77 /// overdefined - This instruction is not known to be constant, and we know
78 /// it has a value.
79 overdefined
80 } LatticeValue; // The current lattice position
81
82 Constant *ConstantVal; // If Constant value, the current value
83public:
84 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
85
86 // markOverdefined - Return true if this is a new status to be in...
87 inline bool markOverdefined() {
88 if (LatticeValue != overdefined) {
89 LatticeValue = overdefined;
90 return true;
91 }
92 return false;
93 }
94
95 // markConstant - Return true if this is a new status for us.
96 inline bool markConstant(Constant *V) {
97 if (LatticeValue != constant) {
98 if (LatticeValue == undefined) {
99 LatticeValue = constant;
100 assert(V && "Marking constant with NULL");
101 ConstantVal = V;
102 } else {
103 assert(LatticeValue == forcedconstant &&
104 "Cannot move from overdefined to constant!");
105 // Stay at forcedconstant if the constant is the same.
106 if (V == ConstantVal) return false;
107
108 // Otherwise, we go to overdefined. Assumptions made based on the
109 // forced value are possibly wrong. Assuming this is another constant
110 // could expose a contradiction.
111 LatticeValue = overdefined;
112 }
113 return true;
114 } else {
115 assert(ConstantVal == V && "Marking constant with different value");
116 }
117 return false;
118 }
119
120 inline void markForcedConstant(Constant *V) {
121 assert(LatticeValue == undefined && "Can't force a defined value!");
122 LatticeValue = forcedconstant;
123 ConstantVal = V;
124 }
125
126 inline bool isUndefined() const { return LatticeValue == undefined; }
127 inline bool isConstant() const {
128 return LatticeValue == constant || LatticeValue == forcedconstant;
129 }
130 inline bool isOverdefined() const { return LatticeValue == overdefined; }
131
132 inline Constant *getConstant() const {
133 assert(isConstant() && "Cannot get the constant of a non-constant!");
134 return ConstantVal;
135 }
136};
137
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138//===----------------------------------------------------------------------===//
139//
140/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
141/// Constant Propagation.
142///
143class SCCPSolver : public InstVisitor<SCCPSolver> {
Owen Anderson5349f052009-07-06 23:00:19 +0000144 LLVMContext *Context;
Chris Lattnerd3123a72008-08-23 23:36:38 +0000145 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000146 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147
148 /// GlobalValue - If we are tracking any values for the contents of a global
149 /// variable, we keep a mapping from the constant accessor to the element of
150 /// the global, to the currently known value. If the value becomes
151 /// overdefined, it's entry is simply removed from this map.
152 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
153
Devang Pateladd320d2008-03-11 05:46:42 +0000154 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000155 /// value out of a function, it will have an entry in this map, indicating
156 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000157 DenseMap<Function*, LatticeVal> TrackedRetVals;
158
159 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
160 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000161 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162
163 // The reason for two worklists is that overdefined is the lowest state
164 // on the lattice, and moving things to overdefined as fast as possible
165 // makes SCCP converge much faster.
166 // By having a separate worklist, we accomplish this because everything
167 // possibly overdefined will become overdefined at the soonest possible
168 // point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000169 SmallVector<Value*, 64> OverdefinedInstWorkList;
170 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171
172
Chris Lattnerd3123a72008-08-23 23:36:38 +0000173 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000174
175 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
176 /// overdefined, despite the fact that the PHI node is overdefined.
177 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
178
179 /// KnownFeasibleEdges - Entries in this set are edges which have already had
180 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000181 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
182 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183public:
Owen Anderson5349f052009-07-06 23:00:19 +0000184 void setContext(LLVMContext *C) { Context = C; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185
186 /// MarkBlockExecutable - This method can be used by clients to mark all of
187 /// the blocks that are known to be intrinsically live in the processed unit.
188 void MarkBlockExecutable(BasicBlock *BB) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000189 DEBUG(errs() << "Marking Block Executable: " << BB->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 BBExecutable.insert(BB); // Basic block is executable!
191 BBWorkList.push_back(BB); // Add the block to the work list!
192 }
193
194 /// TrackValueOfGlobalVariable - Clients can use this method to
195 /// inform the SCCPSolver that it should track loads and stores to the
196 /// specified global variable if it can. This is only legal to call if
197 /// performing Interprocedural SCCP.
198 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
199 const Type *ElTy = GV->getType()->getElementType();
200 if (ElTy->isFirstClassType()) {
201 LatticeVal &IV = TrackedGlobals[GV];
202 if (!isa<UndefValue>(GV->getInitializer()))
203 IV.markConstant(GV->getInitializer());
204 }
205 }
206
207 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
208 /// and out of the specified function (which cannot have its address taken),
209 /// this method must be called.
210 void AddTrackedFunction(Function *F) {
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000211 assert(F->hasLocalLinkage() && "Can only track internal functions!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000213 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000215 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
216 LatticeVal()));
217 } else
218 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 }
220
221 /// Solve - Solve for constants and executable blocks.
222 ///
223 void Solve();
224
225 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
226 /// that branches on undef values cannot reach any of their successors.
227 /// However, this is not a safe assumption. After we solve dataflow, this
228 /// method should be use to handle this. If this returns true, the solver
229 /// should be rerun.
230 bool ResolvedUndefsIn(Function &F);
231
Chris Lattner317e6b62008-08-23 23:39:31 +0000232 bool isBlockExecutable(BasicBlock *BB) const {
233 return BBExecutable.count(BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 }
235
236 /// getValueMapping - Once we have solved for constants, return the mapping of
237 /// LLVM values to LatticeVals.
Bill Wendling03488ae2008-08-14 23:05:24 +0000238 std::map<Value*, LatticeVal> &getValueMapping() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 return ValueState;
240 }
241
Devang Pateladd320d2008-03-11 05:46:42 +0000242 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000244 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
245 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 }
247
248 /// getTrackedGlobals - Get and return the set of inferred initializers for
249 /// global variables.
250 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
251 return TrackedGlobals;
252 }
253
254 inline void markOverdefined(Value *V) {
255 markOverdefined(ValueState[V], V);
256 }
257
258private:
259 // markConstant - Make a value be marked as "constant". If the value
260 // is not already a constant, add it to the instruction work list so that
261 // the users of the instruction are updated later.
262 //
263 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
264 if (IV.markConstant(C)) {
Dan Gohmandff8d172009-08-17 15:25:05 +0000265 DEBUG(errs() << "markConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266 InstWorkList.push_back(V);
267 }
268 }
269
270 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
271 IV.markForcedConstant(C);
Dan Gohmandff8d172009-08-17 15:25:05 +0000272 DEBUG(errs() << "markForcedConstant: " << *C << ": " << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 InstWorkList.push_back(V);
274 }
275
276 inline void markConstant(Value *V, Constant *C) {
277 markConstant(ValueState[V], V, C);
278 }
279
280 // markOverdefined - Make a value be marked as "overdefined". If the
281 // value is not already overdefined, add it to the overdefined instruction
282 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 inline void markOverdefined(LatticeVal &IV, Value *V) {
284 if (IV.markOverdefined()) {
Daniel Dunbar005975c2009-07-25 00:23:56 +0000285 DEBUG(errs() << "markOverdefined: ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 if (Function *F = dyn_cast<Function>(V))
Daniel Dunbar005975c2009-07-25 00:23:56 +0000287 errs() << "Function '" << F->getName() << "'\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 else
Dan Gohmandff8d172009-08-17 15:25:05 +0000289 errs() << *V << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 // Only instructions go on the work list
291 OverdefinedInstWorkList.push_back(V);
292 }
293 }
294
295 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
296 if (IV.isOverdefined() || MergeWithV.isUndefined())
297 return; // Noop.
298 if (MergeWithV.isOverdefined())
299 markOverdefined(IV, V);
300 else if (IV.isUndefined())
301 markConstant(IV, V, MergeWithV.getConstant());
302 else if (IV.getConstant() != MergeWithV.getConstant())
303 markOverdefined(IV, V);
304 }
305
306 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
307 return mergeInValue(ValueState[V], V, MergeWithV);
308 }
309
310
311 // getValueState - Return the LatticeVal object that corresponds to the value.
312 // This function is necessary because not all values should start out in the
313 // underdefined state... Argument's should be overdefined, and
314 // constants should be marked as constants. If a value is not known to be an
315 // Instruction object, then use this accessor to get its value from the map.
316 //
317 inline LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000318 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 if (I != ValueState.end()) return I->second; // Common case, in the map
320
321 if (Constant *C = dyn_cast<Constant>(V)) {
322 if (isa<UndefValue>(V)) {
323 // Nothing to do, remain undefined.
324 } else {
325 LatticeVal &LV = ValueState[C];
326 LV.markConstant(C); // Constants are constant
327 return LV;
328 }
329 }
330 // All others are underdefined by default...
331 return ValueState[V];
332 }
333
334 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
335 // work list if it is not already executable...
336 //
337 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
338 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
339 return; // This edge is already known to be executable!
340
341 if (BBExecutable.count(Dest)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +0000342 DEBUG(errs() << "Marking Edge Executable: " << Source->getName()
343 << " -> " << Dest->getName() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344
345 // The destination is already executable, but we just made an edge
346 // feasible that wasn't before. Revisit the PHI nodes in the block
347 // because they have potentially new operands.
348 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
349 visitPHINode(*cast<PHINode>(I));
350
351 } else {
352 MarkBlockExecutable(Dest);
353 }
354 }
355
356 // getFeasibleSuccessors - Return a vector of booleans to indicate which
357 // successors are reachable from a given terminator instruction.
358 //
359 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
360
361 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
362 // block to the 'To' basic block is currently feasible...
363 //
364 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
365
366 // OperandChangedState - This method is invoked on all of the users of an
367 // instruction that was just changed state somehow.... Based on this
368 // information, we need to update the specified user of this instruction.
369 //
370 void OperandChangedState(User *U) {
371 // Only instructions use other variable values!
372 Instruction &I = cast<Instruction>(*U);
373 if (BBExecutable.count(I.getParent())) // Inst is executable?
374 visit(I);
375 }
376
377private:
378 friend class InstVisitor<SCCPSolver>;
379
380 // visit implementations - Something changed in this instruction... Either an
381 // operand made a transition, or the instruction is newly executable. Change
382 // the value type of I to reflect these changes if appropriate.
383 //
384 void visitPHINode(PHINode &I);
385
386 // Terminators
387 void visitReturnInst(ReturnInst &I);
388 void visitTerminatorInst(TerminatorInst &TI);
389
390 void visitCastInst(CastInst &I);
391 void visitSelectInst(SelectInst &I);
392 void visitBinaryOperator(Instruction &I);
393 void visitCmpInst(CmpInst &I);
394 void visitExtractElementInst(ExtractElementInst &I);
395 void visitInsertElementInst(InsertElementInst &I);
396 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000397 void visitExtractValueInst(ExtractValueInst &EVI);
398 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
400 // Instructions that cannot be folded away...
401 void visitStoreInst (Instruction &I);
402 void visitLoadInst (LoadInst &I);
403 void visitGetElementPtrInst(GetElementPtrInst &I);
Victor Hernandez93946082009-10-24 04:23:03 +0000404 void visitCallInst (CallInst &I) {
405 if (isFreeCall(&I))
406 return;
Chris Lattner6ad04a02009-09-27 21:35:11 +0000407 visitCallSite(CallSite::get(&I));
Victor Hernandez48c3c542009-09-18 22:35:49 +0000408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 void visitInvokeInst (InvokeInst &II) {
410 visitCallSite(CallSite::get(&II));
411 visitTerminatorInst(II);
412 }
413 void visitCallSite (CallSite CS);
414 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
415 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
Victor Hernandezb1687302009-10-23 21:09:37 +0000416 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
418 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419
420 void visitInstruction(Instruction &I) {
421 // If a new instruction is added to LLVM that we don't handle...
Chris Lattner8a6411c2009-08-23 04:37:46 +0000422 errs() << "SCCP: Don't know how to handle: " << I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 markOverdefined(&I); // Just in case
424 }
425};
426
Duncan Sands40f67972007-07-20 08:56:21 +0000427} // end anonymous namespace
428
429
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430// getFeasibleSuccessors - Return a vector of booleans to indicate which
431// successors are reachable from a given terminator instruction.
432//
433void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
434 SmallVector<bool, 16> &Succs) {
435 Succs.resize(TI.getNumSuccessors());
436 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
437 if (BI->isUnconditional()) {
438 Succs[0] = true;
439 } else {
440 LatticeVal &BCValue = getValueState(BI->getCondition());
441 if (BCValue.isOverdefined() ||
442 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
443 // Overdefined condition variables, and branches on unfoldable constant
444 // conditions, mean the branch could go either way.
445 Succs[0] = Succs[1] = true;
446 } else if (BCValue.isConstant()) {
447 // Constant condition variables mean the branch can only go a single way
Owen Anderson4f720fa2009-07-31 17:39:07 +0000448 Succs[BCValue.getConstant() == ConstantInt::getFalse(*Context)] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 }
450 }
451 } else if (isa<InvokeInst>(&TI)) {
452 // Invoke instructions successors are always executable.
453 Succs[0] = Succs[1] = true;
454 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
455 LatticeVal &SCValue = getValueState(SI->getCondition());
456 if (SCValue.isOverdefined() || // Overdefined condition?
457 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
458 // All destinations are executable!
459 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner81335532008-05-10 23:56:54 +0000460 } else if (SCValue.isConstant())
461 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +0000463 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 }
465}
466
467
468// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
469// block to the 'To' basic block is currently feasible...
470//
471bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
472 assert(BBExecutable.count(To) && "Dest should always be alive!");
473
474 // Make sure the source basic block is executable!!
475 if (!BBExecutable.count(From)) return false;
476
477 // Check to make sure this edge itself is actually feasible now...
478 TerminatorInst *TI = From->getTerminator();
479 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
480 if (BI->isUnconditional())
481 return true;
482 else {
483 LatticeVal &BCValue = getValueState(BI->getCondition());
484 if (BCValue.isOverdefined()) {
485 // Overdefined condition variables mean the branch could go either way.
486 return true;
487 } else if (BCValue.isConstant()) {
488 // Not branching on an evaluatable constant?
489 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
490
491 // Constant condition variables mean the branch can only go a single way
492 return BI->getSuccessor(BCValue.getConstant() ==
Owen Anderson4f720fa2009-07-31 17:39:07 +0000493 ConstantInt::getFalse(*Context)) == To;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494 }
495 return false;
496 }
497 } else if (isa<InvokeInst>(TI)) {
498 // Invoke instructions successors are always executable.
499 return true;
500 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
501 LatticeVal &SCValue = getValueState(SI->getCondition());
502 if (SCValue.isOverdefined()) { // Overdefined condition?
503 // All destinations are executable!
504 return true;
505 } else if (SCValue.isConstant()) {
506 Constant *CPV = SCValue.getConstant();
507 if (!isa<ConstantInt>(CPV))
508 return true; // not a foldable constant?
509
510 // Make sure to skip the "default value" which isn't a value
511 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
512 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
513 return SI->getSuccessor(i) == To;
514
515 // Constant value not equal to any of the branches... must execute
516 // default branch then...
517 return SI->getDefaultDest() == To;
518 }
519 return false;
520 } else {
Edwin Törökced9ff82009-07-11 13:10:19 +0000521#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +0000522 errs() << "Unknown terminator instruction: " << *TI << '\n';
Edwin Törökced9ff82009-07-11 13:10:19 +0000523#endif
Edwin Törökbd448e32009-07-14 16:55:14 +0000524 llvm_unreachable(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 }
526}
527
528// visit Implementations - Something changed in this instruction... Either an
529// operand made a transition, or the instruction is newly executable. Change
530// the value type of I to reflect these changes if appropriate. This method
531// makes sure to do the following actions:
532//
533// 1. If a phi node merges two constants in, and has conflicting value coming
534// from different branches, or if the PHI node merges in an overdefined
535// value, then the PHI node becomes overdefined.
536// 2. If a phi node merges only constants in, and they all agree on value, the
537// PHI node becomes a constant value equal to that.
538// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
539// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
540// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
541// 6. If a conditional branch has a value that is constant, make the selected
542// destination executable
543// 7. If a conditional branch has a value that is overdefined, make all
544// successors executable.
545//
546void SCCPSolver::visitPHINode(PHINode &PN) {
547 LatticeVal &PNIV = getValueState(&PN);
548 if (PNIV.isOverdefined()) {
549 // There may be instructions using this PHI node that are not overdefined
550 // themselves. If so, make sure that they know that the PHI node operand
551 // changed.
552 std::multimap<PHINode*, Instruction*>::iterator I, E;
553 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
554 if (I != E) {
555 SmallVector<Instruction*, 16> Users;
556 for (; I != E; ++I) Users.push_back(I->second);
557 while (!Users.empty()) {
558 visit(Users.back());
559 Users.pop_back();
560 }
561 }
562 return; // Quick exit
563 }
564
565 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
566 // and slow us down a lot. Just mark them overdefined.
567 if (PN.getNumIncomingValues() > 64) {
568 markOverdefined(PNIV, &PN);
569 return;
570 }
571
572 // Look at all of the executable operands of the PHI node. If any of them
573 // are overdefined, the PHI becomes overdefined as well. If they are all
574 // constant, and they agree with each other, the PHI becomes the identical
575 // constant. If they are constant and don't agree, the PHI is overdefined.
576 // If there are no executable operands, the PHI remains undefined.
577 //
578 Constant *OperandVal = 0;
579 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
580 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
581 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
582
583 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
584 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnerd3123a72008-08-23 23:36:38 +0000585 markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 return;
587 }
588
589 if (OperandVal == 0) { // Grab the first value...
590 OperandVal = IV.getConstant();
591 } else { // Another value is being merged in!
592 // There is already a reachable operand. If we conflict with it,
593 // then the PHI node becomes overdefined. If we agree with it, we
594 // can continue on.
595
596 // Check to see if there are two different constants merging...
597 if (IV.getConstant() != OperandVal) {
598 // Yes there is. This means the PHI node is not constant.
599 // You must be overdefined poor PHI.
600 //
Chris Lattnerd3123a72008-08-23 23:36:38 +0000601 markOverdefined(&PN); // The PHI node now becomes overdefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 return; // I'm done analyzing you
603 }
604 }
605 }
606 }
607
608 // If we exited the loop, this means that the PHI node only has constant
609 // arguments that agree with each other(and OperandVal is the constant) or
610 // OperandVal is null because there are no defined incoming arguments. If
611 // this is the case, the PHI remains undefined.
612 //
613 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000614 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615}
616
617void SCCPSolver::visitReturnInst(ReturnInst &I) {
618 if (I.getNumOperands() == 0) return; // Ret void
619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000621 // If we are tracking the return value of this function, merge it in.
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000622 if (!F->hasLocalLinkage())
Devang Pateladd320d2008-03-11 05:46:42 +0000623 return;
624
Chris Lattnercd73be02008-04-23 05:38:20 +0000625 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000627 TrackedRetVals.find(F);
628 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 !TFRVI->second.isOverdefined()) {
630 LatticeVal &IV = getValueState(I.getOperand(0));
631 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000632 return;
633 }
634 }
635
Chris Lattnercd73be02008-04-23 05:38:20 +0000636 // Handle functions that return multiple values.
637 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
638 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000639 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000640 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
641 if (It == TrackedMultipleRetVals.end()) break;
642 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 }
Dan Gohman856193b2008-06-20 01:15:44 +0000644 } else if (!TrackedMultipleRetVals.empty() &&
645 I.getNumOperands() == 1 &&
646 isa<StructType>(I.getOperand(0)->getType())) {
647 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
648 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000649 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000650 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
651 if (It == TrackedMultipleRetVals.end()) break;
Owen Anderson175b6542009-07-22 00:24:57 +0000652 if (Value *Val = FindInsertedValue(I.getOperand(0), i, I.getContext()))
Nick Lewycky6ad29e02009-06-06 23:13:08 +0000653 mergeInValue(It->second, F, getValueState(Val));
Dan Gohman856193b2008-06-20 01:15:44 +0000654 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 }
656}
657
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
659 SmallVector<bool, 16> SuccFeasible;
660 getFeasibleSuccessors(TI, SuccFeasible);
661
662 BasicBlock *BB = TI.getParent();
663
664 // Mark all feasible successors executable...
665 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
666 if (SuccFeasible[i])
667 markEdgeExecutable(BB, TI.getSuccessor(i));
668}
669
670void SCCPSolver::visitCastInst(CastInst &I) {
671 Value *V = I.getOperand(0);
672 LatticeVal &VState = getValueState(V);
673 if (VState.isOverdefined()) // Inherit overdefinedness of operand
674 markOverdefined(&I);
675 else if (VState.isConstant()) // Propagate constant value
Owen Anderson02b48c32009-07-29 18:55:55 +0000676 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 VState.getConstant(), I.getType()));
678}
679
Dan Gohman856193b2008-06-20 01:15:44 +0000680void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000681 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000682
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000683 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000684 if (isa<UndefValue>(Aggr))
685 return;
686
687 // Currently only handle single-index extractvalues.
688 if (EVI.getNumIndices() != 1) {
689 markOverdefined(&EVI);
690 return;
691 }
692
693 Function *F = 0;
694 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
695 F = CI->getCalledFunction();
696 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
697 F = II->getCalledFunction();
698
699 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
700 // result back!
701 if (F == 0 || TrackedMultipleRetVals.empty()) {
702 markOverdefined(&EVI);
703 return;
704 }
705
Chris Lattnerd3123a72008-08-23 23:36:38 +0000706 // See if we are tracking the result of the callee. If not tracking this
707 // function (for example, it is a declaration) just move to overdefined.
708 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohman856193b2008-06-20 01:15:44 +0000709 markOverdefined(&EVI);
710 return;
711 }
712
713 // Otherwise, the value will be merged in here as a result of CallSite
714 // handling.
715}
716
717void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000718 Value *Aggr = IVI.getAggregateOperand();
719 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000720
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000721 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000722 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000723 return;
724
725 // Currently only handle single-index insertvalues.
726 if (IVI.getNumIndices() != 1) {
727 markOverdefined(&IVI);
728 return;
729 }
Dan Gohman78b2c392008-06-20 16:39:44 +0000730
731 // Currently only handle insertvalue instructions that are in a single-use
732 // chain that builds up a return value.
733 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
734 if (!TmpIVI->hasOneUse()) {
735 markOverdefined(&IVI);
736 return;
737 }
738 const Value *V = *TmpIVI->use_begin();
739 if (isa<ReturnInst>(V))
740 break;
741 TmpIVI = dyn_cast<InsertValueInst>(V);
742 if (!TmpIVI) {
743 markOverdefined(&IVI);
744 return;
745 }
746 }
Dan Gohman856193b2008-06-20 01:15:44 +0000747
748 // See if we are tracking the result of the callee.
749 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000750 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000751 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
752
753 // Merge in the inserted member value.
754 if (It != TrackedMultipleRetVals.end())
755 mergeInValue(It->second, F, getValueState(Val));
756
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000757 // Mark the aggregate result of the IVI overdefined; any tracking that we do
758 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000759 markOverdefined(&IVI);
760}
761
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762void SCCPSolver::visitSelectInst(SelectInst &I) {
763 LatticeVal &CondValue = getValueState(I.getCondition());
764 if (CondValue.isUndefined())
765 return;
766 if (CondValue.isConstant()) {
767 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
768 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
769 : I.getFalseValue()));
770 return;
771 }
772 }
773
774 // Otherwise, the condition is overdefined or a constant we can't evaluate.
775 // See if we can produce something better than overdefined based on the T/F
776 // value.
777 LatticeVal &TVal = getValueState(I.getTrueValue());
778 LatticeVal &FVal = getValueState(I.getFalseValue());
779
780 // select ?, C, C -> C.
781 if (TVal.isConstant() && FVal.isConstant() &&
782 TVal.getConstant() == FVal.getConstant()) {
783 markConstant(&I, FVal.getConstant());
784 return;
785 }
786
787 if (TVal.isUndefined()) { // select ?, undef, X -> X.
788 mergeInValue(&I, FVal);
789 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
790 mergeInValue(&I, TVal);
791 } else {
792 markOverdefined(&I);
793 }
794}
795
796// Handle BinaryOperators and Shift Instructions...
797void SCCPSolver::visitBinaryOperator(Instruction &I) {
798 LatticeVal &IV = ValueState[&I];
799 if (IV.isOverdefined()) return;
800
801 LatticeVal &V1State = getValueState(I.getOperand(0));
802 LatticeVal &V2State = getValueState(I.getOperand(1));
803
804 if (V1State.isOverdefined() || V2State.isOverdefined()) {
805 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
806 // operand is overdefined.
807 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
808 LatticeVal *NonOverdefVal = 0;
809 if (!V1State.isOverdefined()) {
810 NonOverdefVal = &V1State;
811 } else if (!V2State.isOverdefined()) {
812 NonOverdefVal = &V2State;
813 }
814
815 if (NonOverdefVal) {
816 if (NonOverdefVal->isUndefined()) {
817 // Could annihilate value.
818 if (I.getOpcode() == Instruction::And)
Owen Andersonaac28372009-07-31 20:28:14 +0000819 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
Owen Andersonaac28372009-07-31 20:28:14 +0000821 markConstant(IV, &I, Constant::getAllOnesValue(PT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000822 else
Owen Andersonfa089ab2009-07-03 19:42:02 +0000823 markConstant(IV, &I,
Owen Andersonaac28372009-07-31 20:28:14 +0000824 Constant::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 return;
826 } else {
827 if (I.getOpcode() == Instruction::And) {
828 if (NonOverdefVal->getConstant()->isNullValue()) {
829 markConstant(IV, &I, NonOverdefVal->getConstant());
830 return; // X and 0 = 0
831 }
832 } else {
833 if (ConstantInt *CI =
834 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
835 if (CI->isAllOnesValue()) {
836 markConstant(IV, &I, NonOverdefVal->getConstant());
837 return; // X or -1 = -1
838 }
839 }
840 }
841 }
842 }
843
844
845 // If both operands are PHI nodes, it is possible that this instruction has
846 // a constant value, despite the fact that the PHI node doesn't. Check for
847 // this condition now.
848 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
849 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
850 if (PN1->getParent() == PN2->getParent()) {
851 // Since the two PHI nodes are in the same basic block, they must have
852 // entries for the same predecessors. Walk the predecessor list, and
853 // if all of the incoming values are constants, and the result of
854 // evaluating this expression with all incoming value pairs is the
855 // same, then this expression is a constant even though the PHI node
856 // is not a constant!
857 LatticeVal Result;
858 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
859 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
860 BasicBlock *InBlock = PN1->getIncomingBlock(i);
861 LatticeVal &In2 =
862 getValueState(PN2->getIncomingValueForBlock(InBlock));
863
864 if (In1.isOverdefined() || In2.isOverdefined()) {
865 Result.markOverdefined();
866 break; // Cannot fold this operation over the PHI nodes!
867 } else if (In1.isConstant() && In2.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000868 Constant *V =
Owen Anderson02b48c32009-07-29 18:55:55 +0000869 ConstantExpr::get(I.getOpcode(), In1.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 In2.getConstant());
871 if (Result.isUndefined())
872 Result.markConstant(V);
873 else if (Result.isConstant() && Result.getConstant() != V) {
874 Result.markOverdefined();
875 break;
876 }
877 }
878 }
879
880 // If we found a constant value here, then we know the instruction is
881 // constant despite the fact that the PHI nodes are overdefined.
882 if (Result.isConstant()) {
883 markConstant(IV, &I, Result.getConstant());
884 // Remember that this instruction is virtually using the PHI node
885 // operands.
886 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
887 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
888 return;
889 } else if (Result.isUndefined()) {
890 return;
891 }
892
893 // Okay, this really is overdefined now. Since we might have
894 // speculatively thought that this was not overdefined before, and
895 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
896 // make sure to clean out any entries that we put there, for
897 // efficiency.
898 std::multimap<PHINode*, Instruction*>::iterator It, E;
899 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
900 while (It != E) {
901 if (It->second == &I) {
902 UsersOfOverdefinedPHIs.erase(It++);
903 } else
904 ++It;
905 }
906 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
907 while (It != E) {
908 if (It->second == &I) {
909 UsersOfOverdefinedPHIs.erase(It++);
910 } else
911 ++It;
912 }
913 }
914
915 markOverdefined(IV, &I);
916 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Andersonfa089ab2009-07-03 19:42:02 +0000917 markConstant(IV, &I,
Owen Anderson02b48c32009-07-29 18:55:55 +0000918 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 V2State.getConstant()));
920 }
921}
922
923// Handle ICmpInst instruction...
924void SCCPSolver::visitCmpInst(CmpInst &I) {
925 LatticeVal &IV = ValueState[&I];
926 if (IV.isOverdefined()) return;
927
928 LatticeVal &V1State = getValueState(I.getOperand(0));
929 LatticeVal &V2State = getValueState(I.getOperand(1));
930
931 if (V1State.isOverdefined() || V2State.isOverdefined()) {
932 // If both operands are PHI nodes, it is possible that this instruction has
933 // a constant value, despite the fact that the PHI node doesn't. Check for
934 // this condition now.
935 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
936 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
937 if (PN1->getParent() == PN2->getParent()) {
938 // Since the two PHI nodes are in the same basic block, they must have
939 // entries for the same predecessors. Walk the predecessor list, and
940 // if all of the incoming values are constants, and the result of
941 // evaluating this expression with all incoming value pairs is the
942 // same, then this expression is a constant even though the PHI node
943 // is not a constant!
944 LatticeVal Result;
945 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
946 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
947 BasicBlock *InBlock = PN1->getIncomingBlock(i);
948 LatticeVal &In2 =
949 getValueState(PN2->getIncomingValueForBlock(InBlock));
950
951 if (In1.isOverdefined() || In2.isOverdefined()) {
952 Result.markOverdefined();
953 break; // Cannot fold this operation over the PHI nodes!
954 } else if (In1.isConstant() && In2.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000955 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 In1.getConstant(),
957 In2.getConstant());
958 if (Result.isUndefined())
959 Result.markConstant(V);
960 else if (Result.isConstant() && Result.getConstant() != V) {
961 Result.markOverdefined();
962 break;
963 }
964 }
965 }
966
967 // If we found a constant value here, then we know the instruction is
968 // constant despite the fact that the PHI nodes are overdefined.
969 if (Result.isConstant()) {
970 markConstant(IV, &I, Result.getConstant());
971 // Remember that this instruction is virtually using the PHI node
972 // operands.
973 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
974 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
975 return;
976 } else if (Result.isUndefined()) {
977 return;
978 }
979
980 // Okay, this really is overdefined now. Since we might have
981 // speculatively thought that this was not overdefined before, and
982 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
983 // make sure to clean out any entries that we put there, for
984 // efficiency.
985 std::multimap<PHINode*, Instruction*>::iterator It, E;
986 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
987 while (It != E) {
988 if (It->second == &I) {
989 UsersOfOverdefinedPHIs.erase(It++);
990 } else
991 ++It;
992 }
993 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
994 while (It != E) {
995 if (It->second == &I) {
996 UsersOfOverdefinedPHIs.erase(It++);
997 } else
998 ++It;
999 }
1000 }
1001
1002 markOverdefined(IV, &I);
1003 } else if (V1State.isConstant() && V2State.isConstant()) {
Owen Anderson02b48c32009-07-29 18:55:55 +00001004 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 V1State.getConstant(),
1006 V2State.getConstant()));
1007 }
1008}
1009
1010void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1011 // FIXME : SCCP does not handle vectors properly.
1012 markOverdefined(&I);
1013 return;
1014
1015#if 0
1016 LatticeVal &ValState = getValueState(I.getOperand(0));
1017 LatticeVal &IdxState = getValueState(I.getOperand(1));
1018
1019 if (ValState.isOverdefined() || IdxState.isOverdefined())
1020 markOverdefined(&I);
1021 else if(ValState.isConstant() && IdxState.isConstant())
1022 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1023 IdxState.getConstant()));
1024#endif
1025}
1026
1027void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1028 // FIXME : SCCP does not handle vectors properly.
1029 markOverdefined(&I);
1030 return;
1031#if 0
1032 LatticeVal &ValState = getValueState(I.getOperand(0));
1033 LatticeVal &EltState = getValueState(I.getOperand(1));
1034 LatticeVal &IdxState = getValueState(I.getOperand(2));
1035
1036 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1037 IdxState.isOverdefined())
1038 markOverdefined(&I);
1039 else if(ValState.isConstant() && EltState.isConstant() &&
1040 IdxState.isConstant())
1041 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1042 EltState.getConstant(),
1043 IdxState.getConstant()));
1044 else if (ValState.isUndefined() && EltState.isConstant() &&
1045 IdxState.isConstant())
1046 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1047 EltState.getConstant(),
1048 IdxState.getConstant()));
1049#endif
1050}
1051
1052void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1053 // FIXME : SCCP does not handle vectors properly.
1054 markOverdefined(&I);
1055 return;
1056#if 0
1057 LatticeVal &V1State = getValueState(I.getOperand(0));
1058 LatticeVal &V2State = getValueState(I.getOperand(1));
1059 LatticeVal &MaskState = getValueState(I.getOperand(2));
1060
1061 if (MaskState.isUndefined() ||
1062 (V1State.isUndefined() && V2State.isUndefined()))
1063 return; // Undefined output if mask or both inputs undefined.
1064
1065 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1066 MaskState.isOverdefined()) {
1067 markOverdefined(&I);
1068 } else {
1069 // A mix of constant/undef inputs.
1070 Constant *V1 = V1State.isConstant() ?
1071 V1State.getConstant() : UndefValue::get(I.getType());
1072 Constant *V2 = V2State.isConstant() ?
1073 V2State.getConstant() : UndefValue::get(I.getType());
1074 Constant *Mask = MaskState.isConstant() ?
1075 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1076 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1077 }
1078#endif
1079}
1080
1081// Handle getelementptr instructions... if all operands are constants then we
1082// can turn this into a getelementptr ConstantExpr.
1083//
1084void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1085 LatticeVal &IV = ValueState[&I];
1086 if (IV.isOverdefined()) return;
1087
1088 SmallVector<Constant*, 8> Operands;
1089 Operands.reserve(I.getNumOperands());
1090
1091 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1092 LatticeVal &State = getValueState(I.getOperand(i));
1093 if (State.isUndefined())
1094 return; // Operands are not resolved yet...
1095 else if (State.isOverdefined()) {
1096 markOverdefined(IV, &I);
1097 return;
1098 }
1099 assert(State.isConstant() && "Unknown state!");
1100 Operands.push_back(State.getConstant());
1101 }
1102
1103 Constant *Ptr = Operands[0];
1104 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1105
Owen Anderson02b48c32009-07-29 18:55:55 +00001106 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 Operands.size()));
1108}
1109
1110void SCCPSolver::visitStoreInst(Instruction &SI) {
1111 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1112 return;
1113 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1114 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1115 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1116
1117 // Get the value we are storing into the global.
1118 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1119
1120 mergeInValue(I->second, GV, PtrVal);
1121 if (I->second.isOverdefined())
1122 TrackedGlobals.erase(I); // No need to keep tracking this!
1123}
1124
1125
1126// Handle load instructions. If the operand is a constant pointer to a constant
1127// global, we can replace the load with the loaded constant value!
1128void SCCPSolver::visitLoadInst(LoadInst &I) {
1129 LatticeVal &IV = ValueState[&I];
1130 if (IV.isOverdefined()) return;
1131
1132 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1133 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1134 if (PtrVal.isConstant() && !I.isVolatile()) {
1135 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001136 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner6807a242009-08-30 20:06:40 +00001137 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 // load null -> null
Owen Andersonaac28372009-07-31 20:28:14 +00001139 markConstant(IV, &I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 return;
1141 }
1142
1143 // Transform load (constant global) into the value loaded.
1144 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1145 if (GV->isConstant()) {
Duncan Sands54e70f62009-03-21 21:27:31 +00001146 if (GV->hasDefinitiveInitializer()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 markConstant(IV, &I, GV->getInitializer());
1148 return;
1149 }
1150 } else if (!TrackedGlobals.empty()) {
1151 // If we are tracking this global, merge in the known value for it.
1152 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1153 TrackedGlobals.find(GV);
1154 if (It != TrackedGlobals.end()) {
1155 mergeInValue(IV, &I, It->second);
1156 return;
1157 }
1158 }
1159 }
1160
1161 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1162 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1163 if (CE->getOpcode() == Instruction::GetElementPtr)
1164 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +00001165 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001166 if (Constant *V =
Dan Gohmanf49f7b02009-10-05 16:36:26 +00001167 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 markConstant(IV, &I, V);
1169 return;
1170 }
1171 }
1172
1173 // Otherwise we cannot say for certain what value this load will produce.
1174 // Bail out.
1175 markOverdefined(IV, &I);
1176}
1177
1178void SCCPSolver::visitCallSite(CallSite CS) {
1179 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001181
1182 // The common case is that we aren't tracking the callee, either because we
1183 // are not doing interprocedural analysis or the callee is indirect, or is
1184 // external. Handle these cases first.
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001185 if (F == 0 || !F->hasLocalLinkage()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001186CallOverdefined:
1187 // Void return and not tracking callee, just bail.
Chris Lattner82cdc062009-10-05 05:54:46 +00001188 if (I->getType()->isVoidTy()) return;
Chris Lattnercd73be02008-04-23 05:38:20 +00001189
1190 // Otherwise, if we have a single return value case, and if the function is
1191 // a declaration, maybe we can constant fold it.
1192 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1193 canConstantFoldCallTo(F)) {
1194
1195 SmallVector<Constant*, 8> Operands;
1196 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1197 AI != E; ++AI) {
1198 LatticeVal &State = getValueState(*AI);
1199 if (State.isUndefined())
1200 return; // Operands are not resolved yet.
1201 else if (State.isOverdefined()) {
1202 markOverdefined(I);
1203 return;
1204 }
1205 assert(State.isConstant() && "Unknown state!");
1206 Operands.push_back(State.getConstant());
1207 }
1208
1209 // If we can constant fold this, mark the result of the call as a
1210 // constant.
Nick Lewyckye9279352009-05-28 04:08:10 +00001211 if (Constant *C = ConstantFoldCall(F, Operands.data(), Operands.size())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001212 markConstant(I, C);
1213 return;
1214 }
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.
1218 markOverdefined(I);
1219 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 }
1221
Chris Lattnercd73be02008-04-23 05:38:20 +00001222 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001223 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1224 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001225 // If so, propagate the return value of the callee into this call result.
1226 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001227 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001228 // Check to see if we're tracking this callee, if not, handle it in the
1229 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001230 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1231 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001232 if (TMRVI == TrackedMultipleRetVals.end())
1233 goto CallOverdefined;
Edwin Töröka6174642009-10-20 15:15:09 +00001234
1235 // Need to mark as overdefined, otherwise it stays undefined which
1236 // creates extractvalue undef, <idx>
1237 markOverdefined(I);
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()) {
1283 // Process the instruction work list...
1284 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
1295 // Update all of the users of this instruction's value...
1296 //
1297 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1298 UI != E; ++UI)
1299 OperandChangedState(*UI);
1300 }
1301 // Process the instruction work list...
1302 while (!InstWorkList.empty()) {
1303 Value *I = InstWorkList.back();
1304 InstWorkList.pop_back();
1305
Dan Gohmandff8d172009-08-17 15:25:05 +00001306 DEBUG(errs() << "\nPopped off I-WL: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307
1308 // "I" got into the work list because it either made the transition from
1309 // bottom to constant
1310 //
1311 // Anything on this worklist that is overdefined need not be visited
1312 // since all of its users will have already been marked as overdefined.
1313 // Update all of the users of this instruction's value...
1314 //
1315 if (!getValueState(I).isOverdefined())
1316 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1317 UI != E; ++UI)
1318 OperandChangedState(*UI);
1319 }
1320
1321 // Process the basic block work list...
1322 while (!BBWorkList.empty()) {
1323 BasicBlock *BB = BBWorkList.back();
1324 BBWorkList.pop_back();
1325
Dan Gohmandff8d172009-08-17 15:25:05 +00001326 DEBUG(errs() << "\nPopped off BBWL: " << *BB << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327
1328 // Notify all instructions in this basic block that they are newly
1329 // executable.
1330 visit(BB);
1331 }
1332 }
1333}
1334
1335/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1336/// that branches on undef values cannot reach any of their successors.
1337/// However, this is not a safe assumption. After we solve dataflow, this
1338/// method should be use to handle this. If this returns true, the solver
1339/// should be rerun.
1340///
1341/// This method handles this by finding an unresolved branch and marking it one
1342/// of the edges from the block as being feasible, even though the condition
1343/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1344/// CFG and only slightly pessimizes the analysis results (by marking one,
1345/// potentially infeasible, edge feasible). This cannot usefully modify the
1346/// constraints on the condition of the branch, as that would impact other users
1347/// of the value.
1348///
1349/// This scan also checks for values that use undefs, whose results are actually
1350/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1351/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1352/// even if X isn't defined.
1353bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1354 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1355 if (!BBExecutable.count(BB))
1356 continue;
1357
1358 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1359 // Look for instructions which produce undef values.
Chris Lattner82cdc062009-10-05 05:54:46 +00001360 if (I->getType()->isVoidTy()) continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361
1362 LatticeVal &LV = getValueState(I);
1363 if (!LV.isUndefined()) continue;
1364
1365 // Get the lattice values of the first two operands for use below.
1366 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1367 LatticeVal Op1LV;
1368 if (I->getNumOperands() == 2) {
1369 // If this is a two-operand instruction, and if both operands are
1370 // undefs, the result stays undef.
1371 Op1LV = getValueState(I->getOperand(1));
1372 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1373 continue;
1374 }
1375
1376 // If this is an instructions whose result is defined even if the input is
1377 // not fully defined, propagate the information.
1378 const Type *ITy = I->getType();
1379 switch (I->getOpcode()) {
1380 default: break; // Leave the instruction as an undef.
1381 case Instruction::ZExt:
1382 // After a zero extend, we know the top part is zero. SExt doesn't have
1383 // to be handled here, because we don't know whether the top part is 1's
1384 // or 0's.
1385 assert(Op0LV.isUndefined());
Owen Andersonaac28372009-07-31 20:28:14 +00001386 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 return true;
1388 case Instruction::Mul:
1389 case Instruction::And:
1390 // undef * X -> 0. X could be zero.
1391 // undef & X -> 0. X could be zero.
Owen Andersonaac28372009-07-31 20:28:14 +00001392 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 return true;
1394
1395 case Instruction::Or:
1396 // undef | X -> -1. X could be -1.
1397 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
Owen Andersonfa089ab2009-07-03 19:42:02 +00001398 markForcedConstant(LV, I,
Owen Andersonaac28372009-07-31 20:28:14 +00001399 Constant::getAllOnesValue(PTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001400 else
Owen Andersonaac28372009-07-31 20:28:14 +00001401 markForcedConstant(LV, I, Constant::getAllOnesValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 return true;
1403
1404 case Instruction::SDiv:
1405 case Instruction::UDiv:
1406 case Instruction::SRem:
1407 case Instruction::URem:
1408 // X / undef -> undef. No change.
1409 // X % undef -> undef. No change.
1410 if (Op1LV.isUndefined()) break;
1411
1412 // undef / X -> 0. X could be maxint.
1413 // undef % X -> 0. X could be 1.
Owen Andersonaac28372009-07-31 20:28:14 +00001414 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 return true;
1416
1417 case Instruction::AShr:
1418 // undef >>s X -> undef. No change.
1419 if (Op0LV.isUndefined()) break;
1420
1421 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1422 if (Op0LV.isConstant())
1423 markForcedConstant(LV, I, Op0LV.getConstant());
1424 else
1425 markOverdefined(LV, I);
1426 return true;
1427 case Instruction::LShr:
1428 case Instruction::Shl:
1429 // undef >> X -> undef. No change.
1430 // undef << X -> undef. No change.
1431 if (Op0LV.isUndefined()) break;
1432
1433 // X >> undef -> 0. X could be 0.
1434 // X << undef -> 0. X could be 0.
Owen Andersonaac28372009-07-31 20:28:14 +00001435 markForcedConstant(LV, I, Constant::getNullValue(ITy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 return true;
1437 case Instruction::Select:
1438 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1439 if (Op0LV.isUndefined()) {
1440 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1441 Op1LV = getValueState(I->getOperand(2));
1442 } else if (Op1LV.isUndefined()) {
1443 // c ? undef : undef -> undef. No change.
1444 Op1LV = getValueState(I->getOperand(2));
1445 if (Op1LV.isUndefined())
1446 break;
1447 // Otherwise, c ? undef : x -> x.
1448 } else {
1449 // Leave Op1LV as Operand(1)'s LatticeValue.
1450 }
1451
1452 if (Op1LV.isConstant())
1453 markForcedConstant(LV, I, Op1LV.getConstant());
1454 else
1455 markOverdefined(LV, I);
1456 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001457 case Instruction::Call:
1458 // If a call has an undef result, it is because it is constant foldable
1459 // but one of the inputs was undef. Just force the result to
1460 // overdefined.
1461 markOverdefined(LV, I);
1462 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001463 }
1464 }
1465
1466 TerminatorInst *TI = BB->getTerminator();
1467 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1468 if (!BI->isConditional()) continue;
1469 if (!getValueState(BI->getCondition()).isUndefined())
1470 continue;
1471 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001472 if (SI->getNumSuccessors()<2) // no cases
1473 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 if (!getValueState(SI->getCondition()).isUndefined())
1475 continue;
1476 } else {
1477 continue;
1478 }
1479
Chris Lattner6186e8c2008-01-28 00:32:30 +00001480 // If the edge to the second successor isn't thought to be feasible yet,
1481 // mark it so now. We pick the second one so that this goes to some
1482 // enumerated value in a switch instead of going to the default destination.
1483 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001484 continue;
1485
1486 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1487 // and return. This will make other blocks reachable, which will allow new
1488 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001489 markEdgeExecutable(BB, TI->getSuccessor(1));
1490
1491 // This must be a conditional branch of switch on undef. At this point,
1492 // force the old terminator to branch to the first successor. This is
1493 // required because we are now influencing the dataflow of the function with
1494 // the assumption that this edge is taken. If we leave the branch condition
1495 // as undef, then further analysis could think the undef went another way
1496 // leading to an inconsistent set of conclusions.
1497 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Owen Anderson4f720fa2009-07-31 17:39:07 +00001498 BI->setCondition(ConstantInt::getFalse(*Context));
Chris Lattner6186e8c2008-01-28 00:32:30 +00001499 } else {
1500 SwitchInst *SI = cast<SwitchInst>(TI);
1501 SI->setCondition(SI->getCaseValue(1));
1502 }
1503
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504 return true;
1505 }
1506
1507 return false;
1508}
1509
1510
1511namespace {
1512 //===--------------------------------------------------------------------===//
1513 //
1514 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1515 /// Sparse Conditional Constant Propagator.
1516 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001517 struct SCCP : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +00001519 SCCP() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001520
1521 // runOnFunction - Run the Sparse Conditional Constant Propagation
1522 // algorithm, and return true if the function was modified.
1523 //
1524 bool runOnFunction(Function &F);
1525
1526 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1527 AU.setPreservesCFG();
1528 }
1529 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530} // end anonymous namespace
1531
Dan Gohman089efff2008-05-13 00:00:25 +00001532char SCCP::ID = 0;
1533static RegisterPass<SCCP>
1534X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535
1536// createSCCPPass - This is the public interface to this file...
1537FunctionPass *llvm::createSCCPPass() {
1538 return new SCCP();
1539}
1540
1541
1542// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1543// and return true if the function was modified.
1544//
1545bool SCCP::runOnFunction(Function &F) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001546 DEBUG(errs() << "SCCP on function '" << F.getName() << "'\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 SCCPSolver Solver;
Owen Anderson175b6542009-07-22 00:24:57 +00001548 Solver.setContext(&F.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549
1550 // Mark the first block of the function as being executable.
1551 Solver.MarkBlockExecutable(F.begin());
1552
1553 // Mark all arguments to the function as being overdefined.
1554 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1555 Solver.markOverdefined(AI);
1556
1557 // Solve for constants.
1558 bool ResolvedUndefs = true;
1559 while (ResolvedUndefs) {
1560 Solver.Solve();
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001561 DEBUG(errs() << "RESOLVING UNDEFs\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1563 }
1564
1565 bool MadeChanges = false;
1566
1567 // If we decided that there are basic blocks that are dead in this function,
1568 // delete their contents now. Note that we cannot actually delete the blocks,
1569 // as we cannot modify the CFG of the function.
1570 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001571 SmallVector<Instruction*, 512> Insts;
Bill Wendling03488ae2008-08-14 23:05:24 +00001572 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001573
1574 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001575 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001576 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577 ++NumDeadBlocks;
1578
1579 // Delete the instructions backwards, as it has a reduced likelihood of
1580 // having to update as many def-use and use-def chains.
1581 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1582 I != E; ++I)
1583 Insts.push_back(I);
1584 while (!Insts.empty()) {
1585 Instruction *I = Insts.back();
1586 Insts.pop_back();
1587 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001588 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589 BB->getInstList().erase(I);
1590 MadeChanges = true;
1591 ++NumInstRemoved;
1592 }
1593 } else {
1594 // Iterate over all of the instructions in a function, replacing them with
1595 // constants if we have found them to be of constant values.
1596 //
1597 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1598 Instruction *Inst = BI++;
Chris Lattner82cdc062009-10-05 05:54:46 +00001599 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
Chris Lattnerb6f89362008-04-24 00:16:28 +00001600 continue;
1601
1602 LatticeVal &IV = Values[Inst];
1603 if (!IV.isConstant() && !IV.isUndefined())
1604 continue;
1605
1606 Constant *Const = IV.isConstant()
Owen Andersonb99ecca2009-07-30 23:03:37 +00001607 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001608 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001609
Chris Lattnerb6f89362008-04-24 00:16:28 +00001610 // Replaces all of the uses of a variable with uses of the constant.
1611 Inst->replaceAllUsesWith(Const);
1612
1613 // Delete the instruction.
1614 Inst->eraseFromParent();
1615
1616 // Hey, we just changed something!
1617 MadeChanges = true;
1618 ++NumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001619 }
1620 }
1621
1622 return MadeChanges;
1623}
1624
1625namespace {
1626 //===--------------------------------------------------------------------===//
1627 //
1628 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1629 /// Constant Propagation.
1630 ///
Chris Lattnerfa2d1ba2009-09-02 06:11:42 +00001631 struct IPSCCP : public ModulePass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001632 static char ID;
Dan Gohman26f8c272008-09-04 17:05:41 +00001633 IPSCCP() : ModulePass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 bool runOnModule(Module &M);
1635 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636} // end anonymous namespace
1637
Dan Gohman089efff2008-05-13 00:00:25 +00001638char IPSCCP::ID = 0;
1639static RegisterPass<IPSCCP>
1640Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1641
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642// createIPSCCPPass - This is the public interface to this file...
1643ModulePass *llvm::createIPSCCPPass() {
1644 return new IPSCCP();
1645}
1646
1647
1648static bool AddressIsTaken(GlobalValue *GV) {
1649 // Delete any dead constantexpr klingons.
1650 GV->removeDeadConstantUsers();
1651
1652 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1653 UI != E; ++UI)
1654 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1655 if (SI->getOperand(0) == GV || SI->isVolatile())
1656 return true; // Storing addr of GV.
1657 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1658 // Make sure we are calling the function, not passing the address.
1659 CallSite CS = CallSite::get(cast<Instruction>(*UI));
Nick Lewycky1cc2e102008-11-03 03:49:14 +00001660 if (CS.hasArgument(GV))
1661 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001662 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1663 if (LI->isVolatile())
1664 return true;
1665 } else {
1666 return true;
1667 }
1668 return false;
1669}
1670
1671bool IPSCCP::runOnModule(Module &M) {
Owen Anderson175b6542009-07-22 00:24:57 +00001672 LLVMContext *Context = &M.getContext();
Owen Andersone1f1f822009-07-16 18:04:31 +00001673
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 SCCPSolver Solver;
Owen Andersone1f1f822009-07-16 18:04:31 +00001675 Solver.setContext(Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676
1677 // Loop over all functions, marking arguments to those with their addresses
1678 // taken or that are external as overdefined.
1679 //
1680 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001681 if (!F->hasLocalLinkage() || AddressIsTaken(F)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 if (!F->isDeclaration())
1683 Solver.MarkBlockExecutable(F->begin());
1684 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1685 AI != E; ++AI)
1686 Solver.markOverdefined(AI);
1687 } else {
1688 Solver.AddTrackedFunction(F);
1689 }
1690
1691 // Loop over global variables. We inform the solver about any internal global
1692 // variables that do not have their 'addresses taken'. If they don't have
1693 // their addresses taken, we can propagate constants through them.
1694 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1695 G != E; ++G)
Rafael Espindolaa168fc92009-01-15 20:18:42 +00001696 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697 Solver.TrackValueOfGlobalVariable(G);
1698
1699 // Solve for constants.
1700 bool ResolvedUndefs = true;
1701 while (ResolvedUndefs) {
1702 Solver.Solve();
1703
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001704 DEBUG(errs() << "RESOLVING UNDEFS\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 ResolvedUndefs = false;
1706 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1707 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1708 }
1709
1710 bool MadeChanges = false;
1711
1712 // Iterate over all of the instructions in the module, replacing them with
1713 // constants if we have found them to be of constant values.
1714 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001715 SmallVector<Instruction*, 512> Insts;
1716 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling03488ae2008-08-14 23:05:24 +00001717 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001718
1719 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1720 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1721 AI != E; ++AI)
1722 if (!AI->use_empty()) {
1723 LatticeVal &IV = Values[AI];
1724 if (IV.isConstant() || IV.isUndefined()) {
1725 Constant *CST = IV.isConstant() ?
Owen Andersonb99ecca2009-07-30 23:03:37 +00001726 IV.getConstant() : UndefValue::get(AI->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001727 DEBUG(errs() << "*** Arg " << *AI << " = " << *CST <<"\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728
1729 // Replaces all of the uses of a variable with uses of the
1730 // constant.
1731 AI->replaceAllUsesWith(CST);
1732 ++IPNumArgsElimed;
1733 }
1734 }
1735
1736 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
Chris Lattner317e6b62008-08-23 23:39:31 +00001737 if (!Solver.isBlockExecutable(BB)) {
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001738 DEBUG(errs() << " BasicBlock Dead:" << *BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 ++IPNumDeadBlocks;
1740
1741 // Delete the instructions backwards, as it has a reduced likelihood of
1742 // having to update as many def-use and use-def chains.
1743 TerminatorInst *TI = BB->getTerminator();
1744 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1745 Insts.push_back(I);
1746
1747 while (!Insts.empty()) {
1748 Instruction *I = Insts.back();
1749 Insts.pop_back();
1750 if (!I->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001751 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752 BB->getInstList().erase(I);
1753 MadeChanges = true;
1754 ++IPNumInstRemoved;
1755 }
1756
1757 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1758 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001759 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 TI->getSuccessor(i)->removePredecessor(BB);
1761 }
1762 if (!TI->use_empty())
Owen Andersonb99ecca2009-07-30 23:03:37 +00001763 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764 BB->getInstList().erase(TI);
1765
1766 if (&*BB != &F->front())
1767 BlocksToErase.push_back(BB);
1768 else
Owen Anderson35b47072009-08-13 21:58:54 +00001769 new UnreachableInst(M.getContext(), BB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001770
1771 } else {
1772 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1773 Instruction *Inst = BI++;
Chris Lattner82cdc062009-10-05 05:54:46 +00001774 if (Inst->getType()->isVoidTy())
Chris Lattner50846cf2008-04-24 00:21:50 +00001775 continue;
1776
1777 LatticeVal &IV = Values[Inst];
1778 if (!IV.isConstant() && !IV.isUndefined())
1779 continue;
1780
1781 Constant *Const = IV.isConstant()
Owen Andersonb99ecca2009-07-30 23:03:37 +00001782 ? IV.getConstant() : UndefValue::get(Inst->getType());
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001783 DEBUG(errs() << " Constant: " << *Const << " = " << *Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784
Chris Lattner50846cf2008-04-24 00:21:50 +00001785 // Replaces all of the uses of a variable with uses of the
1786 // constant.
1787 Inst->replaceAllUsesWith(Const);
1788
1789 // Delete the instruction.
Chris Lattnerc27ce6d2009-01-14 21:01:16 +00001790 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
Chris Lattner50846cf2008-04-24 00:21:50 +00001791 Inst->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001792
Chris Lattner50846cf2008-04-24 00:21:50 +00001793 // Hey, we just changed something!
1794 MadeChanges = true;
1795 ++IPNumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796 }
1797 }
1798
1799 // Now that all instructions in the function are constant folded, erase dead
1800 // blocks, because we can now use ConstantFoldTerminator to get rid of
1801 // in-edges.
1802 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1803 // If there are any PHI nodes in this successor, drop entries for BB now.
1804 BasicBlock *DeadBB = BlocksToErase[i];
1805 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001806 Instruction *I = cast<Instruction>(DeadBB->use_back());
1807 bool Folded = ConstantFoldTerminator(I->getParent());
1808 if (!Folded) {
1809 // The constant folder may not have been able to fold the terminator
1810 // if this is a branch or switch on undef. Fold it manually as a
1811 // branch to the first successor.
Devang Patele92c16d2008-11-21 01:52:59 +00001812#ifndef NDEBUG
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1814 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1815 "Branch should be foldable!");
1816 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1817 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1818 } else {
Edwin Törökbd448e32009-07-14 16:55:14 +00001819 llvm_unreachable("Didn't fold away reference to block!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001820 }
Devang Patele92c16d2008-11-21 01:52:59 +00001821#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001822
1823 // Make this an uncond branch to the first successor.
1824 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001825 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001826
1827 // Remove entries in successor phi nodes to remove edges.
1828 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1829 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1830
1831 // Remove the old terminator.
1832 TI->eraseFromParent();
1833 }
1834 }
1835
1836 // Finally, delete the basic block.
1837 F->getBasicBlockList().erase(DeadBB);
1838 }
1839 BlocksToErase.clear();
1840 }
1841
1842 // If we inferred constant or undef return values for a function, we replaced
1843 // all call uses with the inferred value. This means we don't need to bother
1844 // actually returning anything from the function. Replace all return
1845 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001846 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001847 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1849 E = RV.end(); I != E; ++I)
1850 if (!I->second.isOverdefined() &&
Chris Lattner82cdc062009-10-05 05:54:46 +00001851 !I->first->getReturnType()->isVoidTy()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001852 Function *F = I->first;
1853 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1854 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1855 if (!isa<UndefValue>(RI->getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +00001856 RI->setOperand(0, UndefValue::get(F->getReturnType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 }
1858
1859 // If we infered constant or undef values for globals variables, we can delete
1860 // the global and any stores that remain to it.
1861 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1862 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1863 E = TG.end(); I != E; ++I) {
1864 GlobalVariable *GV = I->first;
1865 assert(!I->second.isOverdefined() &&
1866 "Overdefined values should have been taken out of the map!");
Daniel Dunbar23e2b802009-07-26 07:49:05 +00001867 DEBUG(errs() << "Found that GV '" << GV->getName() << "' is constant!\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001868 while (!GV->use_empty()) {
1869 StoreInst *SI = cast<StoreInst>(GV->use_back());
1870 SI->eraseFromParent();
1871 }
1872 M.getGlobalList().erase(GV);
1873 ++IPNumGlobalConst;
1874 }
1875
1876 return MadeChanges;
1877}