Change SCEVExpander's expandCodeFor to provide more flexibility
[oota-llvm.git] / lib / Analysis / ScalarEvolutionExpander.cpp
1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the implementation of the scalar evolution expander,
11 // which is used to generate the code corresponding to a given scalar evolution
12 // expression.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 using namespace llvm;
19
20 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21 /// we can to share the casts.
22 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V, 
23                                     const Type *Ty) {
24   // Short-circuit unnecessary bitcasts.
25   if (opcode == Instruction::BitCast && V->getType() == Ty)
26     return V;
27
28   // Short-circuit unnecessary inttoptr<->ptrtoint casts.
29   if ((opcode == Instruction::PtrToInt || opcode == Instruction::IntToPtr) &&
30       SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType()))
31     if (CastInst *CI = dyn_cast<CastInst>(V))
32       if ((CI->getOpcode() == Instruction::PtrToInt ||
33            CI->getOpcode() == Instruction::IntToPtr) &&
34           SE.getTypeSizeInBits(CI->getType()) ==
35           SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
36         return CI->getOperand(0);
37
38   // FIXME: keep track of the cast instruction.
39   if (Constant *C = dyn_cast<Constant>(V))
40     return ConstantExpr::getCast(opcode, C, Ty);
41   
42   if (Argument *A = dyn_cast<Argument>(V)) {
43     // Check to see if there is already a cast!
44     for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
45          UI != E; ++UI) {
46       if ((*UI)->getType() == Ty)
47         if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
48           if (CI->getOpcode() == opcode) {
49             // If the cast isn't the first instruction of the function, move it.
50             if (BasicBlock::iterator(CI) != 
51                 A->getParent()->getEntryBlock().begin()) {
52               // If the CastInst is the insert point, change the insert point.
53               if (CI == InsertPt) ++InsertPt;
54               // Splice the cast at the beginning of the entry block.
55               CI->moveBefore(A->getParent()->getEntryBlock().begin());
56             }
57             return CI;
58           }
59     }
60     return CastInst::Create(opcode, V, Ty, V->getName(), 
61                             A->getParent()->getEntryBlock().begin());
62   }
63
64   Instruction *I = cast<Instruction>(V);
65
66   // Check to see if there is already a cast.  If there is, use it.
67   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
68        UI != E; ++UI) {
69     if ((*UI)->getType() == Ty)
70       if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
71         if (CI->getOpcode() == opcode) {
72           BasicBlock::iterator It = I; ++It;
73           if (isa<InvokeInst>(I))
74             It = cast<InvokeInst>(I)->getNormalDest()->begin();
75           while (isa<PHINode>(It)) ++It;
76           if (It != BasicBlock::iterator(CI)) {
77             // If the CastInst is the insert point, change the insert point.
78             if (CI == InsertPt) ++InsertPt;
79             // Splice the cast immediately after the operand in question.
80             CI->moveBefore(It);
81           }
82           return CI;
83         }
84   }
85   BasicBlock::iterator IP = I; ++IP;
86   if (InvokeInst *II = dyn_cast<InvokeInst>(I))
87     IP = II->getNormalDest()->begin();
88   while (isa<PHINode>(IP)) ++IP;
89   return CastInst::Create(opcode, V, Ty, V->getName(), IP);
90 }
91
92 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
93 /// which must be possible with a noop cast.
94 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
95   Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
96   assert((Op == Instruction::BitCast ||
97           Op == Instruction::PtrToInt ||
98           Op == Instruction::IntToPtr) &&
99          "InsertNoopCastOfTo cannot perform non-noop casts!");
100   assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
101          "InsertNoopCastOfTo cannot change sizes!");
102   return InsertCastOfTo(Op, V, Ty);
103 }
104
105 /// InsertBinop - Insert the specified binary operator, doing a small amount
106 /// of work to avoid inserting an obviously redundant operation.
107 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
108                                  Value *RHS, BasicBlock::iterator InsertPt) {
109   // Fold a binop with constant operands.
110   if (Constant *CLHS = dyn_cast<Constant>(LHS))
111     if (Constant *CRHS = dyn_cast<Constant>(RHS))
112       return ConstantExpr::get(Opcode, CLHS, CRHS);
113
114   // Do a quick scan to see if we have this binop nearby.  If so, reuse it.
115   unsigned ScanLimit = 6;
116   BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
117   if (InsertPt != BlockBegin) {
118     // Scanning starts from the last instruction before InsertPt.
119     BasicBlock::iterator IP = InsertPt;
120     --IP;
121     for (; ScanLimit; --IP, --ScanLimit) {
122       if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
123         if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
124             BinOp->getOperand(1) == RHS)
125           return BinOp;
126       if (IP == BlockBegin) break;
127     }
128   }
129   
130   // If we haven't found this binop, insert it.
131   return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
132 }
133
134 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
135   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
136   Value *V = expand(S->getOperand(S->getNumOperands()-1));
137   V = InsertNoopCastOfTo(V, Ty);
138
139   // Emit a bunch of add instructions
140   for (int i = S->getNumOperands()-2; i >= 0; --i) {
141     Value *W = expand(S->getOperand(i));
142     W = InsertNoopCastOfTo(W, Ty);
143     V = InsertBinop(Instruction::Add, V, W, InsertPt);
144   }
145   return V;
146 }
147     
148 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
149   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
150   int FirstOp = 0;  // Set if we should emit a subtract.
151   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
152     if (SC->getValue()->isAllOnesValue())
153       FirstOp = 1;
154
155   int i = S->getNumOperands()-2;
156   Value *V = expand(S->getOperand(i+1));
157   V = InsertNoopCastOfTo(V, Ty);
158
159   // Emit a bunch of multiply instructions
160   for (; i >= FirstOp; --i) {
161     Value *W = expand(S->getOperand(i));
162     W = InsertNoopCastOfTo(W, Ty);
163     V = InsertBinop(Instruction::Mul, V, W, InsertPt);
164   }
165
166   // -1 * ...  --->  0 - ...
167   if (FirstOp == 1)
168     V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
169   return V;
170 }
171
172 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
173   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
174
175   Value *LHS = expand(S->getLHS());
176   LHS = InsertNoopCastOfTo(LHS, Ty);
177   if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
178     const APInt &RHS = SC->getValue()->getValue();
179     if (RHS.isPowerOf2())
180       return InsertBinop(Instruction::LShr, LHS,
181                          ConstantInt::get(Ty, RHS.logBase2()),
182                          InsertPt);
183   }
184
185   Value *RHS = expand(S->getRHS());
186   RHS = InsertNoopCastOfTo(RHS, Ty);
187   return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
188 }
189
190 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
191   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
192   const Loop *L = S->getLoop();
193
194   // {X,+,F} --> X + {0,+,F}
195   if (!S->getStart()->isZero()) {
196     Value *Start = expand(S->getStart());
197     Start = InsertNoopCastOfTo(Start, Ty);
198     std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
199     NewOps[0] = SE.getIntegerSCEV(0, Ty);
200     Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
201     Rest = InsertNoopCastOfTo(Rest, Ty);
202
203     // FIXME: look for an existing add to use.
204     return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
205   }
206
207   // {0,+,1} --> Insert a canonical induction variable into the loop!
208   if (S->isAffine() &&
209       S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
210     // Create and insert the PHI node for the induction variable in the
211     // specified loop.
212     BasicBlock *Header = L->getHeader();
213     PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
214     PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
215
216     pred_iterator HPI = pred_begin(Header);
217     assert(HPI != pred_end(Header) && "Loop with zero preds???");
218     if (!L->contains(*HPI)) ++HPI;
219     assert(HPI != pred_end(Header) && L->contains(*HPI) &&
220            "No backedge in loop?");
221
222     // Insert a unit add instruction right before the terminator corresponding
223     // to the back-edge.
224     Constant *One = ConstantInt::get(Ty, 1);
225     Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
226                                                  (*HPI)->getTerminator());
227
228     pred_iterator PI = pred_begin(Header);
229     if (*PI == L->getLoopPreheader())
230       ++PI;
231     PN->addIncoming(Add, *PI);
232     return PN;
233   }
234
235   // Get the canonical induction variable I for this loop.
236   Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
237
238   // If this is a simple linear addrec, emit it now as a special case.
239   if (S->isAffine()) {   // {0,+,F} --> i*F
240     Value *F = expand(S->getOperand(1));
241     F = InsertNoopCastOfTo(F, Ty);
242     
243     // IF the step is by one, just return the inserted IV.
244     if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
245       if (CI->getValue() == 1)
246         return I;
247     
248     // If the insert point is directly inside of the loop, emit the multiply at
249     // the insert point.  Otherwise, L is a loop that is a parent of the insert
250     // point loop.  If we can, move the multiply to the outer most loop that it
251     // is safe to be in.
252     BasicBlock::iterator MulInsertPt = getInsertionPoint();
253     Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
254     if (InsertPtLoop != L && InsertPtLoop &&
255         L->contains(InsertPtLoop->getHeader())) {
256       do {
257         // If we cannot hoist the multiply out of this loop, don't.
258         if (!InsertPtLoop->isLoopInvariant(F)) break;
259
260         BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
261
262         // If this loop hasn't got a preheader, we aren't able to hoist the
263         // multiply.
264         if (!InsertPtLoopPH)
265           break;
266
267         // Otherwise, move the insert point to the preheader.
268         MulInsertPt = InsertPtLoopPH->getTerminator();
269         InsertPtLoop = InsertPtLoop->getParentLoop();
270       } while (InsertPtLoop != L);
271     }
272     
273     return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
274   }
275
276   // If this is a chain of recurrences, turn it into a closed form, using the
277   // folders, then expandCodeFor the closed form.  This allows the folders to
278   // simplify the expression without having to build a bunch of special code
279   // into this folder.
280   SCEVHandle IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
281
282   SCEVHandle V = S->evaluateAtIteration(IH, SE);
283   //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
284
285   return expand(V);
286 }
287
288 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
289   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
290   Value *V = expand(S->getOperand());
291   V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
292   return new TruncInst(V, Ty, "tmp.", InsertPt);
293 }
294
295 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
296   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
297   Value *V = expand(S->getOperand());
298   V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
299   return new ZExtInst(V, Ty, "tmp.", InsertPt);
300 }
301
302 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
303   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
304   Value *V = expand(S->getOperand());
305   V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
306   return new SExtInst(V, Ty, "tmp.", InsertPt);
307 }
308
309 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
310   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
311   Value *LHS = expand(S->getOperand(0));
312   LHS = InsertNoopCastOfTo(LHS, Ty);
313   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
314     Value *RHS = expand(S->getOperand(i));
315     RHS = InsertNoopCastOfTo(RHS, Ty);
316     Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
317     LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
318   }
319   return LHS;
320 }
321
322 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
323   const Type *Ty = SE.getEffectiveSCEVType(S->getType());
324   Value *LHS = expand(S->getOperand(0));
325   LHS = InsertNoopCastOfTo(LHS, Ty);
326   for (unsigned i = 1; i < S->getNumOperands(); ++i) {
327     Value *RHS = expand(S->getOperand(i));
328     RHS = InsertNoopCastOfTo(RHS, Ty);
329     Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
330     LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
331   }
332   return LHS;
333 }
334
335 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
336   // Expand the code for this SCEV.
337   assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
338          "non-trivial casts should be done with the SCEVs directly!");
339   Value *V = expand(SH);
340   return InsertNoopCastOfTo(V, Ty);
341 }
342
343 Value *SCEVExpander::expand(const SCEV *S) {
344   // Check to see if we already expanded this.
345   std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
346   if (I != InsertedExpressions.end())
347     return I->second;
348   
349   Value *V = visit(S);
350   InsertedExpressions[S] = V;
351   return V;
352 }