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