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