ScalarEvolutionExpander.cpp revision 3e6307698084e7adfc10b739442ae29742beefd0
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  for (BasicBlock::iterator IP = InsertPt, E = InsertPt->getParent()->begin();
85       ScanLimit; --IP, --ScanLimit) {
86    if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
87      if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
88          BinOp->getOperand(1) == RHS) {
89        // If we found the instruction *at* the insert point, insert later
90        // instructions after it.
91        if (BinOp == InsertPt)
92          InsertPt = ++IP;
93        return BinOp;
94      }
95    if (IP == E) break;
96  }
97
98  // If we don't have
99  return BinaryOperator::create(Opcode, LHS, RHS, "tmp", InsertPt);
100}
101
102Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
103  int FirstOp = 0;  // Set if we should emit a subtract.
104  if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
105    if (SC->getValue()->isAllOnesValue())
106      FirstOp = 1;
107
108  int i = S->getNumOperands()-2;
109  Value *V = expand(S->getOperand(i+1));
110
111  // Emit a bunch of multiply instructions
112  for (; i >= FirstOp; --i)
113    V = InsertBinop(Instruction::Mul, V, expand(S->getOperand(i)),
114                    InsertPt);
115  // -1 * ...  --->  0 - ...
116  if (FirstOp == 1)
117    V = InsertBinop(Instruction::Sub, Constant::getNullValue(V->getType()), V,
118                    InsertPt);
119  return V;
120}
121
122Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
123  const Type *Ty = S->getType();
124  const Loop *L = S->getLoop();
125  // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
126  assert(Ty->isInteger() && "Cannot expand fp recurrences yet!");
127
128  // {X,+,F} --> X + {0,+,F}
129  if (!isa<SCEVConstant>(S->getStart()) ||
130      !cast<SCEVConstant>(S->getStart())->getValue()->isZero()) {
131    Value *Start = expand(S->getStart());
132    std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
133    NewOps[0] = SE.getIntegerSCEV(0, Ty);
134    Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
135
136    // FIXME: look for an existing add to use.
137    return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
138  }
139
140  // {0,+,1} --> Insert a canonical induction variable into the loop!
141  if (S->getNumOperands() == 2 &&
142      S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
143    // Create and insert the PHI node for the induction variable in the
144    // specified loop.
145    BasicBlock *Header = L->getHeader();
146    PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
147    PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
148
149    pred_iterator HPI = pred_begin(Header);
150    assert(HPI != pred_end(Header) && "Loop with zero preds???");
151    if (!L->contains(*HPI)) ++HPI;
152    assert(HPI != pred_end(Header) && L->contains(*HPI) &&
153           "No backedge in loop?");
154
155    // Insert a unit add instruction right before the terminator corresponding
156    // to the back-edge.
157    Constant *One = ConstantInt::get(Ty, 1);
158    Instruction *Add = BinaryOperator::createAdd(PN, One, "indvar.next",
159                                                 (*HPI)->getTerminator());
160
161    pred_iterator PI = pred_begin(Header);
162    if (*PI == L->getLoopPreheader())
163      ++PI;
164    PN->addIncoming(Add, *PI);
165    return PN;
166  }
167
168  // Get the canonical induction variable I for this loop.
169  Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
170
171  // If this is a simple linear addrec, emit it now as a special case.
172  if (S->getNumOperands() == 2) {   // {0,+,F} --> i*F
173    Value *F = expand(S->getOperand(1));
174
175    // IF the step is by one, just return the inserted IV.
176    if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
177      if (CI->getValue() == 1)
178        return I;
179
180    // If the insert point is directly inside of the loop, emit the multiply at
181    // the insert point.  Otherwise, L is a loop that is a parent of the insert
182    // point loop.  If we can, move the multiply to the outer most loop that it
183    // is safe to be in.
184    Instruction *MulInsertPt = InsertPt;
185    Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
186    if (InsertPtLoop != L && InsertPtLoop &&
187        L->contains(InsertPtLoop->getHeader())) {
188      while (InsertPtLoop != L) {
189        // If we cannot hoist the multiply out of this loop, don't.
190        if (!InsertPtLoop->isLoopInvariant(F)) break;
191
192        // Otherwise, move the insert point to the preheader of the loop.
193        MulInsertPt = InsertPtLoop->getLoopPreheader()->getTerminator();
194        InsertPtLoop = InsertPtLoop->getParentLoop();
195      }
196    }
197
198    return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
199  }
200
201  // If this is a chain of recurrences, turn it into a closed form, using the
202  // folders, then expandCodeFor the closed form.  This allows the folders to
203  // simplify the expression without having to build a bunch of special code
204  // into this folder.
205  SCEVHandle IH = SE.getUnknown(I);   // Get I as a "symbolic" SCEV.
206
207  SCEVHandle V = S->evaluateAtIteration(IH, SE);
208  //cerr << "Evaluated: " << *this << "\n     to: " << *V << "\n";
209
210  return expand(V);
211}
212
213Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
214  Value *LHS = expand(S->getOperand(0));
215  for (unsigned i = 1; i < S->getNumOperands(); ++i) {
216    Value *RHS = expand(S->getOperand(i));
217    Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
218    LHS = new SelectInst(ICmp, LHS, RHS, "smax", InsertPt);
219  }
220  return LHS;
221}
222
223Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
224  Value *LHS = expand(S->getOperand(0));
225  for (unsigned i = 1; i < S->getNumOperands(); ++i) {
226    Value *RHS = expand(S->getOperand(i));
227    Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
228    LHS = new SelectInst(ICmp, LHS, RHS, "umax", InsertPt);
229  }
230  return LHS;
231}
232
233Value *SCEVExpander::expand(SCEV *S) {
234  // Check to see if we already expanded this.
235  std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
236  if (I != InsertedExpressions.end())
237    return I->second;
238
239  Value *V = visit(S);
240  InsertedExpressions[S] = V;
241  return V;
242}
243