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