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/LLVMContext.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/ADT/STLExtras.h"
23 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
24 /// which must be possible with a noop cast, doing what we can to share
26 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
27 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
28 assert((Op == Instruction::BitCast ||
29 Op == Instruction::PtrToInt ||
30 Op == Instruction::IntToPtr) &&
31 "InsertNoopCastOfTo cannot perform non-noop casts!");
32 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
33 "InsertNoopCastOfTo cannot change sizes!");
35 // Short-circuit unnecessary bitcasts.
36 if (Op == Instruction::BitCast && V->getType() == Ty)
39 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
40 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
41 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
42 if (CastInst *CI = dyn_cast<CastInst>(V))
43 if ((CI->getOpcode() == Instruction::PtrToInt ||
44 CI->getOpcode() == Instruction::IntToPtr) &&
45 SE.getTypeSizeInBits(CI->getType()) ==
46 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
47 return CI->getOperand(0);
48 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
49 if ((CE->getOpcode() == Instruction::PtrToInt ||
50 CE->getOpcode() == Instruction::IntToPtr) &&
51 SE.getTypeSizeInBits(CE->getType()) ==
52 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
53 return CE->getOperand(0);
56 // FIXME: keep track of the cast instruction.
57 if (Constant *C = dyn_cast<Constant>(V))
58 return getContext()->getConstantExprCast(Op, C, Ty);
60 if (Argument *A = dyn_cast<Argument>(V)) {
61 // Check to see if there is already a cast!
62 for (Value::use_iterator UI = A->use_begin(), E = A->use_end();
64 if ((*UI)->getType() == Ty)
65 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
66 if (CI->getOpcode() == Op) {
67 // If the cast isn't the first instruction of the function, move it.
68 if (BasicBlock::iterator(CI) !=
69 A->getParent()->getEntryBlock().begin()) {
70 // Recreate the cast at the beginning of the entry block.
71 // The old cast is left in place in case it is being used
72 // as an insert point.
74 CastInst::Create(Op, V, Ty, "",
75 A->getParent()->getEntryBlock().begin());
77 CI->replaceAllUsesWith(NewCI);
83 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(),
84 A->getParent()->getEntryBlock().begin());
85 InsertedValues.insert(I);
89 Instruction *I = cast<Instruction>(V);
91 // Check to see if there is already a cast. If there is, use it.
92 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
94 if ((*UI)->getType() == Ty)
95 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
96 if (CI->getOpcode() == Op) {
97 BasicBlock::iterator It = I; ++It;
98 if (isa<InvokeInst>(I))
99 It = cast<InvokeInst>(I)->getNormalDest()->begin();
100 while (isa<PHINode>(It)) ++It;
101 if (It != BasicBlock::iterator(CI)) {
102 // Recreate the cast at the beginning of the entry block.
103 // The old cast is left in place in case it is being used
104 // as an insert point.
105 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", It);
107 CI->replaceAllUsesWith(NewCI);
113 BasicBlock::iterator IP = I; ++IP;
114 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
115 IP = II->getNormalDest()->begin();
116 while (isa<PHINode>(IP)) ++IP;
117 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
118 InsertedValues.insert(CI);
122 /// InsertBinop - Insert the specified binary operator, doing a small amount
123 /// of work to avoid inserting an obviously redundant operation.
124 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
125 Value *LHS, Value *RHS) {
126 // Fold a binop with constant operands.
127 if (Constant *CLHS = dyn_cast<Constant>(LHS))
128 if (Constant *CRHS = dyn_cast<Constant>(RHS))
129 return getContext()->getConstantExpr(Opcode, CLHS, CRHS);
131 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
132 unsigned ScanLimit = 6;
133 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
134 // Scanning starts from the last instruction before the insertion point.
135 BasicBlock::iterator IP = Builder.GetInsertPoint();
136 if (IP != BlockBegin) {
138 for (; ScanLimit; --IP, --ScanLimit) {
139 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
140 IP->getOperand(1) == RHS)
142 if (IP == BlockBegin) break;
146 // If we haven't found this binop, insert it.
147 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
148 InsertedValues.insert(BO);
152 /// FactorOutConstant - Test if S is divisible by Factor, using signed
153 /// division. If so, update S with Factor divided out and return true.
154 /// S need not be evenly divisble if a reasonable remainder can be
156 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
157 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
158 /// check to see if the divide was folded.
159 static bool FactorOutConstant(const SCEV *&S,
160 const SCEV *&Remainder,
162 ScalarEvolution &SE) {
163 // Everything is divisible by one.
167 // For a Constant, check for a multiple of the given factor.
168 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
170 SE.getContext()->getConstantInt(C->getValue()->getValue().sdiv(Factor));
171 // If the quotient is zero and the remainder is non-zero, reject
172 // the value at this scale. It will be considered for subsequent
174 if (C->isZero() || !CI->isZero()) {
175 const SCEV *Div = SE.getConstant(CI);
178 SE.getAddExpr(Remainder,
179 SE.getConstant(C->getValue()->getValue().srem(Factor)));
184 // In a Mul, check if there is a constant operand which is a multiple
185 // of the given factor.
186 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S))
187 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
188 if (!C->getValue()->getValue().srem(Factor)) {
189 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
190 SmallVector<const SCEV *, 4> NewMulOps(MOperands.begin(),
193 SE.getConstant(C->getValue()->getValue().sdiv(Factor));
194 S = SE.getMulExpr(NewMulOps);
198 // In an AddRec, check if both start and step are divisible.
199 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
200 const SCEV *Step = A->getStepRecurrence(SE);
201 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
202 if (!FactorOutConstant(Step, StepRem, Factor, SE))
204 if (!StepRem->isZero())
206 const SCEV *Start = A->getStart();
207 if (!FactorOutConstant(Start, Remainder, Factor, SE))
209 S = SE.getAddRecExpr(Start, Step, A->getLoop());
216 /// expandAddToGEP - Expand a SCEVAddExpr with a pointer type into a GEP
217 /// instead of using ptrtoint+arithmetic+inttoptr. This helps
218 /// BasicAliasAnalysis analyze the result. However, it suffers from the
219 /// underlying bug described in PR2831. Addition in LLVM currently always
220 /// has two's complement wrapping guaranteed. However, the semantics for
221 /// getelementptr overflow are ambiguous. In the common case though, this
222 /// expansion gets used when a GEP in the original code has been converted
223 /// into integer arithmetic, in which case the resulting code will be no
224 /// more undefined than it was originally.
226 /// Design note: It might seem desirable for this function to be more
227 /// loop-aware. If some of the indices are loop-invariant while others
228 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
229 /// loop-invariant portions of the overall computation outside the loop.
230 /// However, there are a few reasons this is not done here. Hoisting simple
231 /// arithmetic is a low-level optimization that often isn't very
232 /// important until late in the optimization process. In fact, passes
233 /// like InstructionCombining will combine GEPs, even if it means
234 /// pushing loop-invariant computation down into loops, so even if the
235 /// GEPs were split here, the work would quickly be undone. The
236 /// LoopStrengthReduction pass, which is usually run quite late (and
237 /// after the last InstructionCombining pass), takes care of hoisting
238 /// loop-invariant portions of expressions, after considering what
239 /// can be folded using target addressing modes.
241 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
242 const SCEV *const *op_end,
243 const PointerType *PTy,
246 const Type *ElTy = PTy->getElementType();
247 SmallVector<Value *, 4> GepIndices;
248 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
249 bool AnyNonZeroIndices = false;
251 // Decend down the pointer's type and attempt to convert the other
252 // operands into GEP indices, at each level. The first index in a GEP
253 // indexes into the array implied by the pointer operand; the rest of
254 // the indices index into the element or field type selected by the
257 APInt ElSize = APInt(SE.getTypeSizeInBits(Ty),
258 ElTy->isSized() ? SE.TD->getTypeAllocSize(ElTy) : 0);
259 SmallVector<const SCEV *, 8> NewOps;
260 SmallVector<const SCEV *, 8> ScaledOps;
261 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
262 // Split AddRecs up into parts as either of the parts may be usable
263 // without the other.
264 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i]))
265 if (!A->getStart()->isZero()) {
266 const SCEV *Start = A->getStart();
267 Ops.push_back(SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
268 A->getStepRecurrence(SE),
273 // If the scale size is not 0, attempt to factor out a scale.
275 const SCEV *Op = Ops[i];
276 const SCEV *Remainder = SE.getIntegerSCEV(0, Op->getType());
277 if (FactorOutConstant(Op, Remainder, ElSize, SE)) {
278 ScaledOps.push_back(Op); // Op now has ElSize factored out.
279 NewOps.push_back(Remainder);
283 // If the operand was not divisible, add it to the list of operands
284 // we'll scan next iteration.
285 NewOps.push_back(Ops[i]);
288 AnyNonZeroIndices |= !ScaledOps.empty();
289 Value *Scaled = ScaledOps.empty() ?
290 getContext()->getNullValue(Ty) :
291 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
292 GepIndices.push_back(Scaled);
294 // Collect struct field index operands.
296 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
297 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
298 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
299 const StructLayout &SL = *SE.TD->getStructLayout(STy);
300 uint64_t FullOffset = C->getValue()->getZExtValue();
301 if (FullOffset < SL.getSizeInBytes()) {
302 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
303 GepIndices.push_back(
304 getContext()->getConstantInt(Type::Int32Ty, ElIdx));
305 ElTy = STy->getTypeAtIndex(ElIdx);
307 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
308 AnyNonZeroIndices = true;
315 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy)) {
316 ElTy = ATy->getElementType();
322 // If none of the operands were convertable to proper GEP indices, cast
323 // the base to i8* and do an ugly getelementptr with that. It's still
324 // better than ptrtoint+arithmetic+inttoptr at least.
325 if (!AnyNonZeroIndices) {
326 V = InsertNoopCastOfTo(V,
327 Type::Int8Ty->getPointerTo(PTy->getAddressSpace()));
328 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
330 // Fold a GEP with constant operands.
331 if (Constant *CLHS = dyn_cast<Constant>(V))
332 if (Constant *CRHS = dyn_cast<Constant>(Idx))
333 return getContext()->getConstantExprGetElementPtr(CLHS, &CRHS, 1);
335 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
336 unsigned ScanLimit = 6;
337 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
338 // Scanning starts from the last instruction before the insertion point.
339 BasicBlock::iterator IP = Builder.GetInsertPoint();
340 if (IP != BlockBegin) {
342 for (; ScanLimit; --IP, --ScanLimit) {
343 if (IP->getOpcode() == Instruction::GetElementPtr &&
344 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
346 if (IP == BlockBegin) break;
350 Value *GEP = Builder.CreateGEP(V, Idx, "scevgep");
351 InsertedValues.insert(GEP);
355 // Insert a pretty getelementptr.
356 Value *GEP = Builder.CreateGEP(V,
360 Ops.push_back(SE.getUnknown(GEP));
361 InsertedValues.insert(GEP);
362 return expand(SE.getAddExpr(Ops));
365 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
366 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
367 Value *V = expand(S->getOperand(S->getNumOperands()-1));
369 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
370 // comments on expandAddToGEP for details.
372 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType())) {
373 const SmallVectorImpl<const SCEV *> &Ops = S->getOperands();
374 return expandAddToGEP(&Ops[0], &Ops[Ops.size() - 1], PTy, Ty, V);
377 V = InsertNoopCastOfTo(V, Ty);
379 // Emit a bunch of add instructions
380 for (int i = S->getNumOperands()-2; i >= 0; --i) {
381 Value *W = expandCodeFor(S->getOperand(i), Ty);
382 V = InsertBinop(Instruction::Add, V, W);
387 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
388 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
389 int FirstOp = 0; // Set if we should emit a subtract.
390 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getOperand(0)))
391 if (SC->getValue()->isAllOnesValue())
394 int i = S->getNumOperands()-2;
395 Value *V = expandCodeFor(S->getOperand(i+1), Ty);
397 // Emit a bunch of multiply instructions
398 for (; i >= FirstOp; --i) {
399 Value *W = expandCodeFor(S->getOperand(i), Ty);
400 V = InsertBinop(Instruction::Mul, V, W);
403 // -1 * ... ---> 0 - ...
405 V = InsertBinop(Instruction::Sub, getContext()->getNullValue(Ty), V);
409 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
410 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
412 Value *LHS = expandCodeFor(S->getLHS(), Ty);
413 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
414 const APInt &RHS = SC->getValue()->getValue();
415 if (RHS.isPowerOf2())
416 return InsertBinop(Instruction::LShr, LHS,
417 getContext()->getConstantInt(Ty, RHS.logBase2()));
420 Value *RHS = expandCodeFor(S->getRHS(), Ty);
421 return InsertBinop(Instruction::UDiv, LHS, RHS);
424 /// Move parts of Base into Rest to leave Base with the minimal
425 /// expression that provides a pointer operand suitable for a
427 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
428 ScalarEvolution &SE) {
429 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
430 Base = A->getStart();
431 Rest = SE.getAddExpr(Rest,
432 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
433 A->getStepRecurrence(SE),
436 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
437 Base = A->getOperand(A->getNumOperands()-1);
438 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
439 NewAddOps.back() = Rest;
440 Rest = SE.getAddExpr(NewAddOps);
441 ExposePointerBase(Base, Rest, SE);
445 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
446 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
447 const Loop *L = S->getLoop();
449 // First check for an existing canonical IV in a suitable type.
450 PHINode *CanonicalIV = 0;
451 if (PHINode *PN = L->getCanonicalInductionVariable())
452 if (SE.isSCEVable(PN->getType()) &&
453 isa<IntegerType>(SE.getEffectiveSCEVType(PN->getType())) &&
454 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
457 // Rewrite an AddRec in terms of the canonical induction variable, if
458 // its type is more narrow.
460 SE.getTypeSizeInBits(CanonicalIV->getType()) >
461 SE.getTypeSizeInBits(Ty)) {
462 const SCEV *Start = SE.getAnyExtendExpr(S->getStart(),
463 CanonicalIV->getType());
464 const SCEV *Step = SE.getAnyExtendExpr(S->getStepRecurrence(SE),
465 CanonicalIV->getType());
466 Value *V = expand(SE.getAddRecExpr(Start, Step, S->getLoop()));
467 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
468 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
469 BasicBlock::iterator NewInsertPt =
470 next(BasicBlock::iterator(cast<Instruction>(V)));
471 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
472 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
474 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
478 // {X,+,F} --> X + {0,+,F}
479 if (!S->getStart()->isZero()) {
480 const SmallVectorImpl<const SCEV *> &SOperands = S->getOperands();
481 SmallVector<const SCEV *, 4> NewOps(SOperands.begin(), SOperands.end());
482 NewOps[0] = SE.getIntegerSCEV(0, Ty);
483 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
485 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
486 // comments on expandAddToGEP for details.
488 const SCEV *Base = S->getStart();
489 const SCEV *RestArray[1] = { Rest };
490 // Dig into the expression to find the pointer base for a GEP.
491 ExposePointerBase(Base, RestArray[0], SE);
492 // If we found a pointer, expand the AddRec with a GEP.
493 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
494 // Make sure the Base isn't something exotic, such as a multiplied
495 // or divided pointer value. In those cases, the result type isn't
496 // actually a pointer type.
497 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
498 Value *StartV = expand(Base);
499 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
500 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
505 // Just do a normal add. Pre-expand the operands to suppress folding.
506 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
507 SE.getUnknown(expand(Rest))));
510 // {0,+,1} --> Insert a canonical induction variable into the loop!
512 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
513 // If there's a canonical IV, just use it.
515 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
516 "IVs with types different from the canonical IV should "
517 "already have been handled!");
521 // Create and insert the PHI node for the induction variable in the
523 BasicBlock *Header = L->getHeader();
524 BasicBlock *Preheader = L->getLoopPreheader();
525 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
526 InsertedValues.insert(PN);
527 PN->addIncoming(getContext()->getNullValue(Ty), Preheader);
529 pred_iterator HPI = pred_begin(Header);
530 assert(HPI != pred_end(Header) && "Loop with zero preds???");
531 if (!L->contains(*HPI)) ++HPI;
532 assert(HPI != pred_end(Header) && L->contains(*HPI) &&
533 "No backedge in loop?");
535 // Insert a unit add instruction right before the terminator corresponding
537 Constant *One = getContext()->getConstantInt(Ty, 1);
538 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
539 (*HPI)->getTerminator());
540 InsertedValues.insert(Add);
542 pred_iterator PI = pred_begin(Header);
543 if (*PI == Preheader)
545 PN->addIncoming(Add, *PI);
549 // {0,+,F} --> {0,+,1} * F
550 // Get the canonical induction variable I for this loop.
551 Value *I = CanonicalIV ?
553 getOrInsertCanonicalInductionVariable(L, Ty);
555 // If this is a simple linear addrec, emit it now as a special case.
556 if (S->isAffine()) // {0,+,F} --> i*F
558 expand(SE.getTruncateOrNoop(
559 SE.getMulExpr(SE.getUnknown(I),
560 SE.getNoopOrAnyExtend(S->getOperand(1),
564 // If this is a chain of recurrences, turn it into a closed form, using the
565 // folders, then expandCodeFor the closed form. This allows the folders to
566 // simplify the expression without having to build a bunch of special code
568 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
570 // Promote S up to the canonical IV type, if the cast is foldable.
571 const SCEV *NewS = S;
572 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
573 if (isa<SCEVAddRecExpr>(Ext))
576 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
577 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
579 // Truncate the result down to the original type, if needed.
580 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
584 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
585 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
586 Value *V = expandCodeFor(S->getOperand(),
587 SE.getEffectiveSCEVType(S->getOperand()->getType()));
588 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
589 InsertedValues.insert(I);
593 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
594 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
595 Value *V = expandCodeFor(S->getOperand(),
596 SE.getEffectiveSCEVType(S->getOperand()->getType()));
597 Value *I = Builder.CreateZExt(V, Ty, "tmp");
598 InsertedValues.insert(I);
602 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
603 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
604 Value *V = expandCodeFor(S->getOperand(),
605 SE.getEffectiveSCEVType(S->getOperand()->getType()));
606 Value *I = Builder.CreateSExt(V, Ty, "tmp");
607 InsertedValues.insert(I);
611 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
612 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
613 const Type *Ty = LHS->getType();
614 for (int i = S->getNumOperands()-2; i >= 0; --i) {
615 // In the case of mixed integer and pointer types, do the
616 // rest of the comparisons as integer.
617 if (S->getOperand(i)->getType() != Ty) {
618 Ty = SE.getEffectiveSCEVType(Ty);
619 LHS = InsertNoopCastOfTo(LHS, Ty);
621 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
622 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
623 InsertedValues.insert(ICmp);
624 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
625 InsertedValues.insert(Sel);
628 // In the case of mixed integer and pointer types, cast the
629 // final result back to the pointer type.
630 if (LHS->getType() != S->getType())
631 LHS = InsertNoopCastOfTo(LHS, S->getType());
635 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
636 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
637 const Type *Ty = LHS->getType();
638 for (int i = S->getNumOperands()-2; i >= 0; --i) {
639 // In the case of mixed integer and pointer types, do the
640 // rest of the comparisons as integer.
641 if (S->getOperand(i)->getType() != Ty) {
642 Ty = SE.getEffectiveSCEVType(Ty);
643 LHS = InsertNoopCastOfTo(LHS, Ty);
645 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
646 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
647 InsertedValues.insert(ICmp);
648 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
649 InsertedValues.insert(Sel);
652 // In the case of mixed integer and pointer types, cast the
653 // final result back to the pointer type.
654 if (LHS->getType() != S->getType())
655 LHS = InsertNoopCastOfTo(LHS, S->getType());
659 Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
660 // Expand the code for this SCEV.
661 Value *V = expand(SH);
663 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
664 "non-trivial casts should be done with the SCEVs directly!");
665 V = InsertNoopCastOfTo(V, Ty);
670 Value *SCEVExpander::expand(const SCEV *S) {
671 // Compute an insertion point for this SCEV object. Hoist the instructions
672 // as far out in the loop nest as possible.
673 Instruction *InsertPt = Builder.GetInsertPoint();
674 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
675 L = L->getParentLoop())
676 if (S->isLoopInvariant(L)) {
678 if (BasicBlock *Preheader = L->getLoopPreheader())
679 InsertPt = Preheader->getTerminator();
681 // If the SCEV is computable at this level, insert it into the header
682 // after the PHIs (and after any other instructions that we've inserted
683 // there) so that it is guaranteed to dominate any user inside the loop.
684 if (L && S->hasComputableLoopEvolution(L))
685 InsertPt = L->getHeader()->getFirstNonPHI();
686 while (isInsertedInstruction(InsertPt))
687 InsertPt = next(BasicBlock::iterator(InsertPt));
691 // Check to see if we already expanded this here.
692 std::map<std::pair<const SCEV *, Instruction *>,
693 AssertingVH<Value> >::iterator I =
694 InsertedExpressions.find(std::make_pair(S, InsertPt));
695 if (I != InsertedExpressions.end())
698 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
699 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
700 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
702 // Expand the expression into instructions.
705 // Remember the expanded value for this SCEV at this location.
706 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
708 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);
712 /// getOrInsertCanonicalInductionVariable - This method returns the
713 /// canonical induction variable of the specified type for the specified
714 /// loop (inserting one if there is none). A canonical induction variable
715 /// starts at zero and steps by one on each iteration.
717 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
719 assert(Ty->isInteger() && "Can only insert integer induction variables!");
720 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
721 SE.getIntegerSCEV(1, Ty), L);
722 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
723 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
724 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
726 Builder.SetInsertPoint(SaveInsertBB, SaveInsertPt);