Convert more code to use new style casts
[oota-llvm.git] / lib / Transforms / Scalar / InductionVars.cpp
1 //===- InductionVars.cpp - Induction Variable Cannonicalization code --------=//
2 //
3 // This file implements induction variable cannonicalization of loops.
4 //
5 // Specifically, after this executes, the following is true:
6 //   - There is a single induction variable for each loop (at least loops that
7 //     used to contain at least one induction variable)
8 //   * This induction variable starts at 0 and steps by 1 per iteration
9 //   * This induction variable is represented by the first PHI node in the
10 //     Header block, allowing it to be found easily.
11 //   - All other preexisting induction variables are adjusted to operate in
12 //     terms of this primary induction variable
13 //   - Induction variables with a step size of 0 have been eliminated.
14 //
15 // This code assumes the following is true to perform its full job:
16 //   - The CFG has been simplified to not have multiple entrances into an
17 //     interval header.  Interval headers should only have two predecessors,
18 //     one from inside of the loop and one from outside of the loop.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Optimizations/InductionVars.h"
23 #include "llvm/ConstPoolVals.h"
24 #include "llvm/Analysis/IntervalPartition.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/Support/STLExtras.h"
27 #include "llvm/SymbolTable.h"
28 #include "llvm/iOther.h"
29 #include <algorithm>
30
31 #include "llvm/Analysis/LoopDepth.h"
32
33 using namespace opt;
34
35 // isLoopInvariant - Return true if the specified value/basic block source is 
36 // an interval invariant computation.
37 //
38 static bool isLoopInvariant(cfg::Interval *Int, Value *V) {
39   assert(isa<ConstPoolVal>(V) || isa<Instruction>(V) || isa<MethodArgument>(V));
40
41   if (!isa<Instruction>(V))
42     return true;  // Constants and arguments are always loop invariant
43
44   BasicBlock *ValueBlock = ((Instruction*)V)->getParent();
45   assert(ValueBlock && "Instruction not embedded in basic block!");
46
47   // For now, only consider values from outside of the interval, regardless of
48   // whether the expression could be lifted out of the loop by some LICM.
49   //
50   // TODO: invoke LICM library if we find out it would be useful.
51   //
52   return !Int->contains(ValueBlock);
53 }
54
55
56 // isLinearInductionVariableH - Return isLIV if the expression V is a linear
57 // expression defined in terms of loop invariant computations, and a single
58 // instance of the PHI node PN.  Return isLIC if the expression V is a loop
59 // invariant computation.  Return isNLIV if the expression is a negated linear
60 // induction variable.  Return isOther if it is neither.
61 //
62 // Currently allowed operators are: ADD, SUB, NEG
63 // TODO: This should allow casts!
64 //
65 enum LIVType { isLIV, isLIC, isNLIV, isOther };
66 //
67 // neg - Negate the sign of a LIV expression.
68 inline LIVType neg(LIVType T) { 
69   assert(T == isLIV || T == isNLIV && "Negate Only works on LIV expressions");
70   return T == isLIV ? isNLIV : isLIV; 
71 }
72 //
73 static LIVType isLinearInductionVariableH(cfg::Interval *Int, Value *V,
74                                           PHINode *PN) {
75   if (V == PN) { return isLIV; }  // PHI node references are (0+PHI)
76   if (isLoopInvariant(Int, V)) return isLIC;
77
78   // loop variant computations must be instructions!
79   Instruction *I = cast<Instruction>(V);
80   switch (I->getOpcode()) {       // Handle each instruction seperately
81   case Instruction::Add:
82   case Instruction::Sub: {
83     Value *SubV1 = ((BinaryOperator*)I)->getOperand(0);
84     Value *SubV2 = ((BinaryOperator*)I)->getOperand(1);
85     LIVType SubLIVType1 = isLinearInductionVariableH(Int, SubV1, PN);
86     if (SubLIVType1 == isOther) return isOther;  // Early bailout
87     LIVType SubLIVType2 = isLinearInductionVariableH(Int, SubV2, PN);
88
89     switch (SubLIVType2) {
90     case isOther: return isOther;      // Unknown subexpression type
91     case isLIC:   return SubLIVType1;  // Constant offset, return type #1
92     case isLIV:
93     case isNLIV:
94       // So now we know that we have a linear induction variable on the RHS of
95       // the ADD or SUB instruction.  SubLIVType1 cannot be isOther, so it is
96       // either a Loop Invariant computation, or a LIV type.
97       if (SubLIVType1 == isLIC) {
98         // Loop invariant computation, we know this is a LIV then.
99         return (I->getOpcode() == Instruction::Add) ? 
100                        SubLIVType2 : neg(SubLIVType2);
101       }
102
103       // If the LHS is also a LIV Expression, we cannot add two LIVs together
104       if (I->getOpcode() == Instruction::Add) return isOther;
105
106       // We can only subtract two LIVs if they are the same type, which yields
107       // a LIC, because the LIVs cancel each other out.
108       return (SubLIVType1 == SubLIVType2) ? isLIC : isOther;
109     }
110     // NOT REACHED
111   }
112
113   default:            // Any other instruction is not a LINEAR induction var
114     return isOther;
115   }
116 }
117
118 // isLinearInductionVariable - Return true if the specified expression is a
119 // "linear induction variable", which is an expression involving a single 
120 // instance of the PHI node and a loop invariant value that is added or
121 // subtracted to the PHI node.  This is calculated by walking the SSA graph
122 //
123 static inline bool isLinearInductionVariable(cfg::Interval *Int, Value *V,
124                                              PHINode *PN) {
125   return isLinearInductionVariableH(Int, V, PN) == isLIV;
126 }
127
128
129 // isSimpleInductionVar - Return true iff the cannonical induction variable PN
130 // has an initializer of the constant value 0, and has a step size of constant 
131 // 1.
132 static inline bool isSimpleInductionVar(PHINode *PN) {
133   assert(PN->getNumIncomingValues() == 2 && "Must have cannonical PHI node!");
134   Value *Initializer = PN->getIncomingValue(0);
135   if (!isa<ConstPoolVal>(Initializer)) return false;
136
137   if (Initializer->getType()->isSigned()) {  // Signed constant value...
138     if (((ConstPoolSInt*)Initializer)->getValue() != 0) return false;
139   } else if (Initializer->getType()->isUnsigned()) {  // Unsigned constant value
140     if (((ConstPoolUInt*)Initializer)->getValue() != 0) return false;
141   } else {
142     return false;   // Not signed or unsigned?  Must be FP type or something
143   }
144
145   Value *StepExpr = PN->getIncomingValue(1);
146   if (!isa<Instruction>(StepExpr) ||
147       ((Instruction*)StepExpr)->getOpcode() != Instruction::Add)
148     return false;
149
150   BinaryOperator *I = (BinaryOperator*)StepExpr;
151   assert(isa<Instruction>(I->getOperand(0)) && 
152       ((Instruction*)I->getOperand(0))->isPHINode() &&
153          "PHI node should be first operand of ADD instruction!");
154
155   // Get the right hand side of the ADD node.  See if it is a constant 1.
156   Value *StepSize = I->getOperand(1);
157   if (!isa<ConstPoolVal>(StepSize)) return false;
158
159   if (StepSize->getType()->isSigned()) {  // Signed constant value...
160     if (((ConstPoolSInt*)StepSize)->getValue() != 1) return false;
161   } else if (StepSize->getType()->isUnsigned()) {  // Unsigned constant value
162     if (((ConstPoolUInt*)StepSize)->getValue() != 1) return false;
163   } else {
164     return false;   // Not signed or unsigned?  Must be FP type or something
165   }
166
167   // At this point, we know the initializer is a constant value 0 and the step
168   // size is a constant value 1.  This is our simple induction variable!
169   return true;
170 }
171
172 // InjectSimpleInductionVariable - Insert a cannonical induction variable into
173 // the interval header Header.  This assumes that the flow graph is in 
174 // simplified form (so we know that the header block has exactly 2 predecessors)
175 //
176 // TODO: This should inherit the largest type that is being used by the already
177 // present induction variables (instead of always using uint)
178 //
179 static PHINode *InjectSimpleInductionVariable(cfg::Interval *Int) {
180   string PHIName, AddName;
181
182   BasicBlock *Header = Int->getHeaderNode();
183   Method *M = Header->getParent();
184
185   if (M->hasSymbolTable()) {
186     // Only name the induction variable if the method isn't stripped.
187     PHIName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var");
188     AddName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var_next");
189   }
190
191   // Create the neccesary instructions...
192   PHINode        *PN      = new PHINode(Type::UIntTy, PHIName);
193   ConstPoolVal   *One     = ConstPoolUInt::get(Type::UIntTy, 1);
194   ConstPoolVal   *Zero    = ConstPoolUInt::get(Type::UIntTy, 0);
195   BinaryOperator *AddNode = BinaryOperator::create(Instruction::Add, 
196                                                    PN, One, AddName);
197
198   // Figure out which predecessors I have to play with... there should be
199   // exactly two... one of which is a loop predecessor, and one of which is not.
200   //
201   BasicBlock::pred_iterator PI = Header->pred_begin();
202   assert(PI != Header->pred_end() && "Header node should have 2 preds!");
203   BasicBlock *Pred1 = *PI; ++PI;
204   assert(PI != Header->pred_end() && "Header node should have 2 preds!");
205   BasicBlock *Pred2 = *PI;
206   assert(++PI == Header->pred_end() && "Header node should have 2 preds!");
207
208   // Make Pred1 be the loop entrance predecessor, Pred2 be the Loop predecessor
209   if (Int->contains(Pred1)) swap(Pred1, Pred2);
210
211   assert(!Int->contains(Pred1) && "Pred1 should be loop entrance!");
212   assert( Int->contains(Pred2) && "Pred2 should be looping edge!");
213
214   // Link the instructions into the PHI node...
215   PN->addIncoming(Zero, Pred1);     // The initializer is first argument
216   PN->addIncoming(AddNode, Pred2);  // The step size is second PHI argument
217   
218   // Insert the PHI node into the Header of the loop.  It shall be the first
219   // instruction, because the "Simple" Induction Variable must be first in the
220   // block.
221   //
222   BasicBlock::InstListType &IL = Header->getInstList();
223   IL.push_front(PN);
224
225   // Insert the Add instruction as the first (non-phi) instruction in the 
226   // header node's basic block.
227   BasicBlock::iterator I = IL.begin();
228   while ((*I)->isPHINode()) ++I;
229   IL.insert(I, AddNode);
230   return PN;
231 }
232
233 // ProcessInterval - This function is invoked once for each interval in the 
234 // IntervalPartition of the program.  It looks for auxilliary induction
235 // variables in loops.  If it finds one, it:
236 // * Cannonicalizes the induction variable.  This consists of:
237 //   A. Making the first element of the PHI node be the loop invariant 
238 //      computation, and the second element be the linear induction portion.
239 //   B. Changing the first element of the linear induction portion of the PHI 
240 //      node to be of the form ADD(PHI, <loop invariant expr>).
241 // * Add the induction variable PHI to a list of induction variables found.
242 //
243 // After this, a list of cannonical induction variables is known.  This list
244 // is searched to see if there is an induction variable that counts from 
245 // constant 0 with a step size of constant 1.  If there is not one, one is
246 // injected into the loop.  Thus a "simple" induction variable is always known
247 //
248 // One a simple induction variable is known, all other induction variables are
249 // modified to refer to the "simple" induction variable.
250 //
251 static bool ProcessInterval(cfg::Interval *Int) {
252   if (!Int->isLoop()) return false;  // Not a loop?  Ignore it!
253
254   vector<PHINode *> InductionVars;
255
256   BasicBlock *Header = Int->getHeaderNode();
257   // Loop over all of the PHI nodes in the interval header...
258   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); 
259        I != E && (*I)->isPHINode(); ++I) {
260     PHINode *PN = (PHINode*)*I;
261     if (PN->getNumIncomingValues() != 2) { // These should be eliminated by now.
262       cerr << "Found interval header with more than 2 predecessors! Ignoring\n";
263       return false;    // Todo, make an assertion.
264     }
265
266     // For this to be an induction variable, one of the arguments must be a
267     // loop invariant expression, and the other must be an expression involving
268     // the PHI node, along with possible additions and subtractions of loop
269     // invariant values.
270     //
271     BasicBlock *BB1 = PN->getIncomingBlock(0);
272     Value      *V1  = PN->getIncomingValue(0);
273     BasicBlock *BB2 = PN->getIncomingBlock(1);
274     Value      *V2  = PN->getIncomingValue(1);
275
276     // Figure out which computation is loop invariant...
277     if (!isLoopInvariant(Int, V1)) {
278       // V1 is *not* loop invariant.  Check to see if V2 is:
279       if (isLoopInvariant(Int, V2)) {
280         // They *are* loop invariant.  Exchange BB1/BB2 and V1/V2 so that
281         // V1 is always the loop invariant computation.
282         swap(V1, V2); swap(BB1, BB2);
283       } else {
284         // Neither value is loop invariant.  Must not be an induction variable.
285         // This case can happen if there is an unreachable loop in the CFG that
286         // has two tail loops in it that was not split by the cleanup phase
287         // before.
288         continue;
289       }      
290     }
291
292     // At this point, we know that BB1/V1 are loop invariant.  We don't know
293     // anything about BB2/V2.  Check now to see if V2 is a linear induction
294     // variable.
295     //
296     cerr << "Found loop invariant computation: " << V1 << endl;
297     
298     if (!isLinearInductionVariable(Int, V2, PN))
299       continue;         // No, it is not a linear ind var, ignore the PHI node.
300     cerr << "Found linear induction variable: " << V2;
301
302     // TODO: Cannonicalize V2
303
304     // Add this PHI node to the list of induction variables found...
305     InductionVars.push_back(PN);    
306   }
307
308   // No induction variables found?
309   if (InductionVars.empty()) return false;
310
311   // Search to see if there is already a "simple" induction variable.
312   vector<PHINode*>::iterator It = 
313     find_if(InductionVars.begin(), InductionVars.end(), isSimpleInductionVar);
314   
315   PHINode *PrimaryIndVar;
316
317   // A simple induction variable was not found, inject one now...
318   if (It == InductionVars.end()) {
319     PrimaryIndVar = InjectSimpleInductionVariable(Int);
320   } else {
321     // Move the PHI node for this induction variable to the start of the PHI
322     // list in HeaderNode... we do not need to do this for the inserted case
323     // because the inserted node will always be placed at the beginning of
324     // HeaderNode.
325     //
326     PrimaryIndVar = *It;
327     BasicBlock::iterator i =
328       find(Header->begin(), Header->end(), PrimaryIndVar);
329     assert(i != Header->end() && 
330            "How could Primary IndVar not be in the header!?!!?");
331
332     if (i != Header->begin())
333       iter_swap(i, Header->begin());
334   }
335
336   // Now we know that there is a simple induction variable PrimaryIndVar.
337   // Simplify all of the other induction variables to use this induction 
338   // variable as their counter, and destroy the PHI nodes that correspond to
339   // the old indvars.
340   //
341   // TODO
342
343
344   cerr << "Found Interval Header with indvars (primary indvar should be first "
345        << "phi): \n" << Header << "\nPrimaryIndVar: " << PrimaryIndVar;
346
347   return false;  // TODO: true;
348 }
349
350
351 // ProcessIntervalPartition - This function loops over the interval partition
352 // processing each interval with ProcessInterval
353 //
354 static bool ProcessIntervalPartition(cfg::IntervalPartition &IP) {
355   // This currently just prints out information about the interval structure
356   // of the method...
357 #if 0
358   static unsigned N = 0;
359   cerr << "\n***********Interval Partition #" << (++N) << "************\n\n";
360   copy(IP.begin(), IP.end(), ostream_iterator<cfg::Interval*>(cerr, "\n"));
361
362   cerr << "\n*********** PERFORMING WORK ************\n\n";
363 #endif
364   // Loop over all of the intervals in the partition and look for induction
365   // variables in intervals that represent loops.
366   //
367   return reduce_apply(IP.begin(), IP.end(), bitwise_or<bool>(), false,
368                       ptr_fun(ProcessInterval));
369 }
370
371 // DoInductionVariableCannonicalize - Simplify induction variables in loops.
372 // This function loops over an interval partition of a program, reducing it
373 // until the graph is gone.
374 //
375 bool opt::DoInductionVariableCannonicalize(Method *M) {
376   // TODO: REMOVE
377   if (0) {   // Print basic blocks with their depth
378     LoopDepthCalculator LDC(M);
379     for (Method::iterator I = M->begin(); I != M->end(); ++I) {
380       cerr << "Basic Block Depth: " << LDC.getLoopDepth(*I) << *I;
381     }
382   }
383
384
385   cfg::IntervalPartition *IP = new cfg::IntervalPartition(M);
386   bool Changed = false;
387
388   while (!IP->isDegeneratePartition()) {
389     Changed |= ProcessIntervalPartition(*IP);
390
391     // Calculate the reduced version of this graph until we get to an 
392     // irreducible graph or a degenerate graph...
393     //
394     cfg::IntervalPartition *NewIP = new cfg::IntervalPartition(*IP, false);
395     if (NewIP->size() == IP->size()) {
396       cerr << "IRREDUCIBLE GRAPH FOUND!!!\n";
397       return Changed;
398     }
399     delete IP;
400     IP = NewIP;
401   }
402
403   delete IP;
404   return Changed;
405 }