1 //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Analysis/ScalarEvolutionExpander.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/Target/TargetData.h"
21 /// InsertCastOfTo - Insert a cast of V to the specified type, doing what
22 /// we can to share the casts.
23 Value *SCEVExpander::InsertCastOfTo(Instruction::CastOps opcode, Value *V,
25 // Short-circuit unnecessary bitcasts.
26 if (opcode == Instruction::BitCast && V->getType() == Ty)
29 // 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);
37 // FIXME: keep track of the cast instruction.
38 if (Constant *C = dyn_cast<Constant>(V))
39 return ConstantExpr::getCast(opcode, C, Ty);
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();
45 if ((*UI)->getType() == Ty)
46 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());
56 return CastInst::Create(opcode, V, Ty, V->getName(),
57 A->getParent()->getEntryBlock().begin());
60 Instruction *I = cast<Instruction>(V);
62 // 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();
65 if ((*UI)->getType() == Ty)
66 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.
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;
83 return CastInst::Create(opcode, V, Ty, V->getName(), IP);
86 /// InsertBinop - Insert the specified binary operator, doing a small amount
87 /// of work to avoid inserting an obviously redundant operation.
88 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
89 Value *RHS, Instruction *InsertPt) {
90 // 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);
95 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
96 unsigned ScanLimit = 6;
97 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
98 if (InsertPt != BlockBegin) {
99 // Scanning starts from the last instruction before InsertPt.
100 BasicBlock::iterator IP = InsertPt;
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)
107 if (IP == BlockBegin) break;
111 // If we haven't found this binop, insert it.
112 return BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
115 Value *SCEVExpander::visitAddExpr(SCEVAddExpr *S) {
116 const Type *Ty = S->getType();
117 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
118 Value *V = expand(S->getOperand(S->getNumOperands()-1));
119 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
121 // Emit a bunch of add instructions
122 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);
130 Value *SCEVExpander::visitMulExpr(SCEVMulExpr *S) {
131 const Type *Ty = S->getType();
132 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
133 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())
138 int i = S->getNumOperands()-2;
139 Value *V = expand(S->getOperand(i+1));
140 V = InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
142 // Emit a bunch of multiply instructions
143 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);
149 // -1 * ... ---> 0 - ...
151 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
155 Value *SCEVExpander::visitUDivExpr(SCEVUDivExpr *S) {
156 const Type *Ty = S->getType();
157 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
159 Value *LHS = expand(S->getLHS());
160 LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
161 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,
165 ConstantInt::get(Ty, RHS.logBase2()),
169 Value *RHS = expand(S->getRHS());
170 RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false), RHS, Ty);
171 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
174 Value *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}
178 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
179 "Cannot expand fp recurrences yet!");
181 // {X,+,F} --> X + {0,+,F}
182 if (!S->getStart()->isZero()) {
183 Value *Start = expand(S->getStart());
184 if (isa<PointerType>(Start->getType()))
185 Start = InsertCastOfTo(Instruction::PtrToInt, Start, TD.getIntPtrType());
186 std::vector<SCEVHandle> NewOps(S->op_begin(), S->op_end());
187 NewOps[0] = SE.getIntegerSCEV(0, Ty);
188 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
189 if (isa<PointerType>(Rest->getType()))
190 Rest = InsertCastOfTo(Instruction::PtrToInt, Rest, TD.getIntPtrType());
192 // FIXME: look for an existing add to use.
193 return InsertBinop(Instruction::Add, Rest, Start, InsertPt);
196 // {0,+,1} --> Insert a canonical induction variable into the loop!
198 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
199 // Create and insert the PHI node for the induction variable in the
201 BasicBlock *Header = L->getHeader();
202 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
203 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
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?");
211 // Insert a unit add instruction right before the terminator corresponding
213 Constant *One = ConstantInt::get(Ty, 1);
214 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
215 (*HPI)->getTerminator());
217 pred_iterator PI = pred_begin(Header);
218 if (*PI == L->getLoopPreheader())
220 PN->addIncoming(Add, *PI);
224 // Get the canonical induction variable I for this loop.
225 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
227 // If this is a simple linear addrec, emit it now as a special case.
228 if (S->isAffine()) { // {0,+,F} --> i*F
229 Value *F = expand(S->getOperand(1));
230 if (isa<PointerType>(F->getType()))
231 F = InsertCastOfTo(Instruction::PtrToInt, F, TD.getIntPtrType());
233 // IF the step is by one, just return the inserted IV.
234 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
235 if (CI->getValue() == 1)
238 // If the insert point is directly inside of the loop, emit the multiply at
239 // the insert point. Otherwise, L is a loop that is a parent of the insert
240 // point loop. If we can, move the multiply to the outer most loop that it
242 Instruction *MulInsertPt = InsertPt;
243 Loop *InsertPtLoop = LI.getLoopFor(MulInsertPt->getParent());
244 if (InsertPtLoop != L && InsertPtLoop &&
245 L->contains(InsertPtLoop->getHeader())) {
247 // If we cannot hoist the multiply out of this loop, don't.
248 if (!InsertPtLoop->isLoopInvariant(F)) break;
250 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
252 // If this loop hasn't got a preheader, we aren't able to hoist the
257 // Otherwise, move the insert point to the preheader.
258 MulInsertPt = InsertPtLoopPH->getTerminator();
259 InsertPtLoop = InsertPtLoop->getParentLoop();
260 } while (InsertPtLoop != L);
263 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
266 // If this is a chain of recurrences, turn it into a closed form, using the
267 // folders, then expandCodeFor the closed form. This allows the folders to
268 // simplify the expression without having to build a bunch of special code
270 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
272 SCEVHandle V = S->evaluateAtIteration(IH, SE);
273 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
278 Value *SCEVExpander::visitTruncateExpr(SCEVTruncateExpr *S) {
279 Value *V = expand(S->getOperand());
280 if (isa<PointerType>(V->getType()))
281 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
282 return CastInst::CreateTruncOrBitCast(V, S->getType(), "tmp.", InsertPt);
285 Value *SCEVExpander::visitZeroExtendExpr(SCEVZeroExtendExpr *S) {
286 const Type *Ty = S->getType();
287 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
288 Value *V = expand(S->getOperand());
289 if (isa<PointerType>(V->getType()))
290 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
291 return CastInst::CreateZExtOrBitCast(V, Ty, "tmp.", InsertPt);
294 Value *SCEVExpander::visitSignExtendExpr(SCEVSignExtendExpr *S) {
295 const Type *Ty = S->getType();
296 if (isa<PointerType>(Ty)) Ty = TD.getIntPtrType();
297 Value *V = expand(S->getOperand());
298 if (isa<PointerType>(V->getType()))
299 V = InsertCastOfTo(Instruction::PtrToInt, V, TD.getIntPtrType());
300 return CastInst::CreateSExtOrBitCast(V, Ty, "tmp.", InsertPt);
303 Value *SCEVExpander::visitSMaxExpr(SCEVSMaxExpr *S) {
304 const Type *Ty = S->getType();
305 Value *LHS = expand(S->getOperand(0));
306 LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
307 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
308 Value *RHS = expand(S->getOperand(i));
309 RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false),
311 Value *ICmp = new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
312 LHS = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
317 Value *SCEVExpander::visitUMaxExpr(SCEVUMaxExpr *S) {
318 const Type *Ty = S->getType();
319 Value *LHS = expand(S->getOperand(0));
320 LHS = InsertCastOfTo(CastInst::getCastOpcode(LHS, false, Ty, false), LHS, Ty);
321 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
322 Value *RHS = expand(S->getOperand(i));
323 RHS = InsertCastOfTo(CastInst::getCastOpcode(RHS, false, Ty, false),
325 Value *ICmp = new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
326 LHS = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
331 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty,
333 // Expand the code for this SCEV.
334 assert(TD.getTypeSizeInBits(Ty) == TD.getTypeSizeInBits(SH->getType()) &&
335 "non-trivial casts should be done with the SCEVs directly!");
337 Value *V = expand(SH);
338 return InsertCastOfTo(CastInst::getCastOpcode(V, false, Ty, false), V, Ty);
341 Value *SCEVExpander::expand(SCEV *S) {
342 // Check to see if we already expanded this.
343 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
344 if (I != InsertedExpressions.end())
348 InsertedExpressions[S] = V;