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 || opcode == Instruction::IntToPtr) &&
31 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
32 if (CastInst *CI = dyn_cast<CastInst>(V))
33 if ((CI->getOpcode() == Instruction::PtrToInt ||
34 CI->getOpcode() == Instruction::IntToPtr) &&
35 SE.getTypeSizeInBits(CI->getType()) ==
36 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
37 return CI->getOperand(0);
38 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
39 if ((CE->getOpcode() == Instruction::PtrToInt ||
40 CE->getOpcode() == Instruction::IntToPtr) &&
41 SE.getTypeSizeInBits(CE->getType()) ==
42 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
43 return CE->getOperand(0);
46 // FIXME: keep track of the cast instruction.
47 if (Constant *C = dyn_cast<Constant>(V))
48 return ConstantExpr::getCast(opcode, C, Ty);
50 if (Argument *A = dyn_cast<Argument>(V)) {
51 // Check to see if there is already a cast!
52 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
54 if ((*UI)->getType() == Ty)
55 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
56 if (CI->getOpcode() == opcode) {
57 // If the cast isn't the first instruction of the function, move it.
58 if (BasicBlock::iterator(CI) !=
59 A->getParent()->getEntryBlock().begin()) {
60 // If the CastInst is the insert point, change the insert point.
61 if (CI == InsertPt) ++InsertPt;
62 // Splice the cast at the beginning of the entry block.
63 CI->moveBefore(A->getParent()->getEntryBlock().begin());
68 Instruction *I = CastInst::Create(opcode, V, Ty, V->getName(),
69 A->getParent()->getEntryBlock().begin());
70 InsertedValues.insert(I);
74 Instruction *I = cast<Instruction>(V);
76 // Check to see if there is already a cast. If there is, use it.
77 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
79 if ((*UI)->getType() == Ty)
80 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
81 if (CI->getOpcode() == opcode) {
82 BasicBlock::iterator It = I; ++It;
83 if (isa<InvokeInst>(I))
84 It = cast<InvokeInst>(I)->getNormalDest()->begin();
85 while (isa<PHINode>(It)) ++It;
86 if (It != BasicBlock::iterator(CI)) {
87 // If the CastInst is the insert point, change the insert point.
88 if (CI == InsertPt) ++InsertPt;
89 // Splice the cast immediately after the operand in question.
95 BasicBlock::iterator IP = I; ++IP;
96 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
97 IP = II->getNormalDest()->begin();
98 while (isa<PHINode>(IP)) ++IP;
99 Instruction *CI = CastInst::Create(opcode, V, Ty, V->getName(), IP);
100 InsertedValues.insert(CI);
104 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
105 /// which must be possible with a noop cast.
106 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
107 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
108 assert((Op == Instruction::BitCast ||
109 Op == Instruction::PtrToInt ||
110 Op == Instruction::IntToPtr) &&
111 "InsertNoopCastOfTo cannot perform non-noop casts!");
112 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
113 "InsertNoopCastOfTo cannot change sizes!");
114 return InsertCastOfTo(Op, V, Ty);
117 /// InsertBinop - Insert the specified binary operator, doing a small amount
118 /// of work to avoid inserting an obviously redundant operation.
119 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode, Value *LHS,
120 Value *RHS, BasicBlock::iterator InsertPt) {
121 // Fold a binop with constant operands.
122 if (Constant *CLHS = dyn_cast<Constant>(LHS))
123 if (Constant *CRHS = dyn_cast<Constant>(RHS))
124 return ConstantExpr::get(Opcode, CLHS, CRHS);
126 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
127 unsigned ScanLimit = 6;
128 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
129 if (InsertPt != BlockBegin) {
130 // Scanning starts from the last instruction before InsertPt.
131 BasicBlock::iterator IP = InsertPt;
133 for (; ScanLimit; --IP, --ScanLimit) {
134 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
135 IP->getOperand(1) == RHS)
137 if (IP == BlockBegin) break;
141 // If we haven't found this binop, insert it.
142 Instruction *BO = BinaryOperator::Create(Opcode, LHS, RHS, "tmp", InsertPt);
143 InsertedValues.insert(BO);
147 /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
148 /// instead of using ptrtoint+arithmetic+inttoptr.
149 Value *SCEVExpander::expandAddToGEP(const SCEVAddExpr *S,
150 const PointerType *PTy,
153 const Type *ElTy = PTy->getElementType();
154 SmallVector<Value *, 4> GepIndices;
155 std::vector<SCEVHandle> Ops = S->getOperands();
156 bool AnyNonZeroIndices = false;
159 // Decend down the pointer's type and attempt to convert the other
160 // operands into GEP indices, at each level. The first index in a GEP
161 // indexes into the array implied by the pointer operand; the rest of
162 // the indices index into the element or field type selected by the
165 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
166 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
167 std::vector<SCEVHandle> NewOps;
168 std::vector<SCEVHandle> ScaledOps;
169 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
171 // For a Constant, check for a multiple of the pointer type's
173 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i]))
174 if (!C->getValue()->getValue().srem(ElSize)) {
176 ConstantInt::get(C->getValue()->getValue().sdiv(ElSize));
177 SCEVHandle Div = SE.getConstant(CI);
178 ScaledOps.push_back(Div);
181 // In a Mul, check if there is a constant operand which is a multiple
182 // of the pointer type's scale size.
183 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i]))
184 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
185 if (!C->getValue()->getValue().srem(ElSize)) {
186 std::vector<SCEVHandle> NewMulOps(M->getOperands());
188 SE.getConstant(C->getValue()->getValue().sdiv(ElSize));
189 ScaledOps.push_back(SE.getMulExpr(NewMulOps));
192 // In an Unknown, check if the underlying value is a Mul by a constant
193 // which is equal to the pointer type's scale size.
194 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i]))
195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getValue()))
196 if (BO->getOpcode() == Instruction::Mul)
197 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
198 if (CI->getValue() == ElSize) {
199 ScaledOps.push_back(SE.getUnknown(BO->getOperand(0)));
202 // If the pointer type's scale size is 1, no scaling is necessary
203 // and any value can be used.
205 ScaledOps.push_back(Ops[i]);
209 NewOps.push_back(Ops[i]);
212 AnyNonZeroIndices |= !ScaledOps.empty();
213 Value *Scaled = ScaledOps.empty() ?
214 Constant::getNullValue(Ty) :
215 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
216 GepIndices.push_back(Scaled);
218 // Collect struct field index operands.
220 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
221 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
222 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
223 const StructLayout &SL = *SE.TD->getStructLayout(STy);
224 uint64_t FullOffset = C->getValue()->getZExtValue();
225 if (FullOffset < SL.getSizeInBytes()) {
226 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
227 GepIndices.push_back(ConstantInt::get(Type::Int32Ty, ElIdx));
228 ElTy = STy->getTypeAtIndex(ElIdx);
230 SE.getConstant(ConstantInt::get(Ty,
232 SL.getElementOffset(ElIdx)));
233 AnyNonZeroIndices = true;
240 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
241 ElTy = ATy->getElementType();
247 // If none of the operands were convertable to proper GEP indices, cast
248 // the base to i8* and do an ugly getelementptr with that. It's still
249 // better than ptrtoint+arithmetic+inttoptr at least.
250 if (!AnyNonZeroIndices) {
251 V = InsertNoopCastOfTo(V,
252 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
253 Value *Idx = expand(SE.getAddExpr(Ops));
254 Idx = InsertNoopCastOfTo(Idx, Ty);
256 // Fold a GEP with constant operands.
257 if (Constant *CLHS = dyn_cast<Constant>(V))
258 if (Constant *CRHS = dyn_cast<Constant>(Idx))
259 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
261 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
262 unsigned ScanLimit = 6;
263 BasicBlock::iterator BlockBegin = InsertPt->getParent()->begin();
264 if (InsertPt != BlockBegin) {
265 // Scanning starts from the last instruction before InsertPt.
266 BasicBlock::iterator IP = InsertPt;
268 for (; ScanLimit; --IP, --ScanLimit) {
269 if (IP->getOpcode() == Instruction::GetElementPtr &&
270 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
272 if (IP == BlockBegin) break;
276 Value *GEP = GetElementPtrInst::Create(V, Idx, "scevgep", InsertPt);
277 InsertedValues.insert(GEP);
281 // Insert a pretty getelementptr.
282 Value *GEP = GetElementPtrInst::Create(V,
285 "scevgep", InsertPt);
286 Ops.push_back(SE.getUnknown(GEP));
287 InsertedValues.insert(GEP);
288 return expand(SE.getAddExpr(Ops));
291 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
292 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
293 Value *V = expand(S->getOperand(S->getNumOperands()-1));
295 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. This helps
296 // BasicAliasAnalysis analyze the result. However, it suffers from the
297 // underlying bug described in PR2831. Addition in LLVM currently always
298 // has two's complement wrapping guaranteed. However, the semantics for
299 // getelementptr overflow are ambiguous. In the common case though, this
300 // expansion gets used when a GEP in the original code has been converted
301 // into integer arithmetic, in which case the resulting code will be no
302 // more undefined than it was originally.
304 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
305 return expandAddToGEP(S, PTy, Ty, V);
307 V = InsertNoopCastOfTo(V, Ty);
309 // Emit a bunch of add instructions
310 for (int i = S->getNumOperands()-2; i >= 0; --i) {
311 Value *W = expand(S->getOperand(i));
312 W = InsertNoopCastOfTo(W, Ty);
313 V = InsertBinop(Instruction::Add, V, W, InsertPt);
318 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
319 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
320 int FirstOp = 0; // Set if we should emit a subtract.
321 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
322 if (SC->getValue()->isAllOnesValue())
325 int i = S->getNumOperands()-2;
326 Value *V = expand(S->getOperand(i+1));
327 V = InsertNoopCastOfTo(V, Ty);
329 // Emit a bunch of multiply instructions
330 for (; i >= FirstOp; --i) {
331 Value *W = expand(S->getOperand(i));
332 W = InsertNoopCastOfTo(W, Ty);
333 V = InsertBinop(Instruction::Mul, V, W, InsertPt);
336 // -1 * ... ---> 0 - ...
338 V = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), V, InsertPt);
342 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
343 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
345 Value *LHS = expand(S->getLHS());
346 LHS = InsertNoopCastOfTo(LHS, Ty);
347 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
348 const APInt &RHS = SC->getValue()->getValue();
349 if (RHS.isPowerOf2())
350 return InsertBinop(Instruction::LShr, LHS,
351 ConstantInt::get(Ty, RHS.logBase2()),
355 Value *RHS = expand(S->getRHS());
356 RHS = InsertNoopCastOfTo(RHS, Ty);
357 return InsertBinop(Instruction::UDiv, LHS, RHS, InsertPt);
360 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
361 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
362 const Loop *L = S->getLoop();
364 // {X,+,F} --> X + {0,+,F}
365 if (!S->getStart()->isZero()) {
366 std::vector<SCEVHandle> NewOps(S->getOperands());
367 NewOps[0] = SE.getIntegerSCEV(0, Ty);
368 Value *Rest = expand(SE.getAddRecExpr(NewOps, L));
369 return expand(SE.getAddExpr(S->getStart(), SE.getUnknown(Rest)));
372 // {0,+,1} --> Insert a canonical induction variable into the loop!
374 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
375 // Create and insert the PHI node for the induction variable in the
377 BasicBlock *Header = L->getHeader();
378 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
379 InsertedValues.insert(PN);
380 PN->addIncoming(Constant::getNullValue(Ty), L->getLoopPreheader());
382 pred_iterator HPI = pred_begin(Header);
383 assert(HPI != pred_end(Header) && "Loop with zero preds???");
384 if (!L->contains(*HPI)) ++HPI;
385 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
386 "No backedge in loop?");
388 // Insert a unit add instruction right before the terminator corresponding
390 Constant *One = ConstantInt::get(Ty, 1);
391 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
392 (*HPI)->getTerminator());
393 InsertedValues.insert(Add);
395 pred_iterator PI = pred_begin(Header);
396 if (*PI == L->getLoopPreheader())
398 PN->addIncoming(Add, *PI);
402 // Get the canonical induction variable I for this loop.
403 Value *I = getOrInsertCanonicalInductionVariable(L, Ty);
405 // If this is a simple linear addrec, emit it now as a special case.
406 if (S->isAffine()) { // {0,+,F} --> i*F
407 Value *F = expand(S->getOperand(1));
408 F = InsertNoopCastOfTo(F, Ty);
410 // IF the step is by one, just return the inserted IV.
411 if (ConstantInt *CI = dyn_cast<ConstantInt>(F))
412 if (CI->getValue() == 1)
415 // If the insert point is directly inside of the loop, emit the multiply at
416 // the insert point. Otherwise, L is a loop that is a parent of the insert
417 // point loop. If we can, move the multiply to the outer most loop that it
419 BasicBlock::iterator MulInsertPt = getInsertionPoint();
420 Loop *InsertPtLoop = SE.LI->getLoopFor(MulInsertPt->getParent());
421 if (InsertPtLoop != L && InsertPtLoop &&
422 L->contains(InsertPtLoop->getHeader())) {
424 // If we cannot hoist the multiply out of this loop, don't.
425 if (!InsertPtLoop->isLoopInvariant(F)) break;
427 BasicBlock *InsertPtLoopPH = InsertPtLoop->getLoopPreheader();
429 // If this loop hasn't got a preheader, we aren't able to hoist the
434 // Otherwise, move the insert point to the preheader.
435 MulInsertPt = InsertPtLoopPH->getTerminator();
436 InsertPtLoop = InsertPtLoop->getParentLoop();
437 } while (InsertPtLoop != L);
440 return InsertBinop(Instruction::Mul, I, F, MulInsertPt);
443 // If this is a chain of recurrences, turn it into a closed form, using the
444 // folders, then expandCodeFor the closed form. This allows the folders to
445 // simplify the expression without having to build a bunch of special code
447 SCEVHandle IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
449 SCEVHandle V = S->evaluateAtIteration(IH, SE);
450 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
455 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
456 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
457 Value *V = expand(S->getOperand());
458 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
459 Instruction *I = new TruncInst(V, Ty, "tmp.", InsertPt);
460 InsertedValues.insert(I);
464 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
465 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
466 Value *V = expand(S->getOperand());
467 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
468 Instruction *I = new ZExtInst(V, Ty, "tmp.", InsertPt);
469 InsertedValues.insert(I);
473 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
474 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
475 Value *V = expand(S->getOperand());
476 V = InsertNoopCastOfTo(V, SE.getEffectiveSCEVType(V->getType()));
477 Instruction *I = new SExtInst(V, Ty, "tmp.", InsertPt);
478 InsertedValues.insert(I);
482 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
483 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
484 Value *LHS = expand(S->getOperand(0));
485 LHS = InsertNoopCastOfTo(LHS, Ty);
486 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
487 Value *RHS = expand(S->getOperand(i));
488 RHS = InsertNoopCastOfTo(RHS, Ty);
490 new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS, "tmp", InsertPt);
491 InsertedValues.insert(ICmp);
492 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "smax", InsertPt);
493 InsertedValues.insert(Sel);
499 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
500 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
501 Value *LHS = expand(S->getOperand(0));
502 LHS = InsertNoopCastOfTo(LHS, Ty);
503 for (unsigned i = 1; i < S->getNumOperands(); ++i) {
504 Value *RHS = expand(S->getOperand(i));
505 RHS = InsertNoopCastOfTo(RHS, Ty);
507 new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS, "tmp", InsertPt);
508 InsertedValues.insert(ICmp);
509 Instruction *Sel = SelectInst::Create(ICmp, LHS, RHS, "umax", InsertPt);
510 InsertedValues.insert(Sel);
516 Value *SCEVExpander::expandCodeFor(SCEVHandle SH, const Type *Ty) {
517 // Expand the code for this SCEV.
518 Value *V = expand(SH);
520 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
521 "non-trivial casts should be done with the SCEVs directly!");
522 V = InsertNoopCastOfTo(V, Ty);
527 Value *SCEVExpander::expand(const SCEV *S) {
528 // Check to see if we already expanded this.
529 std::map<SCEVHandle, Value*>::iterator I = InsertedExpressions.find(S);
530 if (I != InsertedExpressions.end())
534 InsertedExpressions[S] = V;