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