blob: d91061b2b3a7cec2de5f48abec35a3a37609d732 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
16#include "llvm/Analysis/ScalarEvolutionExpander.h"
17#include "llvm/Analysis/LoopInfo.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000018#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019using namespace llvm;
20
21/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22/// we can to share the casts.
23Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
24 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +000025 // Short-circuit unnecessary bitcasts.
26 if (opcode == Instruction::BitCast && V->getType() == Ty)
27 return V;
28
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029 // FIXME: keep track of the cast instruction.
30 if (Constant *C = dyn_cast<Constant>(V))
31 return ConstantExpr::getCast(opcode, C, Ty);
32
33 if (Argument *A = dyn_cast<Argument>(V)) {
34 // Check to see if there is already a cast!
35 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
36 UI != E; ++UI) {
37 if ((*UI)->getType() == Ty)
Wojciech Matyjewiczf0f23632008-02-09 18:30:13 +000038 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
39 if (CI->getOpcode() == opcode) {
40 // If the cast isn't the first instruction of the function, move it.
41 if (BasicBlock::iterator(CI) !=
42 A->getParent()->getEntryBlock().begin()) {
43 CI->moveBefore(A->getParent()->getEntryBlock().begin());
44 }
45 return CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047 }
Gabor Greifa645dd32008-05-16 19:29:10 +000048 return CastInst::Create(opcode, V, Ty, V->getName(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049 A->getParent()->getEntryBlock().begin());
50 }
Wojciech Matyjewiczf0f23632008-02-09 18:30:13 +000051
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewiczf0f23632008-02-09 18:30:13 +000053
Dan Gohmanf17a25c2007-07-18 16:29:46 +000054 // Check to see if there is already a cast. If there is, use it.
55 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
56 UI != E; ++UI) {
57 if ((*UI)->getType() == Ty)
Wojciech Matyjewiczf0f23632008-02-09 18:30:13 +000058 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
59 if (CI->getOpcode() == opcode) {
60 BasicBlock::iterator It = I; ++It;
61 if (isa<InvokeInst>(I))
62 It = cast<InvokeInst>(I)->getNormalDest()->begin();
63 while (isa<PHINode>(It)) ++It;
64 if (It != BasicBlock::iterator(CI)) {
65 // Splice the cast immediately after the operand in question.
66 CI->moveBefore(It);
67 }
68 return CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 }
71 BasicBlock::iterator IP = I; ++IP;
72 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
73 IP = II->getNormalDest()->begin();
74 while (isa<PHINode>(IP)) ++IP;
Gabor Greifa645dd32008-05-16 19:29:10 +000075 return CastInst::Create(opcode, V, Ty, V->getName(), IP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000076}
77
78/// InsertBinop - Insert the specified binary operator, doing a small amount
79/// of work to avoid inserting an obviously redundant operation.
80Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Wojciech Matyjewicz386e26b2008-06-15 19:07:39 +000081 Value *RHS, Instruction *InsertPt) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 // Fold a binop with constant operands.
83 if (Constant *CLHS = dyn_cast<Constant>(LHS))
84 if (Constant *CRHS = dyn_cast<Constant>(RHS))
85 return ConstantExpr::get(Opcode, CLHS, CRHS);
86
87 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
88 unsigned ScanLimit = 6;
Wojciech Matyjewicz386e26b2008-06-15 19:07:39 +000089 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
90 if (InsertPt != BlockBegin) {
91 // Scanning starts from the last instruction before InsertPt.
92 BasicBlock::iterator IP = InsertPt;
93 --IP;
94 for (; ScanLimit; --IP, --ScanLimit) {
95 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
96 if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
97 BinOp->getOperand(1) == RHS)
98 return BinOp;
99 if (IP == BlockBegin) break;
100 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 }
Wojciech Matyjewicz386e26b2008-06-15 19:07:39 +0000102
103 // If we haven't found this binop, insert it.
Gabor Greifa645dd32008-05-16 19:29:10 +0000104 return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105}
106
Dan Gohman66d34122008-06-18 16:37:11 +0000107Value *SCEVExpander::visitAddExpr(SCEVAddExpr *S) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000108 const Type *Ty = S->getType();
109 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
Dan Gohman66d34122008-06-18 16:37:11 +0000110 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000111 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
Dan Gohman66d34122008-06-18 16:37:11 +0000112
113 // Emit a bunch of add instructions
Dan Gohman01c2ee72009-04-16 03:18:22 +0000114 for (int i = S->getNumOperands()-2; i >= 0; --i) {
115 Value *W = expand(S->getOperand(i));
116 W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
117 V = InsertBinop(Instruction::Add, V, W, InsertPt);
118 }
Dan Gohman66d34122008-06-18 16:37:11 +0000119 return V;
120}
121
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000123 const Type *Ty = S->getType();
124 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 int FirstOp = 0; // Set if we should emit a subtract.
126 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
127 if (SC->getValue()->isAllOnesValue())
128 FirstOp = 1;
129
130 int i = S->getNumOperands()-2;
131 Value *V = expand(S->getOperand(i+1));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000132 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134 // Emit a bunch of multiply instructions
Dan Gohman01c2ee72009-04-16 03:18:22 +0000135 for (; i >= FirstOp; --i) {
136 Value *W = expand(S->getOperand(i));
137 W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
138 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
139 }
140
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 // -1 * ... ---> 0 - ...
142 if (FirstOp == 1)
Dan Gohman01c2ee72009-04-16 03:18:22 +0000143 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 return V;
145}
146
Nick Lewycky0008c192008-07-08 05:05:37 +0000147Value *SCEVExpander::visitUDivExpr(SCEVUDivExpr *S) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000148 const Type *Ty = S->getType();
149 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
150
Nick Lewycky0008c192008-07-08 05:05:37 +0000151 Value *LHS = expand(S->getLHS());
Dan Gohman01c2ee72009-04-16 03:18:22 +0000152 LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
Nick Lewycky0008c192008-07-08 05:05:37 +0000153 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
154 const APInt &RHS = SC->getValue()->getValue();
155 if (RHS.isPowerOf2())
156 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000157 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky0008c192008-07-08 05:05:37 +0000158 InsertPt);
159 }
160
161 Value *RHS = expand(S->getRHS());
Dan Gohman01c2ee72009-04-16 03:18:22 +0000162 RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false), RHS, Ty);
Nick Lewycky0008c192008-07-08 05:05:37 +0000163 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
164}
165
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
167 const Type *Ty = S->getType();
168 const Loop *L = S->getLoop();
169 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
Dan Gohman01c2ee72009-04-16 03:18:22 +0000170 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
171 "Cannot expand fp recurrences yet!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000172
173 // {X,+,F} --> X + {0,+,F}
Dan Gohman7b560c42008-06-18 16:23:07 +0000174 if (!S->getStart()->isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 Value *Start = expand(S->getStart());
Dan Gohman01c2ee72009-04-16 03:18:22 +0000176 if (isa<PointerType>(Start->getType()))
177 Start = InsertCastOfTo(Instruction::PtrToInt, Start, TD.getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000179 NewOps[0] = SE.getIntegerSCEV(0, Ty);
180 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000181 if (isa<PointerType>(Rest->getType()))
182 Rest = InsertCastOfTo(Instruction::PtrToInt, Rest, TD.getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183
184 // FIXME: look for an existing add to use.
185 return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
186 }
187
188 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohmanfa6b3dc2008-06-22 19:23:09 +0000189 if (S->isAffine() &&
Dan Gohman89f85052007-10-22 18:31:58 +0000190 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 // Create and insert the PHI node for the induction variable in the
192 // specified loop.
193 BasicBlock *Header = L->getHeader();
Gabor Greifd6da1d02008-04-06 20:25:17 +0000194 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
196
197 pred_iterator HPI = pred_begin(Header);
198 assert(HPI != pred_end(Header) && "Loop with zero preds???");
199 if (!L->contains(*HPI)) ++HPI;
200 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
201 "No backedge in loop?");
202
203 // Insert a unit add instruction right before the terminator corresponding
204 // to the back-edge.
205 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greifa645dd32008-05-16 19:29:10 +0000206 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 (*HPI)->getTerminator());
208
209 pred_iterator PI = pred_begin(Header);
210 if (*PI == L->getLoopPreheader())
211 ++PI;
212 PN->addIncoming(Add, *PI);
213 return PN;
214 }
215
216 // Get the canonical induction variable I for this loop.
217 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
218
219 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohmanfa6b3dc2008-06-22 19:23:09 +0000220 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 Value *F = expand(S->getOperand(1));
222
223 // IF the step is by one, just return the inserted IV.
224 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
225 if (CI->getValue() == 1)
226 return I;
227
228 // If the insert point is directly inside of the loop, emit the multiply at
229 // the insert point. Otherwise, L is a loop that is a parent of the insert
230 // point loop. If we can, move the multiply to the outer most loop that it
231 // is safe to be in.
232 Instruction *MulInsertPt = InsertPt;
233 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
234 if (InsertPtLoop != L && InsertPtLoop &&
235 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewiczd6bb45c2008-06-14 16:48:22 +0000236 do {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 // If we cannot hoist the multiply out of this loop, don't.
238 if (!InsertPtLoop->isLoopInvariant(F)) break;
239
Wojciech Matyjewiczd6bb45c2008-06-14 16:48:22 +0000240 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
241
242 // If this loop hasn't got a preheader, we aren't able to hoist the
243 // multiply.
244 if (!InsertPtLoopPH)
245 break;
246
247 // Otherwise, move the insert point to the preheader.
248 MulInsertPt = InsertPtLoopPH->getTerminator();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewiczd6bb45c2008-06-14 16:48:22 +0000250 } while (InsertPtLoop != L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 }
252
253 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
254 }
255
256 // If this is a chain of recurrences, turn it into a closed form, using the
257 // folders, then expandCodeFor the closed form. This allows the folders to
258 // simplify the expression without having to build a bunch of special code
259 // into this folder.
Dan Gohman89f85052007-10-22 18:31:58 +0000260 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261
Dan Gohman89f85052007-10-22 18:31:58 +0000262 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
264
265 return expand(V);
266}
Anton Korobeynikova684b672007-08-20 21:17:26 +0000267
Dan Gohman86479482008-06-22 19:09:18 +0000268Value *SCEVExpander::visitTruncateExpr(SCEVTruncateExpr *S) {
269 Value *V = expand(S->getOperand());
Dan Gohman01c2ee72009-04-16 03:18:22 +0000270 if (isa<PointerType>(V->getType()))
271 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
Gabor Greif1dd05e12008-10-13 10:21:17 +0000272 return CastInst::CreateTruncOrBitCast(V, S->getType(), "tmp.", InsertPt);
Dan Gohman86479482008-06-22 19:09:18 +0000273}
274
275Value *SCEVExpander::visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
276 Value *V = expand(S->getOperand());
Dan Gohman01c2ee72009-04-16 03:18:22 +0000277 if (isa<PointerType>(V->getType()))
278 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
Gabor Greif1dd05e12008-10-13 10:21:17 +0000279 return CastInst::CreateZExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
Dan Gohman86479482008-06-22 19:09:18 +0000280}
281
282Value *SCEVExpander::visitSignExtendExpr(SCEVSignExtendExpr *S) {
283 Value *V = expand(S->getOperand());
Dan Gohman01c2ee72009-04-16 03:18:22 +0000284 if (isa<PointerType>(V->getType()))
285 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
Gabor Greif1dd05e12008-10-13 10:21:17 +0000286 return CastInst::CreateSExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
Dan Gohman86479482008-06-22 19:09:18 +0000287}
288
Nick Lewycky711640a2007-11-25 22:41:31 +0000289Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
290 Value *LHS = expand(S->getOperand(0));
291 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
292 Value *RHS = expand(S->getOperand(i));
293 Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000294 LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
Nick Lewycky711640a2007-11-25 22:41:31 +0000295 }
296 return LHS;
297}
298
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000299Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
300 Value *LHS = expand(S->getOperand(0));
301 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
302 Value *RHS = expand(S->getOperand(i));
303 Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000304 LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000305 }
306 return LHS;
307}
308
Dan Gohman01c2ee72009-04-16 03:18:22 +0000309Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty,
310 Instruction *IP) {
Dan Gohman86479482008-06-22 19:09:18 +0000311 // Expand the code for this SCEV.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000312 assert(TD.getTypeSizeInBits(Ty) == TD.getTypeSizeInBits(SH->getType()) &&
313 "non-trivial casts should be done with the SCEVs directly!");
Dan Gohman86479482008-06-22 19:09:18 +0000314 this->InsertPt = IP;
Dan Gohman01c2ee72009-04-16 03:18:22 +0000315 Value *V = expand(SH);
316 return InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
Dan Gohman86479482008-06-22 19:09:18 +0000317}
318
Anton Korobeynikova684b672007-08-20 21:17:26 +0000319Value *SCEVExpander::expand(SCEV *S) {
320 // Check to see if we already expanded this.
321 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
322 if (I != InsertedExpressions.end())
323 return I->second;
324
325 Value *V = visit(S);
326 InsertedExpressions[S] = V;
327 return V;
328}