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