blob: 0033fb4ae4ae615a8868d96007341ced83a6c30e [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"
Dan Gohman2d1be872009-04-16 03:18:22 +000018#include "llvm/Target/TargetData.h"
Nate Begeman36f891b2005-07-30 00:12:19 +000019using namespace llvm;
20
Chris Lattnerca1a4be2006-02-04 09:51:53 +000021/// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22/// we can to share the casts.
Reid Spencer3ba68b92006-12-13 08:06:42 +000023Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
24 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +000025 // Short-circuit unnecessary bitcasts.
26 if (opcode == Instruction::BitCast && V->getType() == Ty)
27 return V;
28
Dan Gohmanf04fa482009-04-16 15:52:57 +000029 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
30 if (opcode == Instruction::PtrToInt && Ty == TD.getIntPtrType())
31 if (IntToPtrInst *ITP = dyn_cast<IntToPtrInst>(V))
32 return ITP->getOperand(0);
33 if (opcode == Instruction::IntToPtr && V->getType() == TD.getIntPtrType())
34 if (PtrToIntInst *PTI = dyn_cast<PtrToIntInst>(V))
35 return PTI->getOperand(0);
36
Chris Lattnerca1a4be2006-02-04 09:51:53 +000037 // FIXME: keep track of the cast instruction.
38 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerd977d862006-12-12 23:36:14 +000039 return ConstantExpr::getCast(opcode, C, Ty);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000040
41 if (Argument *A = dyn_cast<Argument>(V)) {
42 // Check to see if there is already a cast!
43 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
44 UI != E; ++UI) {
45 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000046 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
47 if (CI->getOpcode() == opcode) {
48 // If the cast isn't the first instruction of the function, move it.
49 if (BasicBlock::iterator(CI) !=
50 A->getParent()->getEntryBlock().begin()) {
51 CI->moveBefore(A->getParent()->getEntryBlock().begin());
52 }
53 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000054 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000055 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +000056 return CastInst::Create(opcode, V, Ty, V->getName(),
Reid Spencerd977d862006-12-12 23:36:14 +000057 A->getParent()->getEntryBlock().begin());
Chris Lattnerca1a4be2006-02-04 09:51:53 +000058 }
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000059
Chris Lattnerca1a4be2006-02-04 09:51:53 +000060 Instruction *I = cast<Instruction>(V);
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000061
Chris Lattnerca1a4be2006-02-04 09:51:53 +000062 // Check to see if there is already a cast. If there is, use it.
63 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
64 UI != E; ++UI) {
65 if ((*UI)->getType() == Ty)
Wojciech Matyjewicz39131872008-02-09 18:30:13 +000066 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
67 if (CI->getOpcode() == opcode) {
68 BasicBlock::iterator It = I; ++It;
69 if (isa<InvokeInst>(I))
70 It = cast<InvokeInst>(I)->getNormalDest()->begin();
71 while (isa<PHINode>(It)) ++It;
72 if (It != BasicBlock::iterator(CI)) {
73 // Splice the cast immediately after the operand in question.
74 CI->moveBefore(It);
75 }
76 return CI;
Chris Lattnerca1a4be2006-02-04 09:51:53 +000077 }
Chris Lattnerca1a4be2006-02-04 09:51:53 +000078 }
79 BasicBlock::iterator IP = I; ++IP;
80 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
81 IP = II->getNormalDest()->begin();
82 while (isa<PHINode>(IP)) ++IP;
Gabor Greif7cbd8a32008-05-16 19:29:10 +000083 return CastInst::Create(opcode, V, Ty, V->getName(), IP);
Chris Lattnerca1a4be2006-02-04 09:51:53 +000084}
85
Chris Lattner7fec90e2007-04-13 05:04:18 +000086/// InsertBinop - Insert the specified binary operator, doing a small amount
87/// of work to avoid inserting an obviously redundant operation.
88Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +000089 Value *RHS, Instruction *InsertPt) {
Dan Gohman0f0eb182007-06-15 19:21:55 +000090 // Fold a binop with constant operands.
91 if (Constant *CLHS = dyn_cast<Constant>(LHS))
92 if (Constant *CRHS = dyn_cast<Constant>(RHS))
93 return ConstantExpr::get(Opcode, CLHS, CRHS);
94
Chris Lattner7fec90e2007-04-13 05:04:18 +000095 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
96 unsigned ScanLimit = 6;
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +000097 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
98 if (InsertPt != BlockBegin) {
99 // Scanning starts from the last instruction before InsertPt.
100 BasicBlock::iterator IP = InsertPt;
101 --IP;
102 for (; ScanLimit; --IP, --ScanLimit) {
103 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(IP))
104 if (BinOp->getOpcode() == Opcode && BinOp->getOperand(0) == LHS &&
105 BinOp->getOperand(1) == RHS)
106 return BinOp;
107 if (IP == BlockBegin) break;
108 }
Chris Lattner7fec90e2007-04-13 05:04:18 +0000109 }
Wojciech Matyjewicz8a087692008-06-15 19:07:39 +0000110
111 // If we haven't found this binop, insert it.
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000112 return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
Chris Lattner7fec90e2007-04-13 05:04:18 +0000113}
114
Dan Gohmane24fa642008-06-18 16:37:11 +0000115Value *SCEVExpander::visitAddExpr(SCEVAddExpr *S) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000116 const Type *Ty = S->getType();
117 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
Dan Gohmane24fa642008-06-18 16:37:11 +0000118 Value *V = expand(S->getOperand(S->getNumOperands()-1));
Dan Gohman2d1be872009-04-16 03:18:22 +0000119 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
Dan Gohmane24fa642008-06-18 16:37:11 +0000120
121 // Emit a bunch of add instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000122 for (int i = S->getNumOperands()-2; i >= 0; --i) {
123 Value *W = expand(S->getOperand(i));
124 W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
125 V = InsertBinop(Instruction::Add, V, W, InsertPt);
126 }
Dan Gohmane24fa642008-06-18 16:37:11 +0000127 return V;
128}
129
Nate Begeman36f891b2005-07-30 00:12:19 +0000130Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000131 const Type *Ty = S->getType();
132 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
Nate Begeman36f891b2005-07-30 00:12:19 +0000133 int FirstOp = 0; // Set if we should emit a subtract.
134 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
135 if (SC->getValue()->isAllOnesValue())
136 FirstOp = 1;
137
138 int i = S->getNumOperands()-2;
Dan Gohmand19534a2007-06-15 14:38:12 +0000139 Value *V = expand(S->getOperand(i+1));
Dan Gohman2d1be872009-04-16 03:18:22 +0000140 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
Nate Begeman36f891b2005-07-30 00:12:19 +0000141
142 // Emit a bunch of multiply instructions
Dan Gohman2d1be872009-04-16 03:18:22 +0000143 for (; i >= FirstOp; --i) {
144 Value *W = expand(S->getOperand(i));
145 W = InsertCastOfTo(CastInst::getCastOpcode(W, false, Ty, false), W, Ty);
146 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
147 }
148
Nate Begeman36f891b2005-07-30 00:12:19 +0000149 // -1 * ... ---> 0 - ...
150 if (FirstOp == 1)
Dan Gohman2d1be872009-04-16 03:18:22 +0000151 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000152 return V;
153}
154
Nick Lewycky6177fd42008-07-08 05:05:37 +0000155Value *SCEVExpander::visitUDivExpr(SCEVUDivExpr *S) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000156 const Type *Ty = S->getType();
157 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
158
Nick Lewycky6177fd42008-07-08 05:05:37 +0000159 Value *LHS = expand(S->getLHS());
Dan Gohman2d1be872009-04-16 03:18:22 +0000160 LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000161 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
162 const APInt &RHS = SC->getValue()->getValue();
163 if (RHS.isPowerOf2())
164 return InsertBinop(Instruction::LShr, LHS,
Dan Gohman2d1be872009-04-16 03:18:22 +0000165 ConstantInt::get(Ty, RHS.logBase2()),
Nick Lewycky6177fd42008-07-08 05:05:37 +0000166 InsertPt);
167 }
168
169 Value *RHS = expand(S->getRHS());
Dan Gohman2d1be872009-04-16 03:18:22 +0000170 RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false), RHS, Ty);
Nick Lewycky6177fd42008-07-08 05:05:37 +0000171 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
172}
173
Nate Begeman36f891b2005-07-30 00:12:19 +0000174Value *SCEVExpander::visitAddRecExpr(SCEVAddRecExpr *S) {
175 const Type *Ty = S->getType();
176 const Loop *L = S->getLoop();
177 // We cannot yet do fp recurrences, e.g. the xform of {X,+,F} --> X+{0,+,F}
Dan Gohman2d1be872009-04-16 03:18:22 +0000178 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
179 "Cannot expand fp recurrences yet!");
Nate Begeman36f891b2005-07-30 00:12:19 +0000180
181 // {X,+,F} --> X + {0,+,F}
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000182 if (!S->getStart()->isZero()) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000183 Value *Start = expand(S->getStart());
Dan Gohman2d1be872009-04-16 03:18:22 +0000184 if (isa<PointerType>(Start->getType()))
185 Start = InsertCastOfTo(Instruction::PtrToInt, Start, TD.getIntPtrType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000186 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000187 NewOps[0] = SE.getIntegerSCEV(0, Ty);
188 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
Dan Gohman2d1be872009-04-16 03:18:22 +0000189 if (isa<PointerType>(Rest->getType()))
190 Rest = InsertCastOfTo(Instruction::PtrToInt, Rest, TD.getIntPtrType());
Nate Begeman36f891b2005-07-30 00:12:19 +0000191
192 // FIXME: look for an existing add to use.
Chris Lattner7fec90e2007-04-13 05:04:18 +0000193 return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000194 }
195
196 // {0,+,1} --> Insert a canonical induction variable into the loop!
Dan Gohman17f19722008-06-22 19:23:09 +0000197 if (S->isAffine() &&
Dan Gohman246b2562007-10-22 18:31:58 +0000198 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
Nate Begeman36f891b2005-07-30 00:12:19 +0000199 // Create and insert the PHI node for the induction variable in the
200 // specified loop.
201 BasicBlock *Header = L->getHeader();
Gabor Greif051a9502008-04-06 20:25:17 +0000202 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
Nate Begeman36f891b2005-07-30 00:12:19 +0000203 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
204
205 pred_iterator HPI = pred_begin(Header);
206 assert(HPI != pred_end(Header) && "Loop with zero preds???");
207 if (!L->contains(*HPI)) ++HPI;
208 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
209 "No backedge in loop?");
210
211 // Insert a unit add instruction right before the terminator corresponding
212 // to the back-edge.
Reid Spencer24d6da52007-01-21 00:29:26 +0000213 Constant *One = ConstantInt::get(Ty, 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000214 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
Nate Begeman36f891b2005-07-30 00:12:19 +0000215 (*HPI)->getTerminator());
216
217 pred_iterator PI = pred_begin(Header);
218 if (*PI == L->getLoopPreheader())
219 ++PI;
220 PN->addIncoming(Add, *PI);
221 return PN;
222 }
223
224 // Get the canonical induction variable I for this loop.
225 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
226
Chris Lattnerdf14a042005-10-30 06:24:33 +0000227 // If this is a simple linear addrec, emit it now as a special case.
Dan Gohman17f19722008-06-22 19:23:09 +0000228 if (S->isAffine()) { // {0,+,F} --> i*F
Dan Gohmand19534a2007-06-15 14:38:12 +0000229 Value *F = expand(S->getOperand(1));
Chris Lattnerdf14a042005-10-30 06:24:33 +0000230
231 // IF the step is by one, just return the inserted IV.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000232 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
Reid Spencer4d050d72007-03-01 19:45:00 +0000233 if (CI->getValue() == 1)
Chris Lattnerdf14a042005-10-30 06:24:33 +0000234 return I;
235
236 // If the insert point is directly inside of the loop, emit the multiply at
237 // the insert point. Otherwise, L is a loop that is a parent of the insert
238 // point loop. If we can, move the multiply to the outer most loop that it
239 // is safe to be in.
240 Instruction *MulInsertPt = InsertPt;
241 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
242 if (InsertPtLoop != L && InsertPtLoop &&
243 L->contains(InsertPtLoop->getHeader())) {
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000244 do {
Chris Lattnerdf14a042005-10-30 06:24:33 +0000245 // If we cannot hoist the multiply out of this loop, don't.
246 if (!InsertPtLoop->isLoopInvariant(F)) break;
247
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000248 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
249
250 // If this loop hasn't got a preheader, we aren't able to hoist the
251 // multiply.
252 if (!InsertPtLoopPH)
253 break;
254
255 // Otherwise, move the insert point to the preheader.
256 MulInsertPt = InsertPtLoopPH->getTerminator();
Chris Lattnerdf14a042005-10-30 06:24:33 +0000257 InsertPtLoop = InsertPtLoop->getParentLoop();
Wojciech Matyjewicz5d2bc852008-06-14 16:48:22 +0000258 } while (InsertPtLoop != L);
Chris Lattnerdf14a042005-10-30 06:24:33 +0000259 }
260
Chris Lattner7fec90e2007-04-13 05:04:18 +0000261 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
Nate Begeman36f891b2005-07-30 00:12:19 +0000262 }
263
264 // If this is a chain of recurrences, turn it into a closed form, using the
265 // folders, then expandCodeFor the closed form. This allows the folders to
266 // simplify the expression without having to build a bunch of special code
267 // into this folder.
Dan Gohman246b2562007-10-22 18:31:58 +0000268 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
Nate Begeman36f891b2005-07-30 00:12:19 +0000269
Dan Gohman246b2562007-10-22 18:31:58 +0000270 SCEVHandle V = S->evaluateAtIteration(IH, SE);
Bill Wendlinge8156192006-12-07 01:30:32 +0000271 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
Nate Begeman36f891b2005-07-30 00:12:19 +0000272
Dan Gohmand19534a2007-06-15 14:38:12 +0000273 return expand(V);
Nate Begeman36f891b2005-07-30 00:12:19 +0000274}
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000275
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000276Value *SCEVExpander::visitTruncateExpr(SCEVTruncateExpr *S) {
277 Value *V = expand(S->getOperand());
Dan Gohman2d1be872009-04-16 03:18:22 +0000278 if (isa<PointerType>(V->getType()))
279 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
Gabor Greife9324f32008-10-13 10:21:17 +0000280 return CastInst::CreateTruncOrBitCast(V, S->getType(), "tmp.", InsertPt);
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000281}
282
283Value *SCEVExpander::visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
284 Value *V = expand(S->getOperand());
Dan Gohman2d1be872009-04-16 03:18:22 +0000285 if (isa<PointerType>(V->getType()))
286 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
Gabor Greife9324f32008-10-13 10:21:17 +0000287 return CastInst::CreateZExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000288}
289
290Value *SCEVExpander::visitSignExtendExpr(SCEVSignExtendExpr *S) {
291 Value *V = expand(S->getOperand());
Dan Gohman2d1be872009-04-16 03:18:22 +0000292 if (isa<PointerType>(V->getType()))
293 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
Gabor Greife9324f32008-10-13 10:21:17 +0000294 return CastInst::CreateSExtOrBitCast(V, S->getType(), "tmp.", InsertPt);
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000295}
296
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000297Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
298 Value *LHS = expand(S->getOperand(0));
299 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
300 Value *RHS = expand(S->getOperand(i));
301 Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
Gabor Greif051a9502008-04-06 20:25:17 +0000302 LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000303 }
304 return LHS;
305}
306
Nick Lewycky3e630762008-02-20 06:48:22 +0000307Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
308 Value *LHS = expand(S->getOperand(0));
309 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
310 Value *RHS = expand(S->getOperand(i));
311 Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
Gabor Greif051a9502008-04-06 20:25:17 +0000312 LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
Nick Lewycky3e630762008-02-20 06:48:22 +0000313 }
314 return LHS;
315}
316
Dan Gohman2d1be872009-04-16 03:18:22 +0000317Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty,
318 Instruction *IP) {
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000319 // Expand the code for this SCEV.
Dan Gohman2d1be872009-04-16 03:18:22 +0000320 assert(TD.getTypeSizeInBits(Ty) == TD.getTypeSizeInBits(SH->getType()) &&
321 "non-trivial casts should be done with the SCEVs directly!");
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000322 this->InsertPt = IP;
Dan Gohman2d1be872009-04-16 03:18:22 +0000323 Value *V = expand(SH);
324 return InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
Dan Gohman11f6d3b2008-06-22 19:09:18 +0000325}
326
Anton Korobeynikov96fea332007-08-20 21:17:26 +0000327Value *SCEVExpander::expand(SCEV *S) {
328 // Check to see if we already expanded this.
329 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
330 if (I != InsertedExpressions.end())
331 return I->second;
332
333 Value *V = visit(S);
334 InsertedExpressions[S] = V;
335 return V;
336}