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