blob: f3e508ab7b173ed3c1eb9711a80d3a1201016850 [file] [log] [blame]
Nate Begeman36f891b2005-07-30 00:12:19 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman36f891b2005-07-30 00:12:19 +00007//
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
Nate Begeman36f891b2005-07-30 00:12:19 +000016#include "llvm/Analysis/ScalarEvolutionExpander.h"
Bill Wendlinge8156192006-12-07 01:30:32 +000017#include "llvm/Analysis/LoopInfo.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000018using namespace llvm;
19
Chris Lattnerca1a4be2006-02-04 09:51:53 +000020/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
21/// we can to share the casts.
Reid Spencer3ba68b92006-12-13 08:06:42 +000022Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
23 const Type *Ty) {
Chris Lattnerca1a4be2006-02-04 09:51:53 +000024 // FIXME: keep track of the cast instruction.
25 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000026 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000027
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))) {
Reid Spencer3da59db2006-11-27 01:05:10 +000034 // If the cast isn't the first instruction of the function, move it.
Chris Lattnerca1a4be2006-02-04 09:51:53 +000035 if (BasicBlock::iterator(CI) !=
36 A->getParent()->getEntryBlock().begin()) {
37 CI->moveBefore(A->getParent()->getEntryBlock().begin());
38 }
39 return CI;
40 }
41 }
Reid Spencerd977d862006-12-12 23:36:14 +000042 return CastInst::create(opcode, V, Ty, V->getName(),
43 A->getParent()->getEntryBlock().begin());
Chris Lattnerca1a4be2006-02-04 09:51:53 +000044 }
45
46 Instruction *I = cast<Instruction>(V);
47
48 // Check to see if there is already a cast. If there is, use it.
49 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
50 UI != E; ++UI) {
51 if ((*UI)->getType() == Ty)
52 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI))) {
53 BasicBlock::iterator It = I; ++It;
54 if (isa<InvokeInst>(I))
55 It = cast<InvokeInst>(I)->getNormalDest()->begin();
56 while (isa<PHINode>(It)) ++It;
57 if (It != BasicBlock::iterator(CI)) {
58 // Splice the cast immediately after the operand in question.
59 CI->moveBefore(It);
60 }
61 return CI;
62 }
63 }
64 BasicBlock::iterator IP = I; ++IP;
65 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
66 IP = II->getNormalDest()->begin();
67 while (isa<PHINode>(IP)) ++IP;
Reid Spencerd977d862006-12-12 23:36:14 +000068 return CastInst::create(opcode, V, Ty, V->getName(), IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000069}
70
Chris Lattner7fec90e2007-04-13 05:04:18 +000071/// InsertBinop - Insert the specified binary operator, doing a small amount
72/// of work to avoid inserting an obviously redundant operation.
73Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Chris Lattnerb1b2f0b2007-04-17 23:43:50 +000074 Value *RHS, Instruction *&InsertPt) {
Dan Gohman0f0eb182007-06-15 19:21:55 +000075 // Fold a binop with constant operands.
76 if (Constant *CLHS = dyn_cast<Constant>(LHS))
77 if (Constant *CRHS = dyn_cast<Constant>(RHS))
78 return ConstantExpr::get(Opcode, CLHS, CRHS);
79
Chris Lattner7fec90e2007-04-13 05:04:18 +000080 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
81 unsigned ScanLimit = 6;
82 for (BasicBlock::iterator IP = InsertPt, E = InsertPt->getParent()->begin();
83 ScanLimit; --IP, --ScanLimit) {
84 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
85 if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
Chris Lattnerb1b2f0b2007-04-17 23:43:50 +000086 BinOp->getOperand(1) == RHS) {
87 // If we found the instruction *at* the insert point, insert later
88 // instructions after it.
89 if (BinOp == InsertPt)
90 InsertPt = ++IP;
Chris Lattner7fec90e2007-04-13 05:04:18 +000091 return BinOp;
Chris Lattnerb1b2f0b2007-04-17 23:43:50 +000092 }
Chris Lattner7fec90e2007-04-13 05:04:18 +000093 if (IP == E) break;
94 }
95
96 // If we don't have
Dan Gohman693f5412007-09-14 20:11:40 +000097 return BinaryOperator::create(Opcode, LHS, RHS, "tmp", InsertPt);
Chris Lattner7fec90e2007-04-13 05:04:18 +000098}
99
Nate Begeman36f891b2005-07-30 00:12:19 +0000100Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000101 int FirstOp = 0; // Set if we should emit a subtract.
102 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
103 if (SC->getValue()->isAllOnesValue())
104 FirstOp = 1;
105
106 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000107 Value *V = expand(S->getOperand(i+1));
Nate Begeman36f891b2005-07-30 00:12:19 +0000108
109 // Emit a bunch of multiply instructions
110 for (; i >= FirstOp; --i)
Dan Gohmand19534a2007-06-15 14:38:12 +0000111 V = InsertBinop(Instruction::Mul, V, expand(S->getOperand(i)),
Chris Lattner7fec90e2007-04-13 05:04:18 +0000112 InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000113 // -1 * ... ---> 0 - ...
114 if (FirstOp == 1)
Chris Lattner7fec90e2007-04-13 05:04:18 +0000115 V = InsertBinop(Instruction::Sub, Constant::getNullValue(V->getType()), V,
116 InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000117 return V;
118}
119
120Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
121 const Type *Ty = S->getType();
122 const Loop *L = S->getLoop();
123 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
Chris Lattner42a75512007-01-15 02:27:26 +0000124 assert(Ty->isInteger() && "Cannot expand fp recurrences yet!");
Nate Begeman36f891b2005-07-30 00:12:19 +0000125
126 // {X,+,F} --> X + {0,+,F}
127 if (!isa<SCEVConstant>(S->getStart()) ||
Reid Spencercae57542007-03-02 00:28:52 +0000128 !cast<SCEVConstant>(S->getStart())->getValue()->isZero()) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000129 Value *Start = expand(S->getStart());
Nate Begeman36f891b2005-07-30 00:12:19 +0000130 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000131 NewOps[0] = SE.getIntegerSCEV(0, Ty);
132 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
Nate Begeman36f891b2005-07-30 00:12:19 +0000133
134 // FIXME: look for an existing add to use.
Chris Lattner7fec90e2007-04-13 05:04:18 +0000135 return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000136 }
137
138 // {0,+,1} --> Insert a canonical induction variable into the loop!
139 if (S->getNumOperands() == 2 &&
Dan Gohman246b2562007-10-22 18:31:58 +0000140 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000141 // Create and insert the PHI node for the induction variable in the
142 // specified loop.
143 BasicBlock *Header = L->getHeader();
144 PHINode *PN = new PHINode(Ty, "indvar", Header->begin());
145 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
146
147 pred_iterator HPI = pred_begin(Header);
148 assert(HPI != pred_end(Header) && "Loop with zero preds???");
149 if (!L->contains(*HPI)) ++HPI;
150 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
151 "No backedge in loop?");
152
153 // Insert a unit add instruction right before the terminator corresponding
154 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000155 Constant *One = ConstantInt::get(Ty, 1);
Nate Begeman36f891b2005-07-30 00:12:19 +0000156 Instruction *Add = BinaryOperator::createAdd(PN, One, "indvar.next",
157 (*HPI)->getTerminator());
158
159 pred_iterator PI = pred_begin(Header);
160 if (*PI == L->getLoopPreheader())
161 ++PI;
162 PN->addIncoming(Add, *PI);
163 return PN;
164 }
165
166 // Get the canonical induction variable I for this loop.
167 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
168
Chris Lattnerdf14a042005-10-30 06:24:33 +0000169 // If this is a simple linear addrec, emit it now as a special case.
Nate Begeman36f891b2005-07-30 00:12:19 +0000170 if (S->getNumOperands() == 2) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000171 Value *F = expand(S->getOperand(1));
Chris Lattnerdf14a042005-10-30 06:24:33 +0000172
173 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000174 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000175 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000176 return I;
177
178 // If the insert point is directly inside of the loop, emit the multiply at
179 // the insert point. Otherwise, L is a loop that is a parent of the insert
180 // point loop. If we can, move the multiply to the outer most loop that it
181 // is safe to be in.
182 Instruction *MulInsertPt = InsertPt;
183 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
184 if (InsertPtLoop != L && InsertPtLoop &&
185 L->contains(InsertPtLoop->getHeader())) {
186 while (InsertPtLoop != L) {
187 // If we cannot hoist the multiply out of this loop, don't.
188 if (!InsertPtLoop->isLoopInvariant(F)) break;
189
190 // Otherwise, move the insert point to the preheader of the loop.
191 MulInsertPt = InsertPtLoop->getLoopPreheader()->getTerminator();
192 InsertPtLoop = InsertPtLoop->getParentLoop();
193 }
194 }
195
Chris Lattner7fec90e2007-04-13 05:04:18 +0000196 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000197 }
198
199 // If this is a chain of recurrences, turn it into a closed form, using the
200 // folders, then expandCodeFor the closed form. This allows the folders to
201 // simplify the expression without having to build a bunch of special code
202 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000203 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000204
Dan Gohman246b2562007-10-22 18:31:58 +0000205 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000206 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000207
Dan Gohmand19534a2007-06-15 14:38:12 +0000208 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000209}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000210
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000211Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
212 Value *LHS = expand(S->getOperand(0));
213 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
214 Value *RHS = expand(S->getOperand(i));
215 Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
216 LHS = new SelectInst(ICmp, LHS, RHS, "smax", InsertPt);
217 }
218 return LHS;
219}
220
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000221Value *SCEVExpander::expand(SCEV *S) {
222 // Check to see if we already expanded this.
223 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
224 if (I != InsertedExpressions.end())
225 return I->second;
226
227 Value *V = visit(S);
228 InsertedExpressions[S] = V;
229 return V;
230}
231