* Enable SCCP debugging to be turned on with a simple change of #define
[oota-llvm.git] / lib / Transforms / Scalar / SCCP.cpp
1 //===- SCCP.cpp - Sparse Conditional Constant Propogation -----------------===//
2 //
3 // This file implements sparse conditional constant propogation and merging:
4 //
5 // Specifically, this:
6 //   * Assumes values are constant unless proven otherwise
7 //   * Assumes BasicBlocks are dead unless proven otherwise
8 //   * Proves values to be constant, and replaces them with constants
9 //   . Proves conditional branches constant, and unconditionalizes them
10 //   * Folds multiple identical constants in the constant pool together
11 //
12 // Notice that:
13 //   * This pass has a habit of making definitions be dead.  It is a good idea
14 //     to to run a DCE pass sometime after running this pass.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Scalar/ConstantProp.h"
19 #include "llvm/ConstantHandling.h"
20 #include "llvm/Function.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/iOther.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/STLExtras.h"
28 #include <algorithm>
29 #include <set>
30 #include <iostream>
31 using std::cerr;
32
33 #if 0    // Enable this to get SCCP debug output
34 #define DEBUG_SCCP(X) X
35 #else
36 #define DEBUG_SCCP(X)
37 #endif
38
39 // InstVal class - This class represents the different lattice values that an 
40 // instruction may occupy.  It is a simple class with value semantics.
41 //
42 namespace {
43 class InstVal {
44   enum { 
45     undefined,           // This instruction has no known value
46     constant,            // This instruction has a constant value
47     // Range,            // This instruction is known to fall within a range
48     overdefined          // This instruction has an unknown value
49   } LatticeValue;        // The current lattice position
50   Constant *ConstantVal; // If Constant value, the current value
51 public:
52   inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
53
54   // markOverdefined - Return true if this is a new status to be in...
55   inline bool markOverdefined() {
56     if (LatticeValue != overdefined) {
57       LatticeValue = overdefined;
58       return true;
59     }
60     return false;
61   }
62
63   // markConstant - Return true if this is a new status for us...
64   inline bool markConstant(Constant *V) {
65     if (LatticeValue != constant) {
66       LatticeValue = constant;
67       ConstantVal = V;
68       return true;
69     } else {
70       assert(ConstantVal == V && "Marking constant with different value");
71     }
72     return false;
73   }
74
75   inline bool isUndefined()   const { return LatticeValue == undefined; }
76   inline bool isConstant()    const { return LatticeValue == constant; }
77   inline bool isOverdefined() const { return LatticeValue == overdefined; }
78
79   inline Constant *getConstant() const { return ConstantVal; }
80 };
81
82 } // end anonymous namespace
83
84
85 //===----------------------------------------------------------------------===//
86 // SCCP Class
87 //
88 // This class does all of the work of Sparse Conditional Constant Propogation.
89 //
90 namespace {
91 class SCCP : public FunctionPass, public InstVisitor<SCCP> {
92   std::set<BasicBlock*>     BBExecutable;// The basic blocks that are executable
93   std::map<Value*, InstVal> ValueState;  // The state each value is in...
94
95   std::set<Instruction*>    InstWorkList;// The instruction work list
96   std::vector<BasicBlock*>  BBWorkList;  // The BasicBlock work list
97 public:
98
99   const char *getPassName() const {
100     return "Sparse Conditional Constant Propogation";
101   }
102
103   // runOnFunction - Run the Sparse Conditional Constant Propogation algorithm,
104   // and return true if the function was modified.
105   //
106   bool runOnFunction(Function *F);
107
108   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109     // FIXME: SCCP does not preserve the CFG because it folds terminators!
110     //AU.preservesCFG();
111   }
112
113
114   //===--------------------------------------------------------------------===//
115   // The implementation of this class
116   //
117 private:
118   friend class InstVisitor<SCCP>;        // Allow callbacks from visitor
119
120   // markValueOverdefined - Make a value be marked as "constant".  If the value
121   // is not already a constant, add it to the instruction work list so that 
122   // the users of the instruction are updated later.
123   //
124   inline bool markConstant(Instruction *I, Constant *V) {
125     DEBUG_SCCP(cerr << "markConstant: " << V << " = " << I);
126
127     if (ValueState[I].markConstant(V)) {
128       InstWorkList.insert(I);
129       return true;
130     }
131     return false;
132   }
133
134   // markValueOverdefined - Make a value be marked as "overdefined". If the
135   // value is not already overdefined, add it to the instruction work list so
136   // that the users of the instruction are updated later.
137   //
138   inline bool markOverdefined(Value *V) {
139     if (ValueState[V].markOverdefined()) {
140       if (Instruction *I = dyn_cast<Instruction>(V)) {
141         DEBUG_SCCP(cerr << "markOverdefined: " << V);
142         InstWorkList.insert(I);  // Only instructions go on the work list
143       }
144       return true;
145     }
146     return false;
147   }
148
149   // getValueState - Return the InstVal object that corresponds to the value.
150   // This function is neccesary because not all values should start out in the
151   // underdefined state... Argument's should be overdefined, and
152   // constants should be marked as constants.  If a value is not known to be an
153   // Instruction object, then use this accessor to get its value from the map.
154   //
155   inline InstVal &getValueState(Value *V) {
156     std::map<Value*, InstVal>::iterator I = ValueState.find(V);
157     if (I != ValueState.end()) return I->second;  // Common case, in the map
158       
159     if (Constant *CPV = dyn_cast<Constant>(V)) {  // Constants are constant
160       ValueState[CPV].markConstant(CPV);
161     } else if (isa<Argument>(V)) {                // Arguments are overdefined
162       ValueState[V].markOverdefined();
163     } 
164     // All others are underdefined by default...
165     return ValueState[V];
166   }
167
168   // markExecutable - Mark a basic block as executable, adding it to the BB 
169   // work list if it is not already executable...
170   // 
171   void markExecutable(BasicBlock *BB) {
172     if (BBExecutable.count(BB)) return;
173     DEBUG_SCCP(cerr << "Marking BB Executable: " << BB);
174     BBExecutable.insert(BB);   // Basic block is executable!
175     BBWorkList.push_back(BB);  // Add the block to the work list!
176   }
177
178
179   // visit implementations - Something changed in this instruction... Either an 
180   // operand made a transition, or the instruction is newly executable.  Change
181   // the value type of I to reflect these changes if appropriate.
182   //
183   void visitPHINode(PHINode *I);
184
185   // Terminators
186   void visitReturnInst(ReturnInst *I) { /*does not have an effect*/ }
187   void visitBranchInst(BranchInst *I);
188   void visitInvokeInst(InvokeInst *I);
189   void visitSwitchInst(SwitchInst *I);
190
191   void visitUnaryOperator(Instruction *I);
192   void visitCastInst(CastInst *I) { visitUnaryOperator(I); }
193   void visitBinaryOperator(Instruction *I);
194   void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
195
196   // Instructions that cannot be folded away...
197   void visitStoreInst     (Instruction *I) { /*returns void*/ }
198   void visitMemAccessInst (Instruction *I) { markOverdefined(I); }
199   void visitCallInst      (Instruction *I) { markOverdefined(I); }
200   void visitInvokeInst    (Instruction *I) { markOverdefined(I); }
201   void visitAllocationInst(Instruction *I) { markOverdefined(I); }
202   void visitFreeInst      (Instruction *I) { /*returns void*/ }
203
204   void visitInstruction(Instruction *I) {
205     // If a new instruction is added to LLVM that we don't handle...
206     cerr << "SCCP: Don't know how to handle: " << I;
207     markOverdefined(I);   // Just in case
208   }
209
210   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
211   // block to the 'To' basic block is currently feasible...
212   //
213   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
214
215   // OperandChangedState - This method is invoked on all of the users of an
216   // instruction that was just changed state somehow....  Based on this
217   // information, we need to update the specified user of this instruction.
218   //
219   void OperandChangedState(User *U) {
220     // Only instructions use other variable values!
221     Instruction *I = cast<Instruction>(U);
222     if (!BBExecutable.count(I->getParent())) return;// Inst not executable yet!
223     visit(I);
224   }
225 };
226 } // end anonymous namespace
227
228
229 // createSCCPPass - This is the public interface to this file...
230 //
231 Pass *createSCCPPass() {
232   return new SCCP();
233 }
234
235
236
237 //===----------------------------------------------------------------------===//
238 // SCCP Class Implementation
239
240
241 // runOnFunction() - Run the Sparse Conditional Constant Propogation algorithm,
242 // and return true if the function was modified.
243 //
244 bool SCCP::runOnFunction(Function *F) {
245   // Mark the first block of the function as being executable...
246   markExecutable(F->front());
247
248   // Process the work lists until their are empty!
249   while (!BBWorkList.empty() || !InstWorkList.empty()) {
250     // Process the instruction work list...
251     while (!InstWorkList.empty()) {
252       Instruction *I = *InstWorkList.begin();
253       InstWorkList.erase(InstWorkList.begin());
254
255       DEBUG_SCCP(cerr << "\nPopped off I-WL: " << I);
256
257       
258       // "I" got into the work list because it either made the transition from
259       // bottom to constant, or to Overdefined.
260       //
261       // Update all of the users of this instruction's value...
262       //
263       for_each(I->use_begin(), I->use_end(),
264                bind_obj(this, &SCCP::OperandChangedState));
265     }
266
267     // Process the basic block work list...
268     while (!BBWorkList.empty()) {
269       BasicBlock *BB = BBWorkList.back();
270       BBWorkList.pop_back();
271
272       DEBUG_SCCP(cerr << "\nPopped off BBWL: " << BB);
273
274       // If this block only has a single successor, mark it as executable as
275       // well... if not, terminate the do loop.
276       //
277       if (BB->getTerminator()->getNumSuccessors() == 1)
278         markExecutable(BB->getTerminator()->getSuccessor(0));
279
280       // Notify all instructions in this basic block that they are newly
281       // executable.
282       visit(BB);
283     }
284   }
285
286 #ifdef DEBUG_SCCP
287   for (Function::iterator BBI = F->begin(), BBEnd = F->end();
288        BBI != BBEnd; ++BBI)
289     if (!BBExecutable.count(*BBI))
290       cerr << "BasicBlock Dead:" << *BBI;
291 #endif
292
293
294   // Iterate over all of the instructions in a function, replacing them with
295   // constants if we have found them to be of constant values.
296   //
297   bool MadeChanges = false;
298   for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
299     BasicBlock *BB = *FI;
300     for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
301       Instruction *Inst = *BI;
302       InstVal &IV = ValueState[Inst];
303       if (IV.isConstant()) {
304         Constant *Const = IV.getConstant();
305         DEBUG_SCCP(cerr << "Constant: " << Inst << "  is: " << Const);
306
307         // Replaces all of the uses of a variable with uses of the constant.
308         Inst->replaceAllUsesWith(Const);
309
310         // Remove the operator from the list of definitions... and delete it.
311         delete BB->getInstList().remove(BI);
312
313         // Hey, we just changed something!
314         MadeChanges = true;
315
316         // Do NOT advance the iterator, skipping the next instruction...
317         continue;
318
319       } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Inst)) {
320         MadeChanges |= ConstantFoldTerminator(BB, BI, TI);
321       }
322
323       ++BI;
324     }
325   }
326
327   // Reset state so that the next invocation will have empty data structures
328   BBExecutable.clear();
329   ValueState.clear();
330
331   return MadeChanges;
332 }
333
334 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
335 // block to the 'To' basic block is currently feasible...
336 //
337 bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
338   assert(BBExecutable.count(To) && "Dest should always be alive!");
339
340   // Make sure the source basic block is executable!!
341   if (!BBExecutable.count(From)) return false;
342   
343   // This should check the terminator in From!
344   return true;
345 }
346
347 // visit Implementations - Something changed in this instruction... Either an
348 // operand made a transition, or the instruction is newly executable.  Change
349 // the value type of I to reflect these changes if appropriate.  This method
350 // makes sure to do the following actions:
351 //
352 // 1. If a phi node merges two constants in, and has conflicting value coming
353 //    from different branches, or if the PHI node merges in an overdefined
354 //    value, then the PHI node becomes overdefined.
355 // 2. If a phi node merges only constants in, and they all agree on value, the
356 //    PHI node becomes a constant value equal to that.
357 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
358 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
359 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
360 // 6. If a conditional branch has a value that is constant, make the selected
361 //    destination executable
362 // 7. If a conditional branch has a value that is overdefined, make all
363 //    successors executable.
364 //
365
366 void SCCP::visitPHINode(PHINode *PN) {
367   unsigned NumValues = PN->getNumIncomingValues(), i;
368   InstVal *OperandIV = 0;
369
370   // Look at all of the executable operands of the PHI node.  If any of them
371   // are overdefined, the PHI becomes overdefined as well.  If they are all
372   // constant, and they agree with each other, the PHI becomes the identical
373   // constant.  If they are constant and don't agree, the PHI is overdefined.
374   // If there are no executable operands, the PHI remains undefined.
375   //
376   for (i = 0; i < NumValues; ++i) {
377     if (isEdgeFeasible(PN->getIncomingBlock(i), PN->getParent())) {
378       InstVal &IV = getValueState(PN->getIncomingValue(i));
379       if (IV.isUndefined()) continue;  // Doesn't influence PHI node.
380       if (IV.isOverdefined()) {   // PHI node becomes overdefined!
381         markOverdefined(PN);
382         return;
383       }
384
385       if (OperandIV == 0) {   // Grab the first value...
386         OperandIV = &IV;
387       } else {                // Another value is being merged in!
388         // There is already a reachable operand.  If we conflict with it,
389         // then the PHI node becomes overdefined.  If we agree with it, we
390         // can continue on.
391
392         // Check to see if there are two different constants merging...
393         if (IV.getConstant() != OperandIV->getConstant()) {
394           // Yes there is.  This means the PHI node is not constant.
395           // You must be overdefined poor PHI.
396           //
397           markOverdefined(PN);         // The PHI node now becomes overdefined
398           return;    // I'm done analyzing you
399         }
400       }
401     }
402   }
403
404   // If we exited the loop, this means that the PHI node only has constant
405   // arguments that agree with each other(and OperandIV is a pointer to one
406   // of their InstVal's) or OperandIV is null because there are no defined
407   // incoming arguments.  If this is the case, the PHI remains undefined.
408   //
409   if (OperandIV) {
410     assert(OperandIV->isConstant() && "Should only be here for constants!");
411     markConstant(PN, OperandIV->getConstant());  // Aquire operand value
412   }
413 }
414
415 void SCCP::visitBranchInst(BranchInst *BI) {
416   if (BI->isUnconditional())
417     return; // Unconditional branches are already handled!
418
419   InstVal &BCValue = getValueState(BI->getCondition());
420   if (BCValue.isOverdefined()) {
421     // Overdefined condition variables mean the branch could go either way.
422     markExecutable(BI->getSuccessor(0));
423     markExecutable(BI->getSuccessor(1));
424   } else if (BCValue.isConstant()) {
425     // Constant condition variables mean the branch can only go a single way.
426     if (BCValue.getConstant() == ConstantBool::True)
427       markExecutable(BI->getSuccessor(0));
428     else
429       markExecutable(BI->getSuccessor(1));
430   }
431 }
432
433 void SCCP::visitInvokeInst(InvokeInst *II) {
434   markExecutable(II->getNormalDest());
435   markExecutable(II->getExceptionalDest());
436 }
437
438 void SCCP::visitSwitchInst(SwitchInst *SI) {
439   InstVal &SCValue = getValueState(SI->getCondition());
440   if (SCValue.isOverdefined()) {  // Overdefined condition?  All dests are exe
441     for(unsigned i = 0, E = SI->getNumSuccessors(); i != E; ++i)
442       markExecutable(SI->getSuccessor(i));
443   } else if (SCValue.isConstant()) {
444     Constant *CPV = SCValue.getConstant();
445     // Make sure to skip the "default value" which isn't a value
446     for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
447       if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
448         markExecutable(SI->getSuccessor(i));
449         return;
450       }
451     }
452
453     // Constant value not equal to any of the branches... must execute
454     // default branch then...
455     markExecutable(SI->getDefaultDest());
456   }
457 }
458
459 void SCCP::visitUnaryOperator(Instruction *I) {
460   Value *V = I->getOperand(0);
461   InstVal &VState = getValueState(V);
462   if (VState.isOverdefined()) {        // Inherit overdefinedness of operand
463     markOverdefined(I);
464   } else if (VState.isConstant()) {    // Propogate constant value
465     Constant *Result = isa<CastInst>(I)
466       ? ConstantFoldCastInstruction(VState.getConstant(), I->getType())
467       : ConstantFoldUnaryInstruction(I->getOpcode(), VState.getConstant());
468
469     if (Result) {
470       // This instruction constant folds!
471       markConstant(I, Result);
472     } else {
473       markOverdefined(I);   // Don't know how to fold this instruction.  :(
474     }
475   }
476 }
477
478 // Handle BinaryOperators and Shift Instructions...
479 void SCCP::visitBinaryOperator(Instruction *I) {
480   InstVal &V1State = getValueState(I->getOperand(0));
481   InstVal &V2State = getValueState(I->getOperand(1));
482   if (V1State.isOverdefined() || V2State.isOverdefined()) {
483     markOverdefined(I);
484   } else if (V1State.isConstant() && V2State.isConstant()) {
485     Constant *Result = ConstantFoldBinaryInstruction(I->getOpcode(),
486                                                      V1State.getConstant(),
487                                                      V2State.getConstant());
488     if (Result)
489       markConstant(I, Result);      // This instruction constant folds!
490     else
491       markOverdefined(I);   // Don't know how to fold this instruction.  :(
492   }
493 }