blob: e299950b8d57df42d65e36037f29b3cf8c9a2d57 [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"
30#include "llvm/Pass.h"
31#include "llvm/Analysis/ConstantFolding.h"
Dan Gohman856193b2008-06-20 01:15:44 +000032#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Transforms/Utils/Local.h"
34#include "llvm/Support/CallSite.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/InstVisitor.h"
38#include "llvm/ADT/DenseMap.h"
Chris Lattnerd3123a72008-08-23 23:36:38 +000039#include "llvm/ADT/DenseSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/ADT/SmallSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
44#include <algorithm>
Dan Gohman249ddbf2008-03-21 23:51:57 +000045#include <map>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046using namespace llvm;
47
48STATISTIC(NumInstRemoved, "Number of instructions removed");
49STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
50
Nick Lewyckybbdfc9c2008-03-08 07:48:41 +000051STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052STATISTIC(IPNumDeadBlocks , "Number of basic blocks unreachable by IPSCCP");
53STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
54STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
55
56namespace {
57/// LatticeVal class - This class represents the different lattice values that
58/// an LLVM value may occupy. It is a simple class with value semantics.
59///
60class VISIBILITY_HIDDEN LatticeVal {
61 enum {
62 /// undefined - This LLVM Value has no known value yet.
63 undefined,
64
65 /// constant - This LLVM Value has a specific constant value.
66 constant,
67
68 /// forcedconstant - This LLVM Value was thought to be undef until
69 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
70 /// with another (different) constant, it goes to overdefined, instead of
71 /// asserting.
72 forcedconstant,
73
74 /// overdefined - This instruction is not known to be constant, and we know
75 /// it has a value.
76 overdefined
77 } LatticeValue; // The current lattice position
78
79 Constant *ConstantVal; // If Constant value, the current value
80public:
81 inline LatticeVal() : LatticeValue(undefined), ConstantVal(0) {}
82
83 // markOverdefined - Return true if this is a new status to be in...
84 inline bool markOverdefined() {
85 if (LatticeValue != overdefined) {
86 LatticeValue = overdefined;
87 return true;
88 }
89 return false;
90 }
91
92 // markConstant - Return true if this is a new status for us.
93 inline bool markConstant(Constant *V) {
94 if (LatticeValue != constant) {
95 if (LatticeValue == undefined) {
96 LatticeValue = constant;
97 assert(V && "Marking constant with NULL");
98 ConstantVal = V;
99 } else {
100 assert(LatticeValue == forcedconstant &&
101 "Cannot move from overdefined to constant!");
102 // Stay at forcedconstant if the constant is the same.
103 if (V == ConstantVal) return false;
104
105 // Otherwise, we go to overdefined. Assumptions made based on the
106 // forced value are possibly wrong. Assuming this is another constant
107 // could expose a contradiction.
108 LatticeValue = overdefined;
109 }
110 return true;
111 } else {
112 assert(ConstantVal == V && "Marking constant with different value");
113 }
114 return false;
115 }
116
117 inline void markForcedConstant(Constant *V) {
118 assert(LatticeValue == undefined && "Can't force a defined value!");
119 LatticeValue = forcedconstant;
120 ConstantVal = V;
121 }
122
123 inline bool isUndefined() const { return LatticeValue == undefined; }
124 inline bool isConstant() const {
125 return LatticeValue == constant || LatticeValue == forcedconstant;
126 }
127 inline bool isOverdefined() const { return LatticeValue == overdefined; }
128
129 inline Constant *getConstant() const {
130 assert(isConstant() && "Cannot get the constant of a non-constant!");
131 return ConstantVal;
132 }
133};
134
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135//===----------------------------------------------------------------------===//
136//
137/// SCCPSolver - This class is a general purpose solver for Sparse Conditional
138/// Constant Propagation.
139///
140class SCCPSolver : public InstVisitor<SCCPSolver> {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000141 DenseSet<BasicBlock*> BBExecutable;// The basic blocks that are executable
Bill Wendling03488ae2008-08-14 23:05:24 +0000142 std::map<Value*, LatticeVal> ValueState; // The state each value is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143
144 /// GlobalValue - If we are tracking any values for the contents of a global
145 /// variable, we keep a mapping from the constant accessor to the element of
146 /// the global, to the currently known value. If the value becomes
147 /// overdefined, it's entry is simply removed from this map.
148 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
149
Devang Pateladd320d2008-03-11 05:46:42 +0000150 /// TrackedRetVals - If we are tracking arguments into and the return
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151 /// value out of a function, it will have an entry in this map, indicating
152 /// what the known return value for the function is.
Devang Pateladd320d2008-03-11 05:46:42 +0000153 DenseMap<Function*, LatticeVal> TrackedRetVals;
154
155 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
156 /// that return multiple values.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000157 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158
159 // The reason for two worklists is that overdefined is the lowest state
160 // on the lattice, and moving things to overdefined as fast as possible
161 // makes SCCP converge much faster.
162 // By having a separate worklist, we accomplish this because everything
163 // possibly overdefined will become overdefined at the soonest possible
164 // point.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000165 SmallVector<Value*, 64> OverdefinedInstWorkList;
166 SmallVector<Value*, 64> InstWorkList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167
168
Chris Lattnerd3123a72008-08-23 23:36:38 +0000169 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
172 /// overdefined, despite the fact that the PHI node is overdefined.
173 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
174
175 /// KnownFeasibleEdges - Entries in this set are edges which have already had
176 /// PHI nodes retriggered.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000177 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
178 DenseSet<Edge> KnownFeasibleEdges;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179public:
180
181 /// MarkBlockExecutable - This method can be used by clients to mark all of
182 /// the blocks that are known to be intrinsically live in the processed unit.
183 void MarkBlockExecutable(BasicBlock *BB) {
Chris Lattner56bf9a92008-05-11 01:55:59 +0000184 DOUT << "Marking Block Executable: " << BB->getNameStart() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 BBExecutable.insert(BB); // Basic block is executable!
186 BBWorkList.push_back(BB); // Add the block to the work list!
187 }
188
189 /// TrackValueOfGlobalVariable - Clients can use this method to
190 /// inform the SCCPSolver that it should track loads and stores to the
191 /// specified global variable if it can. This is only legal to call if
192 /// performing Interprocedural SCCP.
193 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
194 const Type *ElTy = GV->getType()->getElementType();
195 if (ElTy->isFirstClassType()) {
196 LatticeVal &IV = TrackedGlobals[GV];
197 if (!isa<UndefValue>(GV->getInitializer()))
198 IV.markConstant(GV->getInitializer());
199 }
200 }
201
202 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
203 /// and out of the specified function (which cannot have its address taken),
204 /// this method must be called.
205 void AddTrackedFunction(Function *F) {
206 assert(F->hasInternalLinkage() && "Can only track internal functions!");
207 // Add an entry, F -> undef.
Devang Pateladd320d2008-03-11 05:46:42 +0000208 if (const StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
209 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Chris Lattnercd73be02008-04-23 05:38:20 +0000210 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
211 LatticeVal()));
212 } else
213 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 }
215
216 /// Solve - Solve for constants and executable blocks.
217 ///
218 void Solve();
219
220 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
221 /// that branches on undef values cannot reach any of their successors.
222 /// However, this is not a safe assumption. After we solve dataflow, this
223 /// method should be use to handle this. If this returns true, the solver
224 /// should be rerun.
225 bool ResolvedUndefsIn(Function &F);
226
227 /// getExecutableBlocks - Once we have solved for constants, return the set of
228 /// blocks that is known to be executable.
Chris Lattnerd3123a72008-08-23 23:36:38 +0000229 DenseSet<BasicBlock*> &getExecutableBlocks() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 return BBExecutable;
231 }
232
233 /// getValueMapping - Once we have solved for constants, return the mapping of
234 /// LLVM values to LatticeVals.
Bill Wendling03488ae2008-08-14 23:05:24 +0000235 std::map<Value*, LatticeVal> &getValueMapping() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 return ValueState;
237 }
238
Devang Pateladd320d2008-03-11 05:46:42 +0000239 /// getTrackedRetVals - Get the inferred return value map.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 ///
Devang Pateladd320d2008-03-11 05:46:42 +0000241 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
242 return TrackedRetVals;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 }
244
245 /// getTrackedGlobals - Get and return the set of inferred initializers for
246 /// global variables.
247 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
248 return TrackedGlobals;
249 }
250
251 inline void markOverdefined(Value *V) {
252 markOverdefined(ValueState[V], V);
253 }
254
255private:
256 // markConstant - Make a value be marked as "constant". If the value
257 // is not already a constant, add it to the instruction work list so that
258 // the users of the instruction are updated later.
259 //
260 inline void markConstant(LatticeVal &IV, Value *V, Constant *C) {
261 if (IV.markConstant(C)) {
262 DOUT << "markConstant: " << *C << ": " << *V;
263 InstWorkList.push_back(V);
264 }
265 }
266
267 inline void markForcedConstant(LatticeVal &IV, Value *V, Constant *C) {
268 IV.markForcedConstant(C);
269 DOUT << "markForcedConstant: " << *C << ": " << *V;
270 InstWorkList.push_back(V);
271 }
272
273 inline void markConstant(Value *V, Constant *C) {
274 markConstant(ValueState[V], V, C);
275 }
276
277 // markOverdefined - Make a value be marked as "overdefined". If the
278 // value is not already overdefined, add it to the overdefined instruction
279 // work list so that the users of the instruction are updated later.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 inline void markOverdefined(LatticeVal &IV, Value *V) {
281 if (IV.markOverdefined()) {
282 DEBUG(DOUT << "markOverdefined: ";
283 if (Function *F = dyn_cast<Function>(V))
284 DOUT << "Function '" << F->getName() << "'\n";
285 else
286 DOUT << *V);
287 // Only instructions go on the work list
288 OverdefinedInstWorkList.push_back(V);
289 }
290 }
291
292 inline void mergeInValue(LatticeVal &IV, Value *V, LatticeVal &MergeWithV) {
293 if (IV.isOverdefined() || MergeWithV.isUndefined())
294 return; // Noop.
295 if (MergeWithV.isOverdefined())
296 markOverdefined(IV, V);
297 else if (IV.isUndefined())
298 markConstant(IV, V, MergeWithV.getConstant());
299 else if (IV.getConstant() != MergeWithV.getConstant())
300 markOverdefined(IV, V);
301 }
302
303 inline void mergeInValue(Value *V, LatticeVal &MergeWithV) {
304 return mergeInValue(ValueState[V], V, MergeWithV);
305 }
306
307
308 // getValueState - Return the LatticeVal object that corresponds to the value.
309 // This function is necessary because not all values should start out in the
310 // underdefined state... Argument's should be overdefined, and
311 // constants should be marked as constants. If a value is not known to be an
312 // Instruction object, then use this accessor to get its value from the map.
313 //
314 inline LatticeVal &getValueState(Value *V) {
Bill Wendling03488ae2008-08-14 23:05:24 +0000315 std::map<Value*, LatticeVal>::iterator I = ValueState.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 if (I != ValueState.end()) return I->second; // Common case, in the map
317
318 if (Constant *C = dyn_cast<Constant>(V)) {
319 if (isa<UndefValue>(V)) {
320 // Nothing to do, remain undefined.
321 } else {
322 LatticeVal &LV = ValueState[C];
323 LV.markConstant(C); // Constants are constant
324 return LV;
325 }
326 }
327 // All others are underdefined by default...
328 return ValueState[V];
329 }
330
331 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
332 // work list if it is not already executable...
333 //
334 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
335 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
336 return; // This edge is already known to be executable!
337
338 if (BBExecutable.count(Dest)) {
Chris Lattner56bf9a92008-05-11 01:55:59 +0000339 DOUT << "Marking Edge Executable: " << Source->getNameStart()
340 << " -> " << Dest->getNameStart() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341
342 // The destination is already executable, but we just made an edge
343 // feasible that wasn't before. Revisit the PHI nodes in the block
344 // because they have potentially new operands.
345 for (BasicBlock::iterator I = Dest->begin(); isa<PHINode>(I); ++I)
346 visitPHINode(*cast<PHINode>(I));
347
348 } else {
349 MarkBlockExecutable(Dest);
350 }
351 }
352
353 // getFeasibleSuccessors - Return a vector of booleans to indicate which
354 // successors are reachable from a given terminator instruction.
355 //
356 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
357
358 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
359 // block to the 'To' basic block is currently feasible...
360 //
361 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
362
363 // OperandChangedState - This method is invoked on all of the users of an
364 // instruction that was just changed state somehow.... Based on this
365 // information, we need to update the specified user of this instruction.
366 //
367 void OperandChangedState(User *U) {
368 // Only instructions use other variable values!
369 Instruction &I = cast<Instruction>(*U);
370 if (BBExecutable.count(I.getParent())) // Inst is executable?
371 visit(I);
372 }
373
374private:
375 friend class InstVisitor<SCCPSolver>;
376
377 // visit implementations - Something changed in this instruction... Either an
378 // operand made a transition, or the instruction is newly executable. Change
379 // the value type of I to reflect these changes if appropriate.
380 //
381 void visitPHINode(PHINode &I);
382
383 // Terminators
384 void visitReturnInst(ReturnInst &I);
385 void visitTerminatorInst(TerminatorInst &TI);
386
387 void visitCastInst(CastInst &I);
388 void visitSelectInst(SelectInst &I);
389 void visitBinaryOperator(Instruction &I);
390 void visitCmpInst(CmpInst &I);
391 void visitExtractElementInst(ExtractElementInst &I);
392 void visitInsertElementInst(InsertElementInst &I);
393 void visitShuffleVectorInst(ShuffleVectorInst &I);
Dan Gohman856193b2008-06-20 01:15:44 +0000394 void visitExtractValueInst(ExtractValueInst &EVI);
395 void visitInsertValueInst(InsertValueInst &IVI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000396
397 // Instructions that cannot be folded away...
398 void visitStoreInst (Instruction &I);
399 void visitLoadInst (LoadInst &I);
400 void visitGetElementPtrInst(GetElementPtrInst &I);
401 void visitCallInst (CallInst &I) { visitCallSite(CallSite::get(&I)); }
402 void visitInvokeInst (InvokeInst &II) {
403 visitCallSite(CallSite::get(&II));
404 visitTerminatorInst(II);
405 }
406 void visitCallSite (CallSite CS);
407 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
408 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
409 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
410 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
411 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
412 void visitFreeInst (Instruction &I) { /*returns void*/ }
413
414 void visitInstruction(Instruction &I) {
415 // If a new instruction is added to LLVM that we don't handle...
416 cerr << "SCCP: Don't know how to handle: " << I;
417 markOverdefined(&I); // Just in case
418 }
419};
420
Duncan Sands40f67972007-07-20 08:56:21 +0000421} // end anonymous namespace
422
423
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424// getFeasibleSuccessors - Return a vector of booleans to indicate which
425// successors are reachable from a given terminator instruction.
426//
427void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
428 SmallVector<bool, 16> &Succs) {
429 Succs.resize(TI.getNumSuccessors());
430 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
431 if (BI->isUnconditional()) {
432 Succs[0] = true;
433 } else {
434 LatticeVal &BCValue = getValueState(BI->getCondition());
435 if (BCValue.isOverdefined() ||
436 (BCValue.isConstant() && !isa<ConstantInt>(BCValue.getConstant()))) {
437 // Overdefined condition variables, and branches on unfoldable constant
438 // conditions, mean the branch could go either way.
439 Succs[0] = Succs[1] = true;
440 } else if (BCValue.isConstant()) {
441 // Constant condition variables mean the branch can only go a single way
442 Succs[BCValue.getConstant() == ConstantInt::getFalse()] = true;
443 }
444 }
445 } else if (isa<InvokeInst>(&TI)) {
446 // Invoke instructions successors are always executable.
447 Succs[0] = Succs[1] = true;
448 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
449 LatticeVal &SCValue = getValueState(SI->getCondition());
450 if (SCValue.isOverdefined() || // Overdefined condition?
451 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
452 // All destinations are executable!
453 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattner81335532008-05-10 23:56:54 +0000454 } else if (SCValue.isConstant())
455 Succs[SI->findCaseValue(cast<ConstantInt>(SCValue.getConstant()))] = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456 } else {
457 assert(0 && "SCCP: Don't know how to handle this terminator!");
458 }
459}
460
461
462// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
463// block to the 'To' basic block is currently feasible...
464//
465bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
466 assert(BBExecutable.count(To) && "Dest should always be alive!");
467
468 // Make sure the source basic block is executable!!
469 if (!BBExecutable.count(From)) return false;
470
471 // Check to make sure this edge itself is actually feasible now...
472 TerminatorInst *TI = From->getTerminator();
473 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
474 if (BI->isUnconditional())
475 return true;
476 else {
477 LatticeVal &BCValue = getValueState(BI->getCondition());
478 if (BCValue.isOverdefined()) {
479 // Overdefined condition variables mean the branch could go either way.
480 return true;
481 } else if (BCValue.isConstant()) {
482 // Not branching on an evaluatable constant?
483 if (!isa<ConstantInt>(BCValue.getConstant())) return true;
484
485 // Constant condition variables mean the branch can only go a single way
486 return BI->getSuccessor(BCValue.getConstant() ==
487 ConstantInt::getFalse()) == To;
488 }
489 return false;
490 }
491 } else if (isa<InvokeInst>(TI)) {
492 // Invoke instructions successors are always executable.
493 return true;
494 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
495 LatticeVal &SCValue = getValueState(SI->getCondition());
496 if (SCValue.isOverdefined()) { // Overdefined condition?
497 // All destinations are executable!
498 return true;
499 } else if (SCValue.isConstant()) {
500 Constant *CPV = SCValue.getConstant();
501 if (!isa<ConstantInt>(CPV))
502 return true; // not a foldable constant?
503
504 // Make sure to skip the "default value" which isn't a value
505 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
506 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
507 return SI->getSuccessor(i) == To;
508
509 // Constant value not equal to any of the branches... must execute
510 // default branch then...
511 return SI->getDefaultDest() == To;
512 }
513 return false;
514 } else {
515 cerr << "Unknown terminator instruction: " << *TI;
516 abort();
517 }
518}
519
520// visit Implementations - Something changed in this instruction... Either an
521// operand made a transition, or the instruction is newly executable. Change
522// the value type of I to reflect these changes if appropriate. This method
523// makes sure to do the following actions:
524//
525// 1. If a phi node merges two constants in, and has conflicting value coming
526// from different branches, or if the PHI node merges in an overdefined
527// value, then the PHI node becomes overdefined.
528// 2. If a phi node merges only constants in, and they all agree on value, the
529// PHI node becomes a constant value equal to that.
530// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
531// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
532// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
533// 6. If a conditional branch has a value that is constant, make the selected
534// destination executable
535// 7. If a conditional branch has a value that is overdefined, make all
536// successors executable.
537//
538void SCCPSolver::visitPHINode(PHINode &PN) {
539 LatticeVal &PNIV = getValueState(&PN);
540 if (PNIV.isOverdefined()) {
541 // There may be instructions using this PHI node that are not overdefined
542 // themselves. If so, make sure that they know that the PHI node operand
543 // changed.
544 std::multimap<PHINode*, Instruction*>::iterator I, E;
545 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
546 if (I != E) {
547 SmallVector<Instruction*, 16> Users;
548 for (; I != E; ++I) Users.push_back(I->second);
549 while (!Users.empty()) {
550 visit(Users.back());
551 Users.pop_back();
552 }
553 }
554 return; // Quick exit
555 }
556
557 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
558 // and slow us down a lot. Just mark them overdefined.
559 if (PN.getNumIncomingValues() > 64) {
560 markOverdefined(PNIV, &PN);
561 return;
562 }
563
564 // Look at all of the executable operands of the PHI node. If any of them
565 // are overdefined, the PHI becomes overdefined as well. If they are all
566 // constant, and they agree with each other, the PHI becomes the identical
567 // constant. If they are constant and don't agree, the PHI is overdefined.
568 // If there are no executable operands, the PHI remains undefined.
569 //
570 Constant *OperandVal = 0;
571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
572 LatticeVal &IV = getValueState(PN.getIncomingValue(i));
573 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
574
575 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
576 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattnerd3123a72008-08-23 23:36:38 +0000577 markOverdefined(&PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 return;
579 }
580
581 if (OperandVal == 0) { // Grab the first value...
582 OperandVal = IV.getConstant();
583 } else { // Another value is being merged in!
584 // There is already a reachable operand. If we conflict with it,
585 // then the PHI node becomes overdefined. If we agree with it, we
586 // can continue on.
587
588 // Check to see if there are two different constants merging...
589 if (IV.getConstant() != OperandVal) {
590 // Yes there is. This means the PHI node is not constant.
591 // You must be overdefined poor PHI.
592 //
Chris Lattnerd3123a72008-08-23 23:36:38 +0000593 markOverdefined(&PN); // The PHI node now becomes overdefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 return; // I'm done analyzing you
595 }
596 }
597 }
598 }
599
600 // If we exited the loop, this means that the PHI node only has constant
601 // arguments that agree with each other(and OperandVal is the constant) or
602 // OperandVal is null because there are no defined incoming arguments. If
603 // this is the case, the PHI remains undefined.
604 //
605 if (OperandVal)
Chris Lattnerd3123a72008-08-23 23:36:38 +0000606 markConstant(&PN, OperandVal); // Acquire operand value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607}
608
609void SCCPSolver::visitReturnInst(ReturnInst &I) {
610 if (I.getNumOperands() == 0) return; // Ret void
611
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612 Function *F = I.getParent()->getParent();
Devang Pateladd320d2008-03-11 05:46:42 +0000613 // If we are tracking the return value of this function, merge it in.
614 if (!F->hasInternalLinkage())
615 return;
616
Chris Lattnercd73be02008-04-23 05:38:20 +0000617 if (!TrackedRetVals.empty() && I.getNumOperands() == 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 DenseMap<Function*, LatticeVal>::iterator TFRVI =
Devang Pateladd320d2008-03-11 05:46:42 +0000619 TrackedRetVals.find(F);
620 if (TFRVI != TrackedRetVals.end() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 !TFRVI->second.isOverdefined()) {
622 LatticeVal &IV = getValueState(I.getOperand(0));
623 mergeInValue(TFRVI->second, F, IV);
Devang Pateladd320d2008-03-11 05:46:42 +0000624 return;
625 }
626 }
627
Chris Lattnercd73be02008-04-23 05:38:20 +0000628 // Handle functions that return multiple values.
629 if (!TrackedMultipleRetVals.empty() && I.getNumOperands() > 1) {
630 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000631 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Chris Lattnercd73be02008-04-23 05:38:20 +0000632 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
633 if (It == TrackedMultipleRetVals.end()) break;
634 mergeInValue(It->second, F, getValueState(I.getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 }
Dan Gohman856193b2008-06-20 01:15:44 +0000636 } else if (!TrackedMultipleRetVals.empty() &&
637 I.getNumOperands() == 1 &&
638 isa<StructType>(I.getOperand(0)->getType())) {
639 for (unsigned i = 0, e = I.getOperand(0)->getType()->getNumContainedTypes();
640 i != e; ++i) {
Chris Lattnerd3123a72008-08-23 23:36:38 +0000641 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000642 It = TrackedMultipleRetVals.find(std::make_pair(F, i));
643 if (It == TrackedMultipleRetVals.end()) break;
644 Value *Val = FindInsertedValue(I.getOperand(0), i);
645 mergeInValue(It->second, F, getValueState(Val));
646 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 }
648}
649
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
651 SmallVector<bool, 16> SuccFeasible;
652 getFeasibleSuccessors(TI, SuccFeasible);
653
654 BasicBlock *BB = TI.getParent();
655
656 // Mark all feasible successors executable...
657 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
658 if (SuccFeasible[i])
659 markEdgeExecutable(BB, TI.getSuccessor(i));
660}
661
662void SCCPSolver::visitCastInst(CastInst &I) {
663 Value *V = I.getOperand(0);
664 LatticeVal &VState = getValueState(V);
665 if (VState.isOverdefined()) // Inherit overdefinedness of operand
666 markOverdefined(&I);
667 else if (VState.isConstant()) // Propagate constant value
668 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
669 VState.getConstant(), I.getType()));
670}
671
Dan Gohman856193b2008-06-20 01:15:44 +0000672void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000673 Value *Aggr = EVI.getAggregateOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000674
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000675 // If the operand to the extractvalue is an undef, the result is undef.
Dan Gohman856193b2008-06-20 01:15:44 +0000676 if (isa<UndefValue>(Aggr))
677 return;
678
679 // Currently only handle single-index extractvalues.
680 if (EVI.getNumIndices() != 1) {
681 markOverdefined(&EVI);
682 return;
683 }
684
685 Function *F = 0;
686 if (CallInst *CI = dyn_cast<CallInst>(Aggr))
687 F = CI->getCalledFunction();
688 else if (InvokeInst *II = dyn_cast<InvokeInst>(Aggr))
689 F = II->getCalledFunction();
690
691 // TODO: If IPSCCP resolves the callee of this function, we could propagate a
692 // result back!
693 if (F == 0 || TrackedMultipleRetVals.empty()) {
694 markOverdefined(&EVI);
695 return;
696 }
697
Chris Lattnerd3123a72008-08-23 23:36:38 +0000698 // See if we are tracking the result of the callee. If not tracking this
699 // function (for example, it is a declaration) just move to overdefined.
700 if (!TrackedMultipleRetVals.count(std::make_pair(F, *EVI.idx_begin()))) {
Dan Gohman856193b2008-06-20 01:15:44 +0000701 markOverdefined(&EVI);
702 return;
703 }
704
705 // Otherwise, the value will be merged in here as a result of CallSite
706 // handling.
707}
708
709void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000710 Value *Aggr = IVI.getAggregateOperand();
711 Value *Val = IVI.getInsertedValueOperand();
Dan Gohman856193b2008-06-20 01:15:44 +0000712
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000713 // If the operands to the insertvalue are undef, the result is undef.
Dan Gohman78b2c392008-06-20 16:39:44 +0000714 if (isa<UndefValue>(Aggr) && isa<UndefValue>(Val))
Dan Gohman856193b2008-06-20 01:15:44 +0000715 return;
716
717 // Currently only handle single-index insertvalues.
718 if (IVI.getNumIndices() != 1) {
719 markOverdefined(&IVI);
720 return;
721 }
Dan Gohman78b2c392008-06-20 16:39:44 +0000722
723 // Currently only handle insertvalue instructions that are in a single-use
724 // chain that builds up a return value.
725 for (const InsertValueInst *TmpIVI = &IVI; ; ) {
726 if (!TmpIVI->hasOneUse()) {
727 markOverdefined(&IVI);
728 return;
729 }
730 const Value *V = *TmpIVI->use_begin();
731 if (isa<ReturnInst>(V))
732 break;
733 TmpIVI = dyn_cast<InsertValueInst>(V);
734 if (!TmpIVI) {
735 markOverdefined(&IVI);
736 return;
737 }
738 }
Dan Gohman856193b2008-06-20 01:15:44 +0000739
740 // See if we are tracking the result of the callee.
741 Function *F = IVI.getParent()->getParent();
Chris Lattnerd3123a72008-08-23 23:36:38 +0000742 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
Dan Gohman856193b2008-06-20 01:15:44 +0000743 It = TrackedMultipleRetVals.find(std::make_pair(F, *IVI.idx_begin()));
744
745 // Merge in the inserted member value.
746 if (It != TrackedMultipleRetVals.end())
747 mergeInValue(It->second, F, getValueState(Val));
748
Dan Gohmanaa7b7802008-06-20 16:41:17 +0000749 // Mark the aggregate result of the IVI overdefined; any tracking that we do
750 // will be done on the individual member values.
Dan Gohman856193b2008-06-20 01:15:44 +0000751 markOverdefined(&IVI);
752}
753
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754void SCCPSolver::visitSelectInst(SelectInst &I) {
755 LatticeVal &CondValue = getValueState(I.getCondition());
756 if (CondValue.isUndefined())
757 return;
758 if (CondValue.isConstant()) {
759 if (ConstantInt *CondCB = dyn_cast<ConstantInt>(CondValue.getConstant())){
760 mergeInValue(&I, getValueState(CondCB->getZExtValue() ? I.getTrueValue()
761 : I.getFalseValue()));
762 return;
763 }
764 }
765
766 // Otherwise, the condition is overdefined or a constant we can't evaluate.
767 // See if we can produce something better than overdefined based on the T/F
768 // value.
769 LatticeVal &TVal = getValueState(I.getTrueValue());
770 LatticeVal &FVal = getValueState(I.getFalseValue());
771
772 // select ?, C, C -> C.
773 if (TVal.isConstant() && FVal.isConstant() &&
774 TVal.getConstant() == FVal.getConstant()) {
775 markConstant(&I, FVal.getConstant());
776 return;
777 }
778
779 if (TVal.isUndefined()) { // select ?, undef, X -> X.
780 mergeInValue(&I, FVal);
781 } else if (FVal.isUndefined()) { // select ?, X, undef -> X.
782 mergeInValue(&I, TVal);
783 } else {
784 markOverdefined(&I);
785 }
786}
787
788// Handle BinaryOperators and Shift Instructions...
789void SCCPSolver::visitBinaryOperator(Instruction &I) {
790 LatticeVal &IV = ValueState[&I];
791 if (IV.isOverdefined()) return;
792
793 LatticeVal &V1State = getValueState(I.getOperand(0));
794 LatticeVal &V2State = getValueState(I.getOperand(1));
795
796 if (V1State.isOverdefined() || V2State.isOverdefined()) {
797 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
798 // operand is overdefined.
799 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
800 LatticeVal *NonOverdefVal = 0;
801 if (!V1State.isOverdefined()) {
802 NonOverdefVal = &V1State;
803 } else if (!V2State.isOverdefined()) {
804 NonOverdefVal = &V2State;
805 }
806
807 if (NonOverdefVal) {
808 if (NonOverdefVal->isUndefined()) {
809 // Could annihilate value.
810 if (I.getOpcode() == Instruction::And)
811 markConstant(IV, &I, Constant::getNullValue(I.getType()));
812 else if (const VectorType *PT = dyn_cast<VectorType>(I.getType()))
813 markConstant(IV, &I, ConstantVector::getAllOnesValue(PT));
814 else
815 markConstant(IV, &I, ConstantInt::getAllOnesValue(I.getType()));
816 return;
817 } else {
818 if (I.getOpcode() == Instruction::And) {
819 if (NonOverdefVal->getConstant()->isNullValue()) {
820 markConstant(IV, &I, NonOverdefVal->getConstant());
821 return; // X and 0 = 0
822 }
823 } else {
824 if (ConstantInt *CI =
825 dyn_cast<ConstantInt>(NonOverdefVal->getConstant()))
826 if (CI->isAllOnesValue()) {
827 markConstant(IV, &I, NonOverdefVal->getConstant());
828 return; // X or -1 = -1
829 }
830 }
831 }
832 }
833 }
834
835
836 // If both operands are PHI nodes, it is possible that this instruction has
837 // a constant value, despite the fact that the PHI node doesn't. Check for
838 // this condition now.
839 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
840 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
841 if (PN1->getParent() == PN2->getParent()) {
842 // Since the two PHI nodes are in the same basic block, they must have
843 // entries for the same predecessors. Walk the predecessor list, and
844 // if all of the incoming values are constants, and the result of
845 // evaluating this expression with all incoming value pairs is the
846 // same, then this expression is a constant even though the PHI node
847 // is not a constant!
848 LatticeVal Result;
849 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
850 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
851 BasicBlock *InBlock = PN1->getIncomingBlock(i);
852 LatticeVal &In2 =
853 getValueState(PN2->getIncomingValueForBlock(InBlock));
854
855 if (In1.isOverdefined() || In2.isOverdefined()) {
856 Result.markOverdefined();
857 break; // Cannot fold this operation over the PHI nodes!
858 } else if (In1.isConstant() && In2.isConstant()) {
859 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
860 In2.getConstant());
861 if (Result.isUndefined())
862 Result.markConstant(V);
863 else if (Result.isConstant() && Result.getConstant() != V) {
864 Result.markOverdefined();
865 break;
866 }
867 }
868 }
869
870 // If we found a constant value here, then we know the instruction is
871 // constant despite the fact that the PHI nodes are overdefined.
872 if (Result.isConstant()) {
873 markConstant(IV, &I, Result.getConstant());
874 // Remember that this instruction is virtually using the PHI node
875 // operands.
876 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
877 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
878 return;
879 } else if (Result.isUndefined()) {
880 return;
881 }
882
883 // Okay, this really is overdefined now. Since we might have
884 // speculatively thought that this was not overdefined before, and
885 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
886 // make sure to clean out any entries that we put there, for
887 // efficiency.
888 std::multimap<PHINode*, Instruction*>::iterator It, E;
889 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
890 while (It != E) {
891 if (It->second == &I) {
892 UsersOfOverdefinedPHIs.erase(It++);
893 } else
894 ++It;
895 }
896 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
897 while (It != E) {
898 if (It->second == &I) {
899 UsersOfOverdefinedPHIs.erase(It++);
900 } else
901 ++It;
902 }
903 }
904
905 markOverdefined(IV, &I);
906 } else if (V1State.isConstant() && V2State.isConstant()) {
907 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
908 V2State.getConstant()));
909 }
910}
911
912// Handle ICmpInst instruction...
913void SCCPSolver::visitCmpInst(CmpInst &I) {
914 LatticeVal &IV = ValueState[&I];
915 if (IV.isOverdefined()) return;
916
917 LatticeVal &V1State = getValueState(I.getOperand(0));
918 LatticeVal &V2State = getValueState(I.getOperand(1));
919
920 if (V1State.isOverdefined() || V2State.isOverdefined()) {
921 // If both operands are PHI nodes, it is possible that this instruction has
922 // a constant value, despite the fact that the PHI node doesn't. Check for
923 // this condition now.
924 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
925 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
926 if (PN1->getParent() == PN2->getParent()) {
927 // Since the two PHI nodes are in the same basic block, they must have
928 // entries for the same predecessors. Walk the predecessor list, and
929 // if all of the incoming values are constants, and the result of
930 // evaluating this expression with all incoming value pairs is the
931 // same, then this expression is a constant even though the PHI node
932 // is not a constant!
933 LatticeVal Result;
934 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
935 LatticeVal &In1 = getValueState(PN1->getIncomingValue(i));
936 BasicBlock *InBlock = PN1->getIncomingBlock(i);
937 LatticeVal &In2 =
938 getValueState(PN2->getIncomingValueForBlock(InBlock));
939
940 if (In1.isOverdefined() || In2.isOverdefined()) {
941 Result.markOverdefined();
942 break; // Cannot fold this operation over the PHI nodes!
943 } else if (In1.isConstant() && In2.isConstant()) {
944 Constant *V = ConstantExpr::getCompare(I.getPredicate(),
945 In1.getConstant(),
946 In2.getConstant());
947 if (Result.isUndefined())
948 Result.markConstant(V);
949 else if (Result.isConstant() && Result.getConstant() != V) {
950 Result.markOverdefined();
951 break;
952 }
953 }
954 }
955
956 // If we found a constant value here, then we know the instruction is
957 // constant despite the fact that the PHI nodes are overdefined.
958 if (Result.isConstant()) {
959 markConstant(IV, &I, Result.getConstant());
960 // Remember that this instruction is virtually using the PHI node
961 // operands.
962 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
963 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
964 return;
965 } else if (Result.isUndefined()) {
966 return;
967 }
968
969 // Okay, this really is overdefined now. Since we might have
970 // speculatively thought that this was not overdefined before, and
971 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
972 // make sure to clean out any entries that we put there, for
973 // efficiency.
974 std::multimap<PHINode*, Instruction*>::iterator It, E;
975 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
976 while (It != E) {
977 if (It->second == &I) {
978 UsersOfOverdefinedPHIs.erase(It++);
979 } else
980 ++It;
981 }
982 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
983 while (It != E) {
984 if (It->second == &I) {
985 UsersOfOverdefinedPHIs.erase(It++);
986 } else
987 ++It;
988 }
989 }
990
991 markOverdefined(IV, &I);
992 } else if (V1State.isConstant() && V2State.isConstant()) {
993 markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
994 V1State.getConstant(),
995 V2State.getConstant()));
996 }
997}
998
999void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
1000 // FIXME : SCCP does not handle vectors properly.
1001 markOverdefined(&I);
1002 return;
1003
1004#if 0
1005 LatticeVal &ValState = getValueState(I.getOperand(0));
1006 LatticeVal &IdxState = getValueState(I.getOperand(1));
1007
1008 if (ValState.isOverdefined() || IdxState.isOverdefined())
1009 markOverdefined(&I);
1010 else if(ValState.isConstant() && IdxState.isConstant())
1011 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
1012 IdxState.getConstant()));
1013#endif
1014}
1015
1016void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
1017 // FIXME : SCCP does not handle vectors properly.
1018 markOverdefined(&I);
1019 return;
1020#if 0
1021 LatticeVal &ValState = getValueState(I.getOperand(0));
1022 LatticeVal &EltState = getValueState(I.getOperand(1));
1023 LatticeVal &IdxState = getValueState(I.getOperand(2));
1024
1025 if (ValState.isOverdefined() || EltState.isOverdefined() ||
1026 IdxState.isOverdefined())
1027 markOverdefined(&I);
1028 else if(ValState.isConstant() && EltState.isConstant() &&
1029 IdxState.isConstant())
1030 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
1031 EltState.getConstant(),
1032 IdxState.getConstant()));
1033 else if (ValState.isUndefined() && EltState.isConstant() &&
1034 IdxState.isConstant())
1035 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
1036 EltState.getConstant(),
1037 IdxState.getConstant()));
1038#endif
1039}
1040
1041void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
1042 // FIXME : SCCP does not handle vectors properly.
1043 markOverdefined(&I);
1044 return;
1045#if 0
1046 LatticeVal &V1State = getValueState(I.getOperand(0));
1047 LatticeVal &V2State = getValueState(I.getOperand(1));
1048 LatticeVal &MaskState = getValueState(I.getOperand(2));
1049
1050 if (MaskState.isUndefined() ||
1051 (V1State.isUndefined() && V2State.isUndefined()))
1052 return; // Undefined output if mask or both inputs undefined.
1053
1054 if (V1State.isOverdefined() || V2State.isOverdefined() ||
1055 MaskState.isOverdefined()) {
1056 markOverdefined(&I);
1057 } else {
1058 // A mix of constant/undef inputs.
1059 Constant *V1 = V1State.isConstant() ?
1060 V1State.getConstant() : UndefValue::get(I.getType());
1061 Constant *V2 = V2State.isConstant() ?
1062 V2State.getConstant() : UndefValue::get(I.getType());
1063 Constant *Mask = MaskState.isConstant() ?
1064 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
1065 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
1066 }
1067#endif
1068}
1069
1070// Handle getelementptr instructions... if all operands are constants then we
1071// can turn this into a getelementptr ConstantExpr.
1072//
1073void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1074 LatticeVal &IV = ValueState[&I];
1075 if (IV.isOverdefined()) return;
1076
1077 SmallVector<Constant*, 8> Operands;
1078 Operands.reserve(I.getNumOperands());
1079
1080 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1081 LatticeVal &State = getValueState(I.getOperand(i));
1082 if (State.isUndefined())
1083 return; // Operands are not resolved yet...
1084 else if (State.isOverdefined()) {
1085 markOverdefined(IV, &I);
1086 return;
1087 }
1088 assert(State.isConstant() && "Unknown state!");
1089 Operands.push_back(State.getConstant());
1090 }
1091
1092 Constant *Ptr = Operands[0];
1093 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
1094
1095 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, &Operands[0],
1096 Operands.size()));
1097}
1098
1099void SCCPSolver::visitStoreInst(Instruction &SI) {
1100 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1101 return;
1102 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1103 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1104 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1105
1106 // Get the value we are storing into the global.
1107 LatticeVal &PtrVal = getValueState(SI.getOperand(0));
1108
1109 mergeInValue(I->second, GV, PtrVal);
1110 if (I->second.isOverdefined())
1111 TrackedGlobals.erase(I); // No need to keep tracking this!
1112}
1113
1114
1115// Handle load instructions. If the operand is a constant pointer to a constant
1116// global, we can replace the load with the loaded constant value!
1117void SCCPSolver::visitLoadInst(LoadInst &I) {
1118 LatticeVal &IV = ValueState[&I];
1119 if (IV.isOverdefined()) return;
1120
1121 LatticeVal &PtrVal = getValueState(I.getOperand(0));
1122 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1123 if (PtrVal.isConstant() && !I.isVolatile()) {
1124 Value *Ptr = PtrVal.getConstant();
Christopher Lamb2c175392007-12-29 07:56:53 +00001125 // TODO: Consider a target hook for valid address spaces for this xform.
1126 if (isa<ConstantPointerNull>(Ptr) &&
1127 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 // load null -> null
1129 markConstant(IV, &I, Constant::getNullValue(I.getType()));
1130 return;
1131 }
1132
1133 // Transform load (constant global) into the value loaded.
1134 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1135 if (GV->isConstant()) {
1136 if (!GV->isDeclaration()) {
1137 markConstant(IV, &I, GV->getInitializer());
1138 return;
1139 }
1140 } else if (!TrackedGlobals.empty()) {
1141 // If we are tracking this global, merge in the known value for it.
1142 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1143 TrackedGlobals.find(GV);
1144 if (It != TrackedGlobals.end()) {
1145 mergeInValue(IV, &I, It->second);
1146 return;
1147 }
1148 }
1149 }
1150
1151 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
1152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
1153 if (CE->getOpcode() == Instruction::GetElementPtr)
1154 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
1155 if (GV->isConstant() && !GV->isDeclaration())
1156 if (Constant *V =
1157 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) {
1158 markConstant(IV, &I, V);
1159 return;
1160 }
1161 }
1162
1163 // Otherwise we cannot say for certain what value this load will produce.
1164 // Bail out.
1165 markOverdefined(IV, &I);
1166}
1167
1168void SCCPSolver::visitCallSite(CallSite CS) {
1169 Function *F = CS.getCalledFunction();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 Instruction *I = CS.getInstruction();
Chris Lattnercd73be02008-04-23 05:38:20 +00001171
1172 // The common case is that we aren't tracking the callee, either because we
1173 // are not doing interprocedural analysis or the callee is indirect, or is
1174 // external. Handle these cases first.
1175 if (F == 0 || !F->hasInternalLinkage()) {
1176CallOverdefined:
1177 // Void return and not tracking callee, just bail.
1178 if (I->getType() == Type::VoidTy) return;
1179
1180 // Otherwise, if we have a single return value case, and if the function is
1181 // a declaration, maybe we can constant fold it.
1182 if (!isa<StructType>(I->getType()) && F && F->isDeclaration() &&
1183 canConstantFoldCallTo(F)) {
1184
1185 SmallVector<Constant*, 8> Operands;
1186 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1187 AI != E; ++AI) {
1188 LatticeVal &State = getValueState(*AI);
1189 if (State.isUndefined())
1190 return; // Operands are not resolved yet.
1191 else if (State.isOverdefined()) {
1192 markOverdefined(I);
1193 return;
1194 }
1195 assert(State.isConstant() && "Unknown state!");
1196 Operands.push_back(State.getConstant());
1197 }
1198
1199 // If we can constant fold this, mark the result of the call as a
1200 // constant.
1201 if (Constant *C = ConstantFoldCall(F, &Operands[0], Operands.size())) {
1202 markConstant(I, C);
1203 return;
1204 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001205 }
Chris Lattnercd73be02008-04-23 05:38:20 +00001206
1207 // Otherwise, we don't know anything about this call, mark it overdefined.
1208 markOverdefined(I);
1209 return;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 }
1211
Chris Lattnercd73be02008-04-23 05:38:20 +00001212 // If this is a single/zero retval case, see if we're tracking the function.
Dan Gohman856193b2008-06-20 01:15:44 +00001213 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1214 if (TFRVI != TrackedRetVals.end()) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001215 // If so, propagate the return value of the callee into this call result.
1216 mergeInValue(I, TFRVI->second);
Dan Gohman856193b2008-06-20 01:15:44 +00001217 } else if (isa<StructType>(I->getType())) {
Chris Lattnercd73be02008-04-23 05:38:20 +00001218 // Check to see if we're tracking this callee, if not, handle it in the
1219 // common path above.
Chris Lattnerd3123a72008-08-23 23:36:38 +00001220 DenseMap<std::pair<Function*, unsigned>, LatticeVal>::iterator
1221 TMRVI = TrackedMultipleRetVals.find(std::make_pair(F, 0));
Chris Lattnercd73be02008-04-23 05:38:20 +00001222 if (TMRVI == TrackedMultipleRetVals.end())
1223 goto CallOverdefined;
1224
1225 // If we are tracking this callee, propagate the return values of the call
Dan Gohman856193b2008-06-20 01:15:44 +00001226 // into this call site. We do this by walking all the uses. Single-index
1227 // ExtractValueInst uses can be tracked; anything more complicated is
1228 // currently handled conservatively.
Chris Lattnercd73be02008-04-23 05:38:20 +00001229 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1230 UI != E; ++UI) {
Dan Gohman856193b2008-06-20 01:15:44 +00001231 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(*UI)) {
1232 if (EVI->getNumIndices() == 1) {
1233 mergeInValue(EVI,
Dan Gohmanaa7b7802008-06-20 16:41:17 +00001234 TrackedMultipleRetVals[std::make_pair(F, *EVI->idx_begin())]);
Dan Gohman856193b2008-06-20 01:15:44 +00001235 continue;
1236 }
1237 }
1238 // The aggregate value is used in a way not handled here. Assume nothing.
1239 markOverdefined(*UI);
Chris Lattnercd73be02008-04-23 05:38:20 +00001240 }
Dan Gohman856193b2008-06-20 01:15:44 +00001241 } else {
1242 // Otherwise we're not tracking this callee, so handle it in the
1243 // common path above.
1244 goto CallOverdefined;
Chris Lattnercd73be02008-04-23 05:38:20 +00001245 }
1246
1247 // Finally, if this is the first call to the function hit, mark its entry
1248 // block executable.
1249 if (!BBExecutable.count(F->begin()))
1250 MarkBlockExecutable(F->begin());
1251
1252 // Propagate information from this call site into the callee.
1253 CallSite::arg_iterator CAI = CS.arg_begin();
1254 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1255 AI != E; ++AI, ++CAI) {
1256 LatticeVal &IV = ValueState[AI];
1257 if (!IV.isOverdefined())
1258 mergeInValue(IV, AI, getValueState(*CAI));
1259 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260}
1261
1262
1263void SCCPSolver::Solve() {
1264 // Process the work lists until they are empty!
1265 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1266 !OverdefinedInstWorkList.empty()) {
1267 // Process the instruction work list...
1268 while (!OverdefinedInstWorkList.empty()) {
1269 Value *I = OverdefinedInstWorkList.back();
1270 OverdefinedInstWorkList.pop_back();
1271
1272 DOUT << "\nPopped off OI-WL: " << *I;
1273
1274 // "I" got into the work list because it either made the transition from
1275 // bottom to constant
1276 //
1277 // Anything on this worklist that is overdefined need not be visited
1278 // since all of its users will have already been marked as overdefined
1279 // Update all of the users of this instruction's value...
1280 //
1281 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1282 UI != E; ++UI)
1283 OperandChangedState(*UI);
1284 }
1285 // Process the instruction work list...
1286 while (!InstWorkList.empty()) {
1287 Value *I = InstWorkList.back();
1288 InstWorkList.pop_back();
1289
1290 DOUT << "\nPopped off I-WL: " << *I;
1291
1292 // "I" got into the work list because it either made the transition from
1293 // bottom to constant
1294 //
1295 // Anything on this worklist that is overdefined need not be visited
1296 // since all of its users will have already been marked as overdefined.
1297 // Update all of the users of this instruction's value...
1298 //
1299 if (!getValueState(I).isOverdefined())
1300 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1301 UI != E; ++UI)
1302 OperandChangedState(*UI);
1303 }
1304
1305 // Process the basic block work list...
1306 while (!BBWorkList.empty()) {
1307 BasicBlock *BB = BBWorkList.back();
1308 BBWorkList.pop_back();
1309
1310 DOUT << "\nPopped off BBWL: " << *BB;
1311
1312 // Notify all instructions in this basic block that they are newly
1313 // executable.
1314 visit(BB);
1315 }
1316 }
1317}
1318
1319/// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1320/// that branches on undef values cannot reach any of their successors.
1321/// However, this is not a safe assumption. After we solve dataflow, this
1322/// method should be use to handle this. If this returns true, the solver
1323/// should be rerun.
1324///
1325/// This method handles this by finding an unresolved branch and marking it one
1326/// of the edges from the block as being feasible, even though the condition
1327/// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1328/// CFG and only slightly pessimizes the analysis results (by marking one,
1329/// potentially infeasible, edge feasible). This cannot usefully modify the
1330/// constraints on the condition of the branch, as that would impact other users
1331/// of the value.
1332///
1333/// This scan also checks for values that use undefs, whose results are actually
1334/// defined. For example, 'zext i8 undef to i32' should produce all zeros
1335/// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1336/// even if X isn't defined.
1337bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1338 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1339 if (!BBExecutable.count(BB))
1340 continue;
1341
1342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1343 // Look for instructions which produce undef values.
1344 if (I->getType() == Type::VoidTy) continue;
1345
1346 LatticeVal &LV = getValueState(I);
1347 if (!LV.isUndefined()) continue;
1348
1349 // Get the lattice values of the first two operands for use below.
1350 LatticeVal &Op0LV = getValueState(I->getOperand(0));
1351 LatticeVal Op1LV;
1352 if (I->getNumOperands() == 2) {
1353 // If this is a two-operand instruction, and if both operands are
1354 // undefs, the result stays undef.
1355 Op1LV = getValueState(I->getOperand(1));
1356 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1357 continue;
1358 }
1359
1360 // If this is an instructions whose result is defined even if the input is
1361 // not fully defined, propagate the information.
1362 const Type *ITy = I->getType();
1363 switch (I->getOpcode()) {
1364 default: break; // Leave the instruction as an undef.
1365 case Instruction::ZExt:
1366 // After a zero extend, we know the top part is zero. SExt doesn't have
1367 // to be handled here, because we don't know whether the top part is 1's
1368 // or 0's.
1369 assert(Op0LV.isUndefined());
1370 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1371 return true;
1372 case Instruction::Mul:
1373 case Instruction::And:
1374 // undef * X -> 0. X could be zero.
1375 // undef & X -> 0. X could be zero.
1376 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1377 return true;
1378
1379 case Instruction::Or:
1380 // undef | X -> -1. X could be -1.
1381 if (const VectorType *PTy = dyn_cast<VectorType>(ITy))
1382 markForcedConstant(LV, I, ConstantVector::getAllOnesValue(PTy));
1383 else
1384 markForcedConstant(LV, I, ConstantInt::getAllOnesValue(ITy));
1385 return true;
1386
1387 case Instruction::SDiv:
1388 case Instruction::UDiv:
1389 case Instruction::SRem:
1390 case Instruction::URem:
1391 // X / undef -> undef. No change.
1392 // X % undef -> undef. No change.
1393 if (Op1LV.isUndefined()) break;
1394
1395 // undef / X -> 0. X could be maxint.
1396 // undef % X -> 0. X could be 1.
1397 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1398 return true;
1399
1400 case Instruction::AShr:
1401 // undef >>s X -> undef. No change.
1402 if (Op0LV.isUndefined()) break;
1403
1404 // X >>s undef -> X. X could be 0, X could have the high-bit known set.
1405 if (Op0LV.isConstant())
1406 markForcedConstant(LV, I, Op0LV.getConstant());
1407 else
1408 markOverdefined(LV, I);
1409 return true;
1410 case Instruction::LShr:
1411 case Instruction::Shl:
1412 // undef >> X -> undef. No change.
1413 // undef << X -> undef. No change.
1414 if (Op0LV.isUndefined()) break;
1415
1416 // X >> undef -> 0. X could be 0.
1417 // X << undef -> 0. X could be 0.
1418 markForcedConstant(LV, I, Constant::getNullValue(ITy));
1419 return true;
1420 case Instruction::Select:
1421 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1422 if (Op0LV.isUndefined()) {
1423 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1424 Op1LV = getValueState(I->getOperand(2));
1425 } else if (Op1LV.isUndefined()) {
1426 // c ? undef : undef -> undef. No change.
1427 Op1LV = getValueState(I->getOperand(2));
1428 if (Op1LV.isUndefined())
1429 break;
1430 // Otherwise, c ? undef : x -> x.
1431 } else {
1432 // Leave Op1LV as Operand(1)'s LatticeValue.
1433 }
1434
1435 if (Op1LV.isConstant())
1436 markForcedConstant(LV, I, Op1LV.getConstant());
1437 else
1438 markOverdefined(LV, I);
1439 return true;
Chris Lattner9110ac92008-05-24 03:59:33 +00001440 case Instruction::Call:
1441 // If a call has an undef result, it is because it is constant foldable
1442 // but one of the inputs was undef. Just force the result to
1443 // overdefined.
1444 markOverdefined(LV, I);
1445 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 }
1447 }
1448
1449 TerminatorInst *TI = BB->getTerminator();
1450 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1451 if (!BI->isConditional()) continue;
1452 if (!getValueState(BI->getCondition()).isUndefined())
1453 continue;
1454 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Dale Johannesenfb06d0c2008-05-23 01:01:31 +00001455 if (SI->getNumSuccessors()<2) // no cases
1456 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001457 if (!getValueState(SI->getCondition()).isUndefined())
1458 continue;
1459 } else {
1460 continue;
1461 }
1462
Chris Lattner6186e8c2008-01-28 00:32:30 +00001463 // If the edge to the second successor isn't thought to be feasible yet,
1464 // mark it so now. We pick the second one so that this goes to some
1465 // enumerated value in a switch instead of going to the default destination.
1466 if (KnownFeasibleEdges.count(Edge(BB, TI->getSuccessor(1))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467 continue;
1468
1469 // Otherwise, it isn't already thought to be feasible. Mark it as such now
1470 // and return. This will make other blocks reachable, which will allow new
1471 // values to be discovered and existing ones to be moved in the lattice.
Chris Lattner6186e8c2008-01-28 00:32:30 +00001472 markEdgeExecutable(BB, TI->getSuccessor(1));
1473
1474 // This must be a conditional branch of switch on undef. At this point,
1475 // force the old terminator to branch to the first successor. This is
1476 // required because we are now influencing the dataflow of the function with
1477 // the assumption that this edge is taken. If we leave the branch condition
1478 // as undef, then further analysis could think the undef went another way
1479 // leading to an inconsistent set of conclusions.
1480 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1481 BI->setCondition(ConstantInt::getFalse());
1482 } else {
1483 SwitchInst *SI = cast<SwitchInst>(TI);
1484 SI->setCondition(SI->getCaseValue(1));
1485 }
1486
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001487 return true;
1488 }
1489
1490 return false;
1491}
1492
1493
1494namespace {
1495 //===--------------------------------------------------------------------===//
1496 //
1497 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1498 /// Sparse Conditional Constant Propagator.
1499 ///
1500 struct VISIBILITY_HIDDEN SCCP : public FunctionPass {
1501 static char ID; // Pass identification, replacement for typeid
1502 SCCP() : FunctionPass((intptr_t)&ID) {}
1503
1504 // runOnFunction - Run the Sparse Conditional Constant Propagation
1505 // algorithm, and return true if the function was modified.
1506 //
1507 bool runOnFunction(Function &F);
1508
1509 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1510 AU.setPreservesCFG();
1511 }
1512 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513} // end anonymous namespace
1514
Dan Gohman089efff2008-05-13 00:00:25 +00001515char SCCP::ID = 0;
1516static RegisterPass<SCCP>
1517X("sccp", "Sparse Conditional Constant Propagation");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518
1519// createSCCPPass - This is the public interface to this file...
1520FunctionPass *llvm::createSCCPPass() {
1521 return new SCCP();
1522}
1523
1524
1525// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1526// and return true if the function was modified.
1527//
1528bool SCCP::runOnFunction(Function &F) {
Chris Lattner56bf9a92008-05-11 01:55:59 +00001529 DOUT << "SCCP on function '" << F.getNameStart() << "'\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 SCCPSolver Solver;
1531
1532 // Mark the first block of the function as being executable.
1533 Solver.MarkBlockExecutable(F.begin());
1534
1535 // Mark all arguments to the function as being overdefined.
1536 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1537 Solver.markOverdefined(AI);
1538
1539 // Solve for constants.
1540 bool ResolvedUndefs = true;
1541 while (ResolvedUndefs) {
1542 Solver.Solve();
1543 DOUT << "RESOLVING UNDEFs\n";
1544 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1545 }
1546
1547 bool MadeChanges = false;
1548
1549 // If we decided that there are basic blocks that are dead in this function,
1550 // delete their contents now. Note that we cannot actually delete the blocks,
1551 // as we cannot modify the CFG of the function.
1552 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001553 DenseSet<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1554 SmallVector<Instruction*, 512> Insts;
Bill Wendling03488ae2008-08-14 23:05:24 +00001555 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001556
1557 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1558 if (!ExecutableBBs.count(BB)) {
1559 DOUT << " BasicBlock Dead:" << *BB;
1560 ++NumDeadBlocks;
1561
1562 // Delete the instructions backwards, as it has a reduced likelihood of
1563 // having to update as many def-use and use-def chains.
1564 for (BasicBlock::iterator I = BB->begin(), E = BB->getTerminator();
1565 I != E; ++I)
1566 Insts.push_back(I);
1567 while (!Insts.empty()) {
1568 Instruction *I = Insts.back();
1569 Insts.pop_back();
1570 if (!I->use_empty())
1571 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1572 BB->getInstList().erase(I);
1573 MadeChanges = true;
1574 ++NumInstRemoved;
1575 }
1576 } else {
1577 // Iterate over all of the instructions in a function, replacing them with
1578 // constants if we have found them to be of constant values.
1579 //
1580 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1581 Instruction *Inst = BI++;
Chris Lattner204cfde2008-04-24 00:19:54 +00001582 if (Inst->getType() == Type::VoidTy ||
Chris Lattnerb6f89362008-04-24 00:16:28 +00001583 isa<TerminatorInst>(Inst))
1584 continue;
1585
1586 LatticeVal &IV = Values[Inst];
1587 if (!IV.isConstant() && !IV.isUndefined())
1588 continue;
1589
1590 Constant *Const = IV.isConstant()
1591 ? IV.getConstant() : UndefValue::get(Inst->getType());
1592 DOUT << " Constant: " << *Const << " = " << *Inst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593
Chris Lattnerb6f89362008-04-24 00:16:28 +00001594 // Replaces all of the uses of a variable with uses of the constant.
1595 Inst->replaceAllUsesWith(Const);
1596
1597 // Delete the instruction.
1598 Inst->eraseFromParent();
1599
1600 // Hey, we just changed something!
1601 MadeChanges = true;
1602 ++NumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001603 }
1604 }
1605
1606 return MadeChanges;
1607}
1608
1609namespace {
1610 //===--------------------------------------------------------------------===//
1611 //
1612 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1613 /// Constant Propagation.
1614 ///
1615 struct VISIBILITY_HIDDEN IPSCCP : public ModulePass {
1616 static char ID;
1617 IPSCCP() : ModulePass((intptr_t)&ID) {}
1618 bool runOnModule(Module &M);
1619 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001620} // end anonymous namespace
1621
Dan Gohman089efff2008-05-13 00:00:25 +00001622char IPSCCP::ID = 0;
1623static RegisterPass<IPSCCP>
1624Y("ipsccp", "Interprocedural Sparse Conditional Constant Propagation");
1625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626// createIPSCCPPass - This is the public interface to this file...
1627ModulePass *llvm::createIPSCCPPass() {
1628 return new IPSCCP();
1629}
1630
1631
1632static bool AddressIsTaken(GlobalValue *GV) {
1633 // Delete any dead constantexpr klingons.
1634 GV->removeDeadConstantUsers();
1635
1636 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
1637 UI != E; ++UI)
1638 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1639 if (SI->getOperand(0) == GV || SI->isVolatile())
1640 return true; // Storing addr of GV.
1641 } else if (isa<InvokeInst>(*UI) || isa<CallInst>(*UI)) {
1642 // Make sure we are calling the function, not passing the address.
1643 CallSite CS = CallSite::get(cast<Instruction>(*UI));
1644 for (CallSite::arg_iterator AI = CS.arg_begin(),
1645 E = CS.arg_end(); AI != E; ++AI)
1646 if (*AI == GV)
1647 return true;
1648 } else if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1649 if (LI->isVolatile())
1650 return true;
1651 } else {
1652 return true;
1653 }
1654 return false;
1655}
1656
1657bool IPSCCP::runOnModule(Module &M) {
1658 SCCPSolver Solver;
1659
1660 // Loop over all functions, marking arguments to those with their addresses
1661 // taken or that are external as overdefined.
1662 //
1663 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1664 if (!F->hasInternalLinkage() || AddressIsTaken(F)) {
1665 if (!F->isDeclaration())
1666 Solver.MarkBlockExecutable(F->begin());
1667 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1668 AI != E; ++AI)
1669 Solver.markOverdefined(AI);
1670 } else {
1671 Solver.AddTrackedFunction(F);
1672 }
1673
1674 // Loop over global variables. We inform the solver about any internal global
1675 // variables that do not have their 'addresses taken'. If they don't have
1676 // their addresses taken, we can propagate constants through them.
1677 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1678 G != E; ++G)
1679 if (!G->isConstant() && G->hasInternalLinkage() && !AddressIsTaken(G))
1680 Solver.TrackValueOfGlobalVariable(G);
1681
1682 // Solve for constants.
1683 bool ResolvedUndefs = true;
1684 while (ResolvedUndefs) {
1685 Solver.Solve();
1686
1687 DOUT << "RESOLVING UNDEFS\n";
1688 ResolvedUndefs = false;
1689 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1690 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1691 }
1692
1693 bool MadeChanges = false;
1694
1695 // Iterate over all of the instructions in the module, replacing them with
1696 // constants if we have found them to be of constant values.
1697 //
Chris Lattnerd3123a72008-08-23 23:36:38 +00001698 DenseSet<BasicBlock*> &ExecutableBBs = Solver.getExecutableBlocks();
1699 SmallVector<Instruction*, 512> Insts;
1700 SmallVector<BasicBlock*, 512> BlocksToErase;
Bill Wendling03488ae2008-08-14 23:05:24 +00001701 std::map<Value*, LatticeVal> &Values = Solver.getValueMapping();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702
1703 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1704 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1705 AI != E; ++AI)
1706 if (!AI->use_empty()) {
1707 LatticeVal &IV = Values[AI];
1708 if (IV.isConstant() || IV.isUndefined()) {
1709 Constant *CST = IV.isConstant() ?
1710 IV.getConstant() : UndefValue::get(AI->getType());
1711 DOUT << "*** Arg " << *AI << " = " << *CST <<"\n";
1712
1713 // Replaces all of the uses of a variable with uses of the
1714 // constant.
1715 AI->replaceAllUsesWith(CST);
1716 ++IPNumArgsElimed;
1717 }
1718 }
1719
1720 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1721 if (!ExecutableBBs.count(BB)) {
1722 DOUT << " BasicBlock Dead:" << *BB;
1723 ++IPNumDeadBlocks;
1724
1725 // Delete the instructions backwards, as it has a reduced likelihood of
1726 // having to update as many def-use and use-def chains.
1727 TerminatorInst *TI = BB->getTerminator();
1728 for (BasicBlock::iterator I = BB->begin(), E = TI; I != E; ++I)
1729 Insts.push_back(I);
1730
1731 while (!Insts.empty()) {
1732 Instruction *I = Insts.back();
1733 Insts.pop_back();
1734 if (!I->use_empty())
1735 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1736 BB->getInstList().erase(I);
1737 MadeChanges = true;
1738 ++IPNumInstRemoved;
1739 }
1740
1741 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1742 BasicBlock *Succ = TI->getSuccessor(i);
Dan Gohman3f7d94b2007-10-03 19:26:29 +00001743 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 TI->getSuccessor(i)->removePredecessor(BB);
1745 }
1746 if (!TI->use_empty())
1747 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1748 BB->getInstList().erase(TI);
1749
1750 if (&*BB != &F->front())
1751 BlocksToErase.push_back(BB);
1752 else
1753 new UnreachableInst(BB);
1754
1755 } else {
1756 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1757 Instruction *Inst = BI++;
Chris Lattner50846cf2008-04-24 00:21:50 +00001758 if (Inst->getType() == Type::VoidTy ||
Chris Lattner50846cf2008-04-24 00:21:50 +00001759 isa<TerminatorInst>(Inst))
1760 continue;
1761
1762 LatticeVal &IV = Values[Inst];
1763 if (!IV.isConstant() && !IV.isUndefined())
1764 continue;
1765
1766 Constant *Const = IV.isConstant()
1767 ? IV.getConstant() : UndefValue::get(Inst->getType());
1768 DOUT << " Constant: " << *Const << " = " << *Inst;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769
Chris Lattner50846cf2008-04-24 00:21:50 +00001770 // Replaces all of the uses of a variable with uses of the
1771 // constant.
1772 Inst->replaceAllUsesWith(Const);
1773
1774 // Delete the instruction.
1775 if (!isa<CallInst>(Inst))
1776 Inst->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777
Chris Lattner50846cf2008-04-24 00:21:50 +00001778 // Hey, we just changed something!
1779 MadeChanges = true;
1780 ++IPNumInstRemoved;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 }
1782 }
1783
1784 // Now that all instructions in the function are constant folded, erase dead
1785 // blocks, because we can now use ConstantFoldTerminator to get rid of
1786 // in-edges.
1787 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1788 // If there are any PHI nodes in this successor, drop entries for BB now.
1789 BasicBlock *DeadBB = BlocksToErase[i];
1790 while (!DeadBB->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791 Instruction *I = cast<Instruction>(DeadBB->use_back());
1792 bool Folded = ConstantFoldTerminator(I->getParent());
1793 if (!Folded) {
1794 // The constant folder may not have been able to fold the terminator
1795 // if this is a branch or switch on undef. Fold it manually as a
1796 // branch to the first successor.
1797 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1798 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1799 "Branch should be foldable!");
1800 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1801 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1802 } else {
1803 assert(0 && "Didn't fold away reference to block!");
1804 }
1805
1806 // Make this an uncond branch to the first successor.
1807 TerminatorInst *TI = I->getParent()->getTerminator();
Gabor Greifd6da1d02008-04-06 20:25:17 +00001808 BranchInst::Create(TI->getSuccessor(0), TI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809
1810 // Remove entries in successor phi nodes to remove edges.
1811 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1812 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1813
1814 // Remove the old terminator.
1815 TI->eraseFromParent();
1816 }
1817 }
1818
1819 // Finally, delete the basic block.
1820 F->getBasicBlockList().erase(DeadBB);
1821 }
1822 BlocksToErase.clear();
1823 }
1824
1825 // If we inferred constant or undef return values for a function, we replaced
1826 // all call uses with the inferred value. This means we don't need to bother
1827 // actually returning anything from the function. Replace all return
1828 // instructions with return undef.
Devang Pateld04d42b2008-03-11 17:32:05 +00001829 // TODO: Process multiple value ret instructions also.
Devang Pateladd320d2008-03-11 05:46:42 +00001830 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1832 E = RV.end(); I != E; ++I)
1833 if (!I->second.isOverdefined() &&
1834 I->first->getReturnType() != Type::VoidTy) {
1835 Function *F = I->first;
1836 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1837 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1838 if (!isa<UndefValue>(RI->getOperand(0)))
1839 RI->setOperand(0, UndefValue::get(F->getReturnType()));
1840 }
1841
1842 // If we infered constant or undef values for globals variables, we can delete
1843 // the global and any stores that remain to it.
1844 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1845 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1846 E = TG.end(); I != E; ++I) {
1847 GlobalVariable *GV = I->first;
1848 assert(!I->second.isOverdefined() &&
1849 "Overdefined values should have been taken out of the map!");
Chris Lattner56bf9a92008-05-11 01:55:59 +00001850 DOUT << "Found that GV '" << GV->getNameStart() << "' is constant!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001851 while (!GV->use_empty()) {
1852 StoreInst *SI = cast<StoreInst>(GV->use_back());
1853 SI->eraseFromParent();
1854 }
1855 M.getGlobalList().erase(GV);
1856 ++IPNumGlobalConst;
1857 }
1858
1859 return MadeChanges;
1860}