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/IntrinsicInst.h"
19 #include "llvm/LLVMContext.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/ADT/STLExtras.h"
24 /// ReuseOrCreateCast - Arange for there to be a cast of V to Ty at IP,
25 /// reusing an existing cast if a suitable one exists, moving an existing
26 /// cast if a suitable one exists but isn't in the right place, or
27 /// or creating a new one.
28 Value *SCEVExpander::ReuseOrCreateCast(Value *V, const Type *Ty,
29 Instruction::CastOps Op,
30 BasicBlock::iterator IP) {
31 // Check to see if there is already a cast!
32 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
34 if ((*UI)->getType() == Ty)
35 if (CastInst *CI = dyn_cast<CastInst>(cast<Instruction>(*UI)))
36 if (CI->getOpcode() == Op) {
37 // If the cast isn't where we want it, fix it.
38 if (BasicBlock::iterator(CI) != IP) {
39 // Create a new cast, and leave the old cast in place in case
40 // it is being used as an insert point. Clear its operand
41 // so that it doesn't hold anything live.
42 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
44 CI->replaceAllUsesWith(NewCI);
45 CI->setOperand(0, UndefValue::get(V->getType()));
46 rememberInstruction(NewCI);
49 rememberInstruction(CI);
54 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
55 rememberInstruction(I);
59 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
60 /// which must be possible with a noop cast, doing what we can to share
62 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
63 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
64 assert((Op == Instruction::BitCast ||
65 Op == Instruction::PtrToInt ||
66 Op == Instruction::IntToPtr) &&
67 "InsertNoopCastOfTo cannot perform non-noop casts!");
68 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
69 "InsertNoopCastOfTo cannot change sizes!");
71 // Short-circuit unnecessary bitcasts.
72 if (Op == Instruction::BitCast && V->getType() == Ty)
75 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
76 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
77 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
78 if (CastInst *CI = dyn_cast<CastInst>(V))
79 if ((CI->getOpcode() == Instruction::PtrToInt ||
80 CI->getOpcode() == Instruction::IntToPtr) &&
81 SE.getTypeSizeInBits(CI->getType()) ==
82 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
83 return CI->getOperand(0);
84 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
85 if ((CE->getOpcode() == Instruction::PtrToInt ||
86 CE->getOpcode() == Instruction::IntToPtr) &&
87 SE.getTypeSizeInBits(CE->getType()) ==
88 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
89 return CE->getOperand(0);
92 // Fold a cast of a constant.
93 if (Constant *C = dyn_cast<Constant>(V))
94 return ConstantExpr::getCast(Op, C, Ty);
96 // Cast the argument at the beginning of the entry block, after
97 // any bitcasts of other arguments.
98 if (Argument *A = dyn_cast<Argument>(V)) {
99 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
100 while ((isa<BitCastInst>(IP) &&
101 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
102 cast<BitCastInst>(IP)->getOperand(0) != A) ||
103 isa<DbgInfoIntrinsic>(IP))
105 return ReuseOrCreateCast(A, Ty, Op, IP);
108 // Cast the instruction immediately after the instruction.
109 Instruction *I = cast<Instruction>(V);
110 BasicBlock::iterator IP = I; ++IP;
111 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
112 IP = II->getNormalDest()->begin();
113 while (isa<PHINode>(IP) || isa<DbgInfoIntrinsic>(IP)) ++IP;
114 return ReuseOrCreateCast(I, Ty, Op, IP);
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,
120 Value *LHS, Value *RHS) {
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 = Builder.GetInsertBlock()->begin();
129 // Scanning starts from the last instruction before the insertion point.
130 BasicBlock::iterator IP = Builder.GetInsertPoint();
131 if (IP != BlockBegin) {
133 for (; ScanLimit; --IP, --ScanLimit) {
134 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
136 if (isa<DbgInfoIntrinsic>(IP))
138 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
139 IP->getOperand(1) == RHS)
141 if (IP == BlockBegin) break;
145 // Save the original insertion point so we can restore it when we're done.
146 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
147 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
149 // Move the insertion point out of as many loops as we can.
150 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
151 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
152 BasicBlock *Preheader = L->getLoopPreheader();
153 if (!Preheader) break;
155 // Ok, move up a level.
156 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
159 // If we haven't found this binop, insert it.
160 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
161 rememberInstruction(BO);
163 // Restore the original insert point.
165 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
170 /// FactorOutConstant - Test if S is divisible by Factor, using signed
171 /// division. If so, update S with Factor divided out and return true.
172 /// S need not be evenly divisible if a reasonable remainder can be
174 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
175 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
176 /// check to see if the divide was folded.
177 static bool FactorOutConstant(const SCEV *&S,
178 const SCEV *&Remainder,
181 const TargetData *TD) {
182 // Everything is divisible by one.
188 S = SE.getConstant(S->getType(), 1);
192 // For a Constant, check for a multiple of the given factor.
193 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
197 // Check for divisibility.
198 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
200 ConstantInt::get(SE.getContext(),
201 C->getValue()->getValue().sdiv(
202 FC->getValue()->getValue()));
203 // If the quotient is zero and the remainder is non-zero, reject
204 // the value at this scale. It will be considered for subsequent
207 const SCEV *Div = SE.getConstant(CI);
210 SE.getAddExpr(Remainder,
211 SE.getConstant(C->getValue()->getValue().srem(
212 FC->getValue()->getValue())));
218 // In a Mul, check if there is a constant operand which is a multiple
219 // of the given factor.
220 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
222 // With TargetData, the size is known. Check if there is a constant
223 // operand which is a multiple of the given factor. If so, we can
225 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
226 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
227 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
228 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
230 SE.getConstant(C->getValue()->getValue().sdiv(
231 FC->getValue()->getValue()));
232 S = SE.getMulExpr(NewMulOps);
236 // Without TargetData, check if Factor can be factored out of any of the
237 // Mul's operands. If so, we can just remove it.
238 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
239 const SCEV *SOp = M->getOperand(i);
240 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
241 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
242 Remainder->isZero()) {
243 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
245 S = SE.getMulExpr(NewMulOps);
252 // In an AddRec, check if both start and step are divisible.
253 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
254 const SCEV *Step = A->getStepRecurrence(SE);
255 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
256 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
258 if (!StepRem->isZero())
260 const SCEV *Start = A->getStart();
261 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
263 S = SE.getAddRecExpr(Start, Step, A->getLoop());
270 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
271 /// is the number of SCEVAddRecExprs present, which are kept at the end of
274 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
276 ScalarEvolution &SE) {
277 unsigned NumAddRecs = 0;
278 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
280 // Group Ops into non-addrecs and addrecs.
281 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
282 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
283 // Let ScalarEvolution sort and simplify the non-addrecs list.
284 const SCEV *Sum = NoAddRecs.empty() ?
285 SE.getConstant(Ty, 0) :
286 SE.getAddExpr(NoAddRecs);
287 // If it returned an add, use the operands. Otherwise it simplified
288 // the sum into a single value, so just use that.
290 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
291 Ops.append(Add->op_begin(), Add->op_end());
292 else if (!Sum->isZero())
294 // Then append the addrecs.
295 Ops.append(AddRecs.begin(), AddRecs.end());
298 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
299 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
300 /// This helps expose more opportunities for folding parts of the expressions
301 /// into GEP indices.
303 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
305 ScalarEvolution &SE) {
307 SmallVector<const SCEV *, 8> AddRecs;
308 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
309 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
310 const SCEV *Start = A->getStart();
311 if (Start->isZero()) break;
312 const SCEV *Zero = SE.getConstant(Ty, 0);
313 AddRecs.push_back(SE.getAddRecExpr(Zero,
314 A->getStepRecurrence(SE),
316 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
318 Ops.append(Add->op_begin(), Add->op_end());
319 e += Add->getNumOperands();
324 if (!AddRecs.empty()) {
325 // Add the addrecs onto the end of the list.
326 Ops.append(AddRecs.begin(), AddRecs.end());
327 // Resort the operand list, moving any constants to the front.
328 SimplifyAddOperands(Ops, Ty, SE);
332 /// expandAddToGEP - Expand an addition expression with a pointer type into
333 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
334 /// BasicAliasAnalysis and other passes analyze the result. See the rules
335 /// for getelementptr vs. inttoptr in
336 /// http://llvm.org/docs/LangRef.html#pointeraliasing
339 /// Design note: The correctness of using getelementptr here depends on
340 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
341 /// they may introduce pointer arithmetic which may not be safely converted
342 /// into getelementptr.
344 /// Design note: It might seem desirable for this function to be more
345 /// loop-aware. If some of the indices are loop-invariant while others
346 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
347 /// loop-invariant portions of the overall computation outside the loop.
348 /// However, there are a few reasons this is not done here. Hoisting simple
349 /// arithmetic is a low-level optimization that often isn't very
350 /// important until late in the optimization process. In fact, passes
351 /// like InstructionCombining will combine GEPs, even if it means
352 /// pushing loop-invariant computation down into loops, so even if the
353 /// GEPs were split here, the work would quickly be undone. The
354 /// LoopStrengthReduction pass, which is usually run quite late (and
355 /// after the last InstructionCombining pass), takes care of hoisting
356 /// loop-invariant portions of expressions, after considering what
357 /// can be folded using target addressing modes.
359 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
360 const SCEV *const *op_end,
361 const PointerType *PTy,
364 const Type *ElTy = PTy->getElementType();
365 SmallVector<Value *, 4> GepIndices;
366 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
367 bool AnyNonZeroIndices = false;
369 // Split AddRecs up into parts as either of the parts may be usable
370 // without the other.
371 SplitAddRecs(Ops, Ty, SE);
373 // Descend down the pointer's type and attempt to convert the other
374 // operands into GEP indices, at each level. The first index in a GEP
375 // indexes into the array implied by the pointer operand; the rest of
376 // the indices index into the element or field type selected by the
379 // If the scale size is not 0, attempt to factor out a scale for
381 SmallVector<const SCEV *, 8> ScaledOps;
382 if (ElTy->isSized()) {
383 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
384 if (!ElSize->isZero()) {
385 SmallVector<const SCEV *, 8> NewOps;
386 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
387 const SCEV *Op = Ops[i];
388 const SCEV *Remainder = SE.getConstant(Ty, 0);
389 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
390 // Op now has ElSize factored out.
391 ScaledOps.push_back(Op);
392 if (!Remainder->isZero())
393 NewOps.push_back(Remainder);
394 AnyNonZeroIndices = true;
396 // The operand was not divisible, so add it to the list of operands
397 // we'll scan next iteration.
398 NewOps.push_back(Ops[i]);
401 // If we made any changes, update Ops.
402 if (!ScaledOps.empty()) {
404 SimplifyAddOperands(Ops, Ty, SE);
409 // Record the scaled array index for this level of the type. If
410 // we didn't find any operands that could be factored, tentatively
411 // assume that element zero was selected (since the zero offset
412 // would obviously be folded away).
413 Value *Scaled = ScaledOps.empty() ?
414 Constant::getNullValue(Ty) :
415 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
416 GepIndices.push_back(Scaled);
418 // Collect struct field index operands.
419 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
420 bool FoundFieldNo = false;
421 // An empty struct has no fields.
422 if (STy->getNumElements() == 0) break;
424 // With TargetData, field offsets are known. See if a constant offset
425 // falls within any of the struct fields.
426 if (Ops.empty()) break;
427 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
428 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
429 const StructLayout &SL = *SE.TD->getStructLayout(STy);
430 uint64_t FullOffset = C->getValue()->getZExtValue();
431 if (FullOffset < SL.getSizeInBytes()) {
432 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
433 GepIndices.push_back(
434 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
435 ElTy = STy->getTypeAtIndex(ElIdx);
437 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
438 AnyNonZeroIndices = true;
443 // Without TargetData, just check for an offsetof expression of the
444 // appropriate struct type.
445 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
446 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
449 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
450 GepIndices.push_back(FieldNo);
452 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
453 Ops[i] = SE.getConstant(Ty, 0);
454 AnyNonZeroIndices = true;
460 // If no struct field offsets were found, tentatively assume that
461 // field zero was selected (since the zero offset would obviously
464 ElTy = STy->getTypeAtIndex(0u);
465 GepIndices.push_back(
466 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
470 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
471 ElTy = ATy->getElementType();
476 // If none of the operands were convertible to proper GEP indices, cast
477 // the base to i8* and do an ugly getelementptr with that. It's still
478 // better than ptrtoint+arithmetic+inttoptr at least.
479 if (!AnyNonZeroIndices) {
480 // Cast the base to i8*.
481 V = InsertNoopCastOfTo(V,
482 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
484 // Expand the operands for a plain byte offset.
485 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
487 // Fold a GEP with constant operands.
488 if (Constant *CLHS = dyn_cast<Constant>(V))
489 if (Constant *CRHS = dyn_cast<Constant>(Idx))
490 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
492 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
493 unsigned ScanLimit = 6;
494 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
495 // Scanning starts from the last instruction before the insertion point.
496 BasicBlock::iterator IP = Builder.GetInsertPoint();
497 if (IP != BlockBegin) {
499 for (; ScanLimit; --IP, --ScanLimit) {
500 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
502 if (isa<DbgInfoIntrinsic>(IP))
504 if (IP->getOpcode() == Instruction::GetElementPtr &&
505 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
507 if (IP == BlockBegin) break;
511 // Save the original insertion point so we can restore it when we're done.
512 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
513 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
515 // Move the insertion point out of as many loops as we can.
516 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
517 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
518 BasicBlock *Preheader = L->getLoopPreheader();
519 if (!Preheader) break;
521 // Ok, move up a level.
522 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
526 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
527 rememberInstruction(GEP);
529 // Restore the original insert point.
531 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
536 // Save the original insertion point so we can restore it when we're done.
537 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
538 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
540 // Move the insertion point out of as many loops as we can.
541 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
542 if (!L->isLoopInvariant(V)) break;
544 bool AnyIndexNotLoopInvariant = false;
545 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
546 E = GepIndices.end(); I != E; ++I)
547 if (!L->isLoopInvariant(*I)) {
548 AnyIndexNotLoopInvariant = true;
551 if (AnyIndexNotLoopInvariant)
554 BasicBlock *Preheader = L->getLoopPreheader();
555 if (!Preheader) break;
557 // Ok, move up a level.
558 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
561 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
562 // because ScalarEvolution may have changed the address arithmetic to
563 // compute a value which is beyond the end of the allocated object.
565 if (V->getType() != PTy)
566 Casted = InsertNoopCastOfTo(Casted, PTy);
567 Value *GEP = Builder.CreateGEP(Casted,
571 Ops.push_back(SE.getUnknown(GEP));
572 rememberInstruction(GEP);
574 // Restore the original insert point.
576 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
578 return expand(SE.getAddExpr(Ops));
581 /// isNonConstantNegative - Return true if the specified scev is negated, but
583 static bool isNonConstantNegative(const SCEV *F) {
584 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
585 if (!Mul) return false;
587 // If there is a constant factor, it will be first.
588 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
589 if (!SC) return false;
591 // Return true if the value is negative, this matches things like (-42 * V).
592 return SC->getValue()->getValue().isNegative();
595 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
596 /// SCEV expansion. If they are nested, this is the most nested. If they are
597 /// neighboring, pick the later.
598 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
602 if (A->contains(B)) return B;
603 if (B->contains(A)) return A;
604 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
605 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
606 return A; // Arbitrarily break the tie.
609 /// GetRelevantLoop - Get the most relevant loop associated with the given
610 /// expression, according to PickMostRelevantLoop.
611 static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
613 if (isa<SCEVConstant>(S))
615 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
616 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
617 return LI.getLoopFor(I->getParent());
620 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
622 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
624 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
626 L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
629 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
630 return GetRelevantLoop(C->getOperand(), LI, DT);
631 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
632 return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
633 GetRelevantLoop(D->getRHS(), LI, DT),
635 llvm_unreachable("Unexpected SCEV type!");
640 /// LoopCompare - Compare loops by PickMostRelevantLoop.
644 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
646 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
647 std::pair<const Loop *, const SCEV *> RHS) const {
648 // Compare loops with PickMostRelevantLoop.
649 if (LHS.first != RHS.first)
650 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
652 // If one operand is a non-constant negative and the other is not,
653 // put the non-constant negative on the right so that a sub can
654 // be used instead of a negate and add.
655 if (isNonConstantNegative(LHS.second)) {
656 if (!isNonConstantNegative(RHS.second))
658 } else if (isNonConstantNegative(RHS.second))
661 // Otherwise they are equivalent according to this comparison.
668 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
669 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
671 // Collect all the add operands in a loop, along with their associated loops.
672 // Iterate in reverse so that constants are emitted last, all else equal, and
673 // so that pointer operands are inserted first, which the code below relies on
674 // to form more involved GEPs.
675 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
676 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
677 E(S->op_begin()); I != E; ++I)
678 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
681 // Sort by loop. Use a stable sort so that constants follow non-constants and
682 // pointer operands precede non-pointer operands.
683 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
685 // Emit instructions to add all the operands. Hoist as much as possible
686 // out of loops, and form meaningful getelementptrs where possible.
688 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
689 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
690 const Loop *CurLoop = I->first;
691 const SCEV *Op = I->second;
693 // This is the first operand. Just expand it.
696 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
697 // The running sum expression is a pointer. Try to form a getelementptr
698 // at this level with that as the base.
699 SmallVector<const SCEV *, 4> NewOps;
700 for (; I != E && I->first == CurLoop; ++I)
701 NewOps.push_back(I->second);
702 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
703 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
704 // The running sum is an integer, and there's a pointer at this level.
705 // Try to form a getelementptr. If the running sum is instructions,
706 // use a SCEVUnknown to avoid re-analyzing them.
707 SmallVector<const SCEV *, 4> NewOps;
708 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
710 for (++I; I != E && I->first == CurLoop; ++I)
711 NewOps.push_back(I->second);
712 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
713 } else if (isNonConstantNegative(Op)) {
714 // Instead of doing a negate and add, just do a subtract.
715 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
716 Sum = InsertNoopCastOfTo(Sum, Ty);
717 Sum = InsertBinop(Instruction::Sub, Sum, W);
721 Value *W = expandCodeFor(Op, Ty);
722 Sum = InsertNoopCastOfTo(Sum, Ty);
723 // Canonicalize a constant to the RHS.
724 if (isa<Constant>(Sum)) std::swap(Sum, W);
725 Sum = InsertBinop(Instruction::Add, Sum, W);
733 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
734 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
736 // Collect all the mul operands in a loop, along with their associated loops.
737 // Iterate in reverse so that constants are emitted last, all else equal.
738 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
739 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
740 E(S->op_begin()); I != E; ++I)
741 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
744 // Sort by loop. Use a stable sort so that constants follow non-constants.
745 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
747 // Emit instructions to mul all the operands. Hoist as much as possible
750 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
751 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
752 const SCEV *Op = I->second;
754 // This is the first operand. Just expand it.
757 } else if (Op->isAllOnesValue()) {
758 // Instead of doing a multiply by negative one, just do a negate.
759 Prod = InsertNoopCastOfTo(Prod, Ty);
760 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
764 Value *W = expandCodeFor(Op, Ty);
765 Prod = InsertNoopCastOfTo(Prod, Ty);
766 // Canonicalize a constant to the RHS.
767 if (isa<Constant>(Prod)) std::swap(Prod, W);
768 Prod = InsertBinop(Instruction::Mul, Prod, W);
776 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
777 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
779 Value *LHS = expandCodeFor(S->getLHS(), Ty);
780 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
781 const APInt &RHS = SC->getValue()->getValue();
782 if (RHS.isPowerOf2())
783 return InsertBinop(Instruction::LShr, LHS,
784 ConstantInt::get(Ty, RHS.logBase2()));
787 Value *RHS = expandCodeFor(S->getRHS(), Ty);
788 return InsertBinop(Instruction::UDiv, LHS, RHS);
791 /// Move parts of Base into Rest to leave Base with the minimal
792 /// expression that provides a pointer operand suitable for a
794 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
795 ScalarEvolution &SE) {
796 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
797 Base = A->getStart();
798 Rest = SE.getAddExpr(Rest,
799 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
800 A->getStepRecurrence(SE),
803 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
804 Base = A->getOperand(A->getNumOperands()-1);
805 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
806 NewAddOps.back() = Rest;
807 Rest = SE.getAddExpr(NewAddOps);
808 ExposePointerBase(Base, Rest, SE);
812 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
813 /// the base addrec, which is the addrec without any non-loop-dominating
814 /// values, and return the PHI.
816 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
818 const Type *ExpandTy,
820 // Reuse a previously-inserted PHI, if present.
821 for (BasicBlock::iterator I = L->getHeader()->begin();
822 PHINode *PN = dyn_cast<PHINode>(I); ++I)
823 if (SE.isSCEVable(PN->getType()) &&
824 (SE.getEffectiveSCEVType(PN->getType()) ==
825 SE.getEffectiveSCEVType(Normalized->getType())) &&
826 SE.getSCEV(PN) == Normalized)
827 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
829 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
831 // Determine if this is a well-behaved chain of instructions leading
832 // back to the PHI. It probably will be, if we're scanning an inner
833 // loop already visited by LSR for example, but it wouldn't have
836 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
840 // If any of the operands don't dominate the insert position, bail.
841 // Addrec operands are always loop-invariant, so this can only happen
842 // if there are instructions which haven't been hoisted.
843 for (User::op_iterator OI = IncV->op_begin()+1,
844 OE = IncV->op_end(); OI != OE; ++OI)
845 if (Instruction *OInst = dyn_cast<Instruction>(OI))
846 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
852 // Advance to the next instruction.
853 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
856 if (IncV->mayHaveSideEffects()) {
860 } while (IncV != PN);
863 // Ok, the add recurrence looks usable.
864 // Remember this PHI, even in post-inc mode.
865 InsertedValues.insert(PN);
866 // Remember the increment.
867 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
868 rememberInstruction(IncV);
869 if (L == IVIncInsertLoop)
871 if (SE.DT->dominates(IncV, IVIncInsertPos))
873 // Make sure the increment is where we want it. But don't move it
874 // down past a potential existing post-inc user.
875 IncV->moveBefore(IVIncInsertPos);
876 IVIncInsertPos = IncV;
877 IncV = cast<Instruction>(IncV->getOperand(0));
878 } while (IncV != PN);
883 // Save the original insertion point so we can restore it when we're done.
884 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
885 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
887 // Expand code for the start value.
888 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
889 L->getHeader()->begin());
891 // Expand code for the step value. Insert instructions right before the
892 // terminator corresponding to the back-edge. Do this before creating the PHI
893 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
894 // negative, insert a sub instead of an add for the increment (unless it's a
895 // constant, because subtracts of constants are canonicalized to adds).
896 const SCEV *Step = Normalized->getStepRecurrence(SE);
897 bool isPointer = ExpandTy->isPointerTy();
898 bool isNegative = !isPointer && isNonConstantNegative(Step);
900 Step = SE.getNegativeSCEV(Step);
901 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
904 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
905 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
906 rememberInstruction(PN);
908 // Create the step instructions and populate the PHI.
909 BasicBlock *Header = L->getHeader();
910 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
912 BasicBlock *Pred = *HPI;
914 // Add a start value.
915 if (!L->contains(Pred)) {
916 PN->addIncoming(StartV, Pred);
920 // Create a step value and add it to the PHI. If IVIncInsertLoop is
921 // non-null and equal to the addrec's loop, insert the instructions
922 // at IVIncInsertPos.
923 Instruction *InsertPos = L == IVIncInsertLoop ?
924 IVIncInsertPos : Pred->getTerminator();
925 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
927 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
929 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
930 // If the step isn't constant, don't use an implicitly scaled GEP, because
931 // that would require a multiply inside the loop.
932 if (!isa<ConstantInt>(StepV))
933 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
934 GEPPtrTy->getAddressSpace());
935 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
936 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
937 if (IncV->getType() != PN->getType()) {
938 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
939 rememberInstruction(IncV);
943 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
944 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
945 rememberInstruction(IncV);
947 PN->addIncoming(IncV, Pred);
950 // Restore the original insert point.
952 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
954 // Remember this PHI, even in post-inc mode.
955 InsertedValues.insert(PN);
960 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
961 const Type *STy = S->getType();
962 const Type *IntTy = SE.getEffectiveSCEVType(STy);
963 const Loop *L = S->getLoop();
965 // Determine a normalized form of this expression, which is the expression
966 // before any post-inc adjustment is made.
967 const SCEVAddRecExpr *Normalized = S;
968 if (PostIncLoops.count(L)) {
969 PostIncLoopSet Loops;
972 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
976 // Strip off any non-loop-dominating component from the addrec start.
977 const SCEV *Start = Normalized->getStart();
978 const SCEV *PostLoopOffset = 0;
979 if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
980 PostLoopOffset = Start;
981 Start = SE.getConstant(Normalized->getType(), 0);
983 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
984 Normalized->getStepRecurrence(SE),
985 Normalized->getLoop()));
988 // Strip off any non-loop-dominating component from the addrec step.
989 const SCEV *Step = Normalized->getStepRecurrence(SE);
990 const SCEV *PostLoopScale = 0;
991 if (!Step->dominates(L->getHeader(), SE.DT)) {
992 PostLoopScale = Step;
993 Step = SE.getConstant(Normalized->getType(), 1);
995 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
996 Normalized->getLoop()));
999 // Expand the core addrec. If we need post-loop scaling, force it to
1000 // expand to an integer type to avoid the need for additional casting.
1001 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1002 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1004 // Accommodate post-inc mode, if necessary.
1006 if (!PostIncLoops.count(L))
1009 // In PostInc mode, use the post-incremented value.
1010 BasicBlock *LatchBlock = L->getLoopLatch();
1011 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1012 Result = PN->getIncomingValueForBlock(LatchBlock);
1015 // Re-apply any non-loop-dominating scale.
1016 if (PostLoopScale) {
1017 Result = InsertNoopCastOfTo(Result, IntTy);
1018 Result = Builder.CreateMul(Result,
1019 expandCodeFor(PostLoopScale, IntTy));
1020 rememberInstruction(Result);
1023 // Re-apply any non-loop-dominating offset.
1024 if (PostLoopOffset) {
1025 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1026 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1027 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1029 Result = InsertNoopCastOfTo(Result, IntTy);
1030 Result = Builder.CreateAdd(Result,
1031 expandCodeFor(PostLoopOffset, IntTy));
1032 rememberInstruction(Result);
1039 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1040 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1042 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1043 const Loop *L = S->getLoop();
1045 // First check for an existing canonical IV in a suitable type.
1046 PHINode *CanonicalIV = 0;
1047 if (PHINode *PN = L->getCanonicalInductionVariable())
1048 if (SE.isSCEVable(PN->getType()) &&
1049 SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
1050 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1053 // Rewrite an AddRec in terms of the canonical induction variable, if
1054 // its type is more narrow.
1056 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1057 SE.getTypeSizeInBits(Ty)) {
1058 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1059 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1060 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1061 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
1062 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1063 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1064 BasicBlock::iterator NewInsertPt =
1065 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1066 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt))
1068 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1070 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1074 // {X,+,F} --> X + {0,+,F}
1075 if (!S->getStart()->isZero()) {
1076 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1077 NewOps[0] = SE.getConstant(Ty, 0);
1078 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
1080 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1081 // comments on expandAddToGEP for details.
1082 const SCEV *Base = S->getStart();
1083 const SCEV *RestArray[1] = { Rest };
1084 // Dig into the expression to find the pointer base for a GEP.
1085 ExposePointerBase(Base, RestArray[0], SE);
1086 // If we found a pointer, expand the AddRec with a GEP.
1087 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1088 // Make sure the Base isn't something exotic, such as a multiplied
1089 // or divided pointer value. In those cases, the result type isn't
1090 // actually a pointer type.
1091 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1092 Value *StartV = expand(Base);
1093 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1094 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1098 // Just do a normal add. Pre-expand the operands to suppress folding.
1099 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1100 SE.getUnknown(expand(Rest))));
1103 // {0,+,1} --> Insert a canonical induction variable into the loop!
1104 if (S->isAffine() && S->getOperand(1)->isOne()) {
1105 // If there's a canonical IV, just use it.
1107 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1108 "IVs with types different from the canonical IV should "
1109 "already have been handled!");
1113 // Create and insert the PHI node for the induction variable in the
1115 BasicBlock *Header = L->getHeader();
1116 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
1117 rememberInstruction(PN);
1119 Constant *One = ConstantInt::get(Ty, 1);
1120 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
1121 HPI != HPE; ++HPI) {
1122 BasicBlock *HP = *HPI;
1123 if (L->contains(HP)) {
1124 // Insert a unit add instruction right before the terminator
1125 // corresponding to the back-edge.
1126 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
1127 HP->getTerminator());
1128 rememberInstruction(Add);
1129 PN->addIncoming(Add, HP);
1131 PN->addIncoming(Constant::getNullValue(Ty), HP);
1136 // {0,+,F} --> {0,+,1} * F
1137 // Get the canonical induction variable I for this loop.
1138 Value *I = CanonicalIV ?
1140 getOrInsertCanonicalInductionVariable(L, Ty);
1142 // If this is a simple linear addrec, emit it now as a special case.
1143 if (S->isAffine()) // {0,+,F} --> i*F
1145 expand(SE.getTruncateOrNoop(
1146 SE.getMulExpr(SE.getUnknown(I),
1147 SE.getNoopOrAnyExtend(S->getOperand(1),
1151 // If this is a chain of recurrences, turn it into a closed form, using the
1152 // folders, then expandCodeFor the closed form. This allows the folders to
1153 // simplify the expression without having to build a bunch of special code
1154 // into this folder.
1155 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
1157 // Promote S up to the canonical IV type, if the cast is foldable.
1158 const SCEV *NewS = S;
1159 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
1160 if (isa<SCEVAddRecExpr>(Ext))
1163 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1164 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1166 // Truncate the result down to the original type, if needed.
1167 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1171 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1172 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1173 Value *V = expandCodeFor(S->getOperand(),
1174 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1175 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
1176 rememberInstruction(I);
1180 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1181 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1182 Value *V = expandCodeFor(S->getOperand(),
1183 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1184 Value *I = Builder.CreateZExt(V, Ty, "tmp");
1185 rememberInstruction(I);
1189 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1190 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1191 Value *V = expandCodeFor(S->getOperand(),
1192 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1193 Value *I = Builder.CreateSExt(V, Ty, "tmp");
1194 rememberInstruction(I);
1198 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1199 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1200 const Type *Ty = LHS->getType();
1201 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1202 // In the case of mixed integer and pointer types, do the
1203 // rest of the comparisons as integer.
1204 if (S->getOperand(i)->getType() != Ty) {
1205 Ty = SE.getEffectiveSCEVType(Ty);
1206 LHS = InsertNoopCastOfTo(LHS, Ty);
1208 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1209 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
1210 rememberInstruction(ICmp);
1211 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1212 rememberInstruction(Sel);
1215 // In the case of mixed integer and pointer types, cast the
1216 // final result back to the pointer type.
1217 if (LHS->getType() != S->getType())
1218 LHS = InsertNoopCastOfTo(LHS, S->getType());
1222 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1223 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1224 const Type *Ty = LHS->getType();
1225 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1226 // In the case of mixed integer and pointer types, do the
1227 // rest of the comparisons as integer.
1228 if (S->getOperand(i)->getType() != Ty) {
1229 Ty = SE.getEffectiveSCEVType(Ty);
1230 LHS = InsertNoopCastOfTo(LHS, Ty);
1232 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1233 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
1234 rememberInstruction(ICmp);
1235 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1236 rememberInstruction(Sel);
1239 // In the case of mixed integer and pointer types, cast the
1240 // final result back to the pointer type.
1241 if (LHS->getType() != S->getType())
1242 LHS = InsertNoopCastOfTo(LHS, S->getType());
1246 Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
1248 BasicBlock::iterator IP = I;
1249 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1251 Builder.SetInsertPoint(IP->getParent(), IP);
1252 return expandCodeFor(SH, Ty);
1255 Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
1256 // Expand the code for this SCEV.
1257 Value *V = expand(SH);
1259 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1260 "non-trivial casts should be done with the SCEVs directly!");
1261 V = InsertNoopCastOfTo(V, Ty);
1266 Value *SCEVExpander::expand(const SCEV *S) {
1267 // Compute an insertion point for this SCEV object. Hoist the instructions
1268 // as far out in the loop nest as possible.
1269 Instruction *InsertPt = Builder.GetInsertPoint();
1270 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
1271 L = L->getParentLoop())
1272 if (S->isLoopInvariant(L)) {
1274 if (BasicBlock *Preheader = L->getLoopPreheader())
1275 InsertPt = Preheader->getTerminator();
1277 // If the SCEV is computable at this level, insert it into the header
1278 // after the PHIs (and after any other instructions that we've inserted
1279 // there) so that it is guaranteed to dominate any user inside the loop.
1280 if (L && S->hasComputableLoopEvolution(L) && !PostIncLoops.count(L))
1281 InsertPt = L->getHeader()->getFirstNonPHI();
1282 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
1283 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1287 // Check to see if we already expanded this here.
1288 std::map<std::pair<const SCEV *, Instruction *>,
1289 AssertingVH<Value> >::iterator I =
1290 InsertedExpressions.find(std::make_pair(S, InsertPt));
1291 if (I != InsertedExpressions.end())
1294 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1295 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1296 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1298 // Expand the expression into instructions.
1299 Value *V = visit(S);
1301 // Remember the expanded value for this SCEV at this location.
1302 if (PostIncLoops.empty())
1303 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1305 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1309 void SCEVExpander::rememberInstruction(Value *I) {
1310 if (!PostIncLoops.empty())
1311 InsertedPostIncValues.insert(I);
1313 InsertedValues.insert(I);
1315 // If we just claimed an existing instruction and that instruction had
1316 // been the insert point, adjust the insert point forward so that
1317 // subsequently inserted code will be dominated.
1318 if (Builder.GetInsertPoint() == I) {
1319 BasicBlock::iterator It = cast<Instruction>(I);
1320 do { ++It; } while (isInsertedInstruction(It) ||
1321 isa<DbgInfoIntrinsic>(It));
1322 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1326 void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
1327 // If we acquired more instructions since the old insert point was saved,
1328 // advance past them.
1329 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
1331 Builder.SetInsertPoint(BB, I);
1334 /// getOrInsertCanonicalInductionVariable - This method returns the
1335 /// canonical induction variable of the specified type for the specified
1336 /// loop (inserting one if there is none). A canonical induction variable
1337 /// starts at zero and steps by one on each iteration.
1339 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1341 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1342 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1343 SE.getConstant(Ty, 1), L);
1344 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1345 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1346 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
1348 restoreInsertPoint(SaveInsertBB, SaveInsertPt);