Minor code cleanup
[oota-llvm.git] / lib / Analysis / InductionVariable.cpp
1 //===- InductionVariable.cpp - Induction variable classification ----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements identification and classification of induction 
11 // variables.  Induction variables must contain a PHI node that exists in a 
12 // loop header.  Because of this, they are identified an managed by this PHI 
13 // node.
14 //
15 // Induction variables are classified into a type.  Knowing that an induction
16 // variable is of a specific type can constrain the values of the start and
17 // step.  For example, a SimpleLinear induction variable must have a start and
18 // step values that are constants.
19 //
20 // Induction variables can be created with or without loop information.  If no
21 // loop information is available, induction variables cannot be recognized to be
22 // more than SimpleLinear variables.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/Analysis/InductionVariable.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/Analysis/Expressions.h"
29 #include "llvm/BasicBlock.h"
30 #include "llvm/iPHINode.h"
31 #include "llvm/iOperators.h"
32 #include "llvm/iTerminators.h"
33 #include "llvm/Type.h"
34 #include "llvm/Constants.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Assembly/Writer.h"
37 #include "Support/Debug.h"
38
39 namespace llvm {
40
41 static bool isLoopInvariant(const Value *V, const Loop *L) {
42   if (const Instruction *I = dyn_cast<Instruction>(V))
43     return !L->contains(I->getParent());
44   // non-instructions all dominate instructions/blocks
45   return true;
46 }
47
48 enum InductionVariable::iType
49 InductionVariable::Classify(const Value *Start, const Value *Step,
50                             const Loop *L) {
51   // Check for canonical and simple linear expressions now...
52   if (const ConstantInt *CStart = dyn_cast<ConstantInt>(Start))
53     if (const ConstantInt *CStep = dyn_cast<ConstantInt>(Step)) {
54       if (CStart->isNullValue() && CStep->equalsInt(1))
55         return Canonical;
56       else
57         return SimpleLinear;
58     }
59
60   // Without loop information, we cannot do any better, so bail now...
61   if (L == 0) return Unknown;
62
63   if (isLoopInvariant(Start, L) && isLoopInvariant(Step, L))
64     return Linear;
65   return Unknown;
66 }
67
68 // Create an induction variable for the specified value.  If it is a PHI, and
69 // if it's recognizable, classify it and fill in instance variables.
70 //
71 InductionVariable::InductionVariable(PHINode *P, LoopInfo *LoopInfo): End(0) {
72   InductionType = Unknown;     // Assume the worst
73   Phi = P;
74   
75   // If the PHI node has more than two predecessors, we don't know how to
76   // handle it.
77   //
78   if (Phi->getNumIncomingValues() != 2) return;
79
80   // FIXME: Handle FP induction variables.
81   if (Phi->getType() == Type::FloatTy || Phi->getType() == Type::DoubleTy)
82     return;
83
84   // If we have loop information, make sure that this PHI node is in the header
85   // of a loop...
86   //
87   const Loop *L = LoopInfo ? LoopInfo->getLoopFor(Phi->getParent()) : 0;
88   if (L && L->getHeader() != Phi->getParent())
89     return;
90
91   Value *V1 = Phi->getIncomingValue(0);
92   Value *V2 = Phi->getIncomingValue(1);
93
94   if (L == 0) {  // No loop information?  Base everything on expression analysis
95     ExprType E1 = ClassifyExpression(V1);
96     ExprType E2 = ClassifyExpression(V2);
97
98     if (E1.ExprTy > E2.ExprTy)        // Make E1 be the simpler expression
99       std::swap(E1, E2);
100     
101     // E1 must be a constant incoming value, and E2 must be a linear expression
102     // with respect to the PHI node.
103     //
104     if (E1.ExprTy > ExprType::Constant || E2.ExprTy != ExprType::Linear ||
105         E2.Var != Phi)
106       return;
107
108     // Okay, we have found an induction variable. Save the start and step values
109     const Type *ETy = Phi->getType();
110     if (isa<PointerType>(ETy)) ETy = Type::ULongTy;
111
112     Start = (Value*)(E1.Offset ? E1.Offset : ConstantInt::get(ETy, 0));
113     Step  = (Value*)(E2.Offset ? E2.Offset : ConstantInt::get(ETy, 0));
114   } else {
115     // Okay, at this point, we know that we have loop information...
116
117     // Make sure that V1 is the incoming value, and V2 is from the backedge of
118     // the loop.
119     if (L->contains(Phi->getIncomingBlock(0)))     // Wrong order.  Swap now.
120       std::swap(V1, V2);
121     
122     Start = V1;     // We know that Start has to be loop invariant...
123     Step = 0;
124
125     if (V2 == Phi) {  // referencing the PHI directly?  Must have zero step
126       Step = Constant::getNullValue(Phi->getType());
127     } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(V2)) {
128       // TODO: This could be much better...
129       if (I->getOpcode() == Instruction::Add) {
130         if (I->getOperand(0) == Phi)
131           Step = I->getOperand(1);
132         else if (I->getOperand(1) == Phi)
133           Step = I->getOperand(0);
134       }
135     }
136
137     if (Step == 0) {                  // Unrecognized step value...
138       ExprType StepE = ClassifyExpression(V2);
139       if (StepE.ExprTy != ExprType::Linear ||
140           StepE.Var != Phi) return;
141
142       const Type *ETy = Phi->getType();
143       if (isa<PointerType>(ETy)) ETy = Type::ULongTy;
144       Step  = (Value*)(StepE.Offset ? StepE.Offset : ConstantInt::get(ETy, 0));
145     } else {   // We were able to get a step value, simplify with expr analysis
146       ExprType StepE = ClassifyExpression(Step);
147       if (StepE.ExprTy == ExprType::Linear && StepE.Offset == 0) {
148         // No offset from variable?  Grab the variable
149         Step = StepE.Var;
150       } else if (StepE.ExprTy == ExprType::Constant) {
151         if (StepE.Offset)
152           Step = (Value*)StepE.Offset;
153         else
154           Step = Constant::getNullValue(Step->getType());
155         const Type *ETy = Phi->getType();
156         if (isa<PointerType>(ETy)) ETy = Type::ULongTy;
157         Step  = (Value*)(StepE.Offset ? StepE.Offset : ConstantInt::get(ETy,0));
158       }
159     }
160   }
161
162   // Classify the induction variable type now...
163   InductionType = InductionVariable::Classify(Start, Step, L);
164 }
165
166
167 Value *InductionVariable::getExecutionCount(LoopInfo *LoopInfo) {
168   if (InductionType != Canonical) return 0;
169
170   DEBUG(std::cerr << "entering getExecutionCount\n");
171
172   // Don't recompute if already available
173   if (End) {
174     DEBUG(std::cerr << "returning cached End value.\n");
175     return End;
176   }
177
178   const Loop *L = LoopInfo ? LoopInfo->getLoopFor(Phi->getParent()) : 0;
179   if (!L) {
180     DEBUG(std::cerr << "null loop. oops\n");
181     return 0;
182   }
183
184   // >1 backedge => cannot predict number of iterations
185   if (Phi->getNumIncomingValues() != 2) {
186     DEBUG(std::cerr << ">2 incoming values. oops\n");
187     return 0;
188   }
189
190   // Find final node: predecessor of the loop header that's also an exit
191   BasicBlock *terminator = 0;
192   for (pred_iterator PI = pred_begin(L->getHeader()),
193          PE = pred_end(L->getHeader()); PI != PE; ++PI)
194     if (L->isLoopExit(*PI)) {
195       terminator = *PI;
196       break;
197     }
198
199   // Break in the loop => cannot predict number of iterations
200   // break: any block which is an exit node whose successor is not in loop,
201   // and this block is not marked as the terminator
202   //
203   const std::vector<BasicBlock*> &blocks = L->getBlocks();
204   for (std::vector<BasicBlock*>::const_iterator I = blocks.begin(),
205          e = blocks.end(); I != e; ++I)
206     if (L->isLoopExit(*I) && *I != terminator)
207       for (succ_iterator SI = succ_begin(*I), SE = succ_end(*I); SI != SE; ++SI)
208         if (!L->contains(*SI)) {
209           DEBUG(std::cerr << "break found in loop");
210           return 0;
211         }
212
213   BranchInst *B = dyn_cast<BranchInst>(terminator->getTerminator());
214   if (!B) {
215     DEBUG(std::cerr << "Terminator is not a cond branch!");
216     return 0; 
217   }
218   SetCondInst *SCI = dyn_cast<SetCondInst>(B->getCondition());
219   if (!SCI) {
220     DEBUG(std::cerr << "Not a cond branch on setcc!\n");
221     return 0;
222   }
223
224   DEBUG(std::cerr << "sci:" << *SCI);
225   Value *condVal0 = SCI->getOperand(0);
226   Value *condVal1 = SCI->getOperand(1);
227
228   // The induction variable is the one coming from the backedge
229   Value *indVar = Phi->getIncomingValue(L->contains(Phi->getIncomingBlock(1)));
230
231
232   // Check to see if indVar is one of the parameters in SCI and if the other is
233   // loop-invariant, it is the UB
234   if (indVar == condVal0) {
235     if (isLoopInvariant(condVal1, L))
236       End = condVal1;
237     else {
238       DEBUG(std::cerr << "not loop invariant 1\n");
239       return 0;
240     }
241   } else if (indVar == condVal1) {
242     if (isLoopInvariant(condVal0, L))
243       End = condVal0;
244     else {
245       DEBUG(std::cerr << "not loop invariant 0\n");
246       return 0;
247     }
248   } else {
249     DEBUG(std::cerr << "Loop condition doesn't directly uses indvar\n");
250     return 0;
251   }
252
253   switch (SCI->getOpcode()) {
254   case Instruction::SetLT:
255   case Instruction::SetNE: return End; // already done
256   case Instruction::SetLE:
257     // if compared to a constant int N, then predict N+1 iterations
258     if (ConstantSInt *ubSigned = dyn_cast<ConstantSInt>(End)) {
259       DEBUG(std::cerr << "signed int constant\n");
260       return ConstantSInt::get(ubSigned->getType(), ubSigned->getValue()+1);
261     } else if (ConstantUInt *ubUnsigned = dyn_cast<ConstantUInt>(End)) {
262       DEBUG(std::cerr << "unsigned int constant\n");
263       return ConstantUInt::get(ubUnsigned->getType(),
264                                ubUnsigned->getValue()+1);
265     } else {
266       DEBUG(std::cerr << "symbolic bound\n");
267       // new expression N+1, insert right before the SCI.  FIXME: If End is loop
268       // invariant, then so is this expression.  We should insert it in the loop
269       // preheader if it exists.
270       return BinaryOperator::create(Instruction::Add, End, 
271                                     ConstantInt::get(End->getType(), 1),
272                                     "tripcount", SCI);
273     }
274
275   default:
276     return 0; // cannot predict
277   }
278 }
279
280
281 void InductionVariable::print(std::ostream &o) const {
282   switch (InductionType) {
283   case InductionVariable::Canonical:    o << "Canonical ";    break;
284   case InductionVariable::SimpleLinear: o << "SimpleLinear "; break;
285   case InductionVariable::Linear:       o << "Linear ";       break;
286   case InductionVariable::Unknown:      o << "Unrecognized "; break;
287   }
288   o << "Induction Variable: ";
289   if (Phi) {
290     WriteAsOperand(o, Phi);
291     o << ":\n" << Phi;
292   } else {
293     o << "\n";
294   }
295   if (InductionType == InductionVariable::Unknown) return;
296
297   o << "  Start = "; WriteAsOperand(o, Start);
298   o << "  Step = " ; WriteAsOperand(o, Step);
299   if (End) { 
300     o << "  End = " ; WriteAsOperand(o, End);
301   }
302   o << "\n";
303 }
304
305 } // End llvm namespace