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