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 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
25 /// which must be possible with a noop cast, doing what we can to share
27 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, const Type *Ty) {
28 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
29 assert((Op == Instruction::BitCast ||
30 Op == Instruction::PtrToInt ||
31 Op == Instruction::IntToPtr) &&
32 "InsertNoopCastOfTo cannot perform non-noop casts!");
33 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
34 "InsertNoopCastOfTo cannot change sizes!");
36 // Short-circuit unnecessary bitcasts.
37 if (Op == Instruction::BitCast && V->getType() == Ty)
40 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
41 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
42 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
43 if (CastInst *CI = dyn_cast<CastInst>(V))
44 if ((CI->getOpcode() == Instruction::PtrToInt ||
45 CI->getOpcode() == Instruction::IntToPtr) &&
46 SE.getTypeSizeInBits(CI->getType()) ==
47 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
48 return CI->getOperand(0);
49 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
50 if ((CE->getOpcode() == Instruction::PtrToInt ||
51 CE->getOpcode() == Instruction::IntToPtr) &&
52 SE.getTypeSizeInBits(CE->getType()) ==
53 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
54 return CE->getOperand(0);
57 if (Constant *C = dyn_cast<Constant>(V))
58 return ConstantExpr::getCast(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 rememberInstruction(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 after the user.
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);
108 rememberInstruction(NewCI);
111 rememberInstruction(CI);
115 BasicBlock::iterator IP = I; ++IP;
116 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
117 IP = II->getNormalDest()->begin();
118 while (isa<PHINode>(IP)) ++IP;
119 Instruction *CI = CastInst::Create(Op, V, Ty, V->getName(), IP);
120 rememberInstruction(CI);
124 /// InsertBinop - Insert the specified binary operator, doing a small amount
125 /// of work to avoid inserting an obviously redundant operation.
126 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
127 Value *LHS, Value *RHS) {
128 // Fold a binop with constant operands.
129 if (Constant *CLHS = dyn_cast<Constant>(LHS))
130 if (Constant *CRHS = dyn_cast<Constant>(RHS))
131 return ConstantExpr::get(Opcode, CLHS, CRHS);
133 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
134 unsigned ScanLimit = 6;
135 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
136 // Scanning starts from the last instruction before the insertion point.
137 BasicBlock::iterator IP = Builder.GetInsertPoint();
138 if (IP != BlockBegin) {
140 for (; ScanLimit; --IP, --ScanLimit) {
141 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
143 if (isa<DbgInfoIntrinsic>(IP))
145 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
146 IP->getOperand(1) == RHS)
148 if (IP == BlockBegin) break;
152 // Save the original insertion point so we can restore it when we're done.
153 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
154 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
156 // Move the insertion point out of as many loops as we can.
157 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
158 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
159 BasicBlock *Preheader = L->getLoopPreheader();
160 if (!Preheader) break;
162 // Ok, move up a level.
163 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
166 // If we haven't found this binop, insert it.
167 Value *BO = Builder.CreateBinOp(Opcode, LHS, RHS, "tmp");
168 rememberInstruction(BO);
170 // Restore the original insert point.
172 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
177 /// FactorOutConstant - Test if S is divisible by Factor, using signed
178 /// division. If so, update S with Factor divided out and return true.
179 /// S need not be evenly divisible if a reasonable remainder can be
181 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
182 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
183 /// check to see if the divide was folded.
184 static bool FactorOutConstant(const SCEV *&S,
185 const SCEV *&Remainder,
188 const TargetData *TD) {
189 // Everything is divisible by one.
195 S = SE.getIntegerSCEV(1, S->getType());
199 // For a Constant, check for a multiple of the given factor.
200 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
204 // Check for divisibility.
205 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
207 ConstantInt::get(SE.getContext(),
208 C->getValue()->getValue().sdiv(
209 FC->getValue()->getValue()));
210 // If the quotient is zero and the remainder is non-zero, reject
211 // the value at this scale. It will be considered for subsequent
214 const SCEV *Div = SE.getConstant(CI);
217 SE.getAddExpr(Remainder,
218 SE.getConstant(C->getValue()->getValue().srem(
219 FC->getValue()->getValue())));
225 // In a Mul, check if there is a constant operand which is a multiple
226 // of the given factor.
227 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
229 // With TargetData, the size is known. Check if there is a constant
230 // operand which is a multiple of the given factor. If so, we can
232 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
233 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
234 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
235 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
237 SE.getConstant(C->getValue()->getValue().sdiv(
238 FC->getValue()->getValue()));
239 S = SE.getMulExpr(NewMulOps);
243 // Without TargetData, check if Factor can be factored out of any of the
244 // Mul's operands. If so, we can just remove it.
245 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
246 const SCEV *SOp = M->getOperand(i);
247 const SCEV *Remainder = SE.getIntegerSCEV(0, SOp->getType());
248 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
249 Remainder->isZero()) {
250 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
252 S = SE.getMulExpr(NewMulOps);
259 // In an AddRec, check if both start and step are divisible.
260 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
261 const SCEV *Step = A->getStepRecurrence(SE);
262 const SCEV *StepRem = SE.getIntegerSCEV(0, Step->getType());
263 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
265 if (!StepRem->isZero())
267 const SCEV *Start = A->getStart();
268 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
270 S = SE.getAddRecExpr(Start, Step, A->getLoop());
277 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
278 /// is the number of SCEVAddRecExprs present, which are kept at the end of
281 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
283 ScalarEvolution &SE) {
284 unsigned NumAddRecs = 0;
285 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
287 // Group Ops into non-addrecs and addrecs.
288 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
289 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
290 // Let ScalarEvolution sort and simplify the non-addrecs list.
291 const SCEV *Sum = NoAddRecs.empty() ?
292 SE.getIntegerSCEV(0, Ty) :
293 SE.getAddExpr(NoAddRecs);
294 // If it returned an add, use the operands. Otherwise it simplified
295 // the sum into a single value, so just use that.
297 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
298 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
299 else if (!Sum->isZero())
301 // Then append the addrecs.
302 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
305 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
306 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
307 /// This helps expose more opportunities for folding parts of the expressions
308 /// into GEP indices.
310 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
312 ScalarEvolution &SE) {
314 SmallVector<const SCEV *, 8> AddRecs;
315 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
316 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
317 const SCEV *Start = A->getStart();
318 if (Start->isZero()) break;
319 const SCEV *Zero = SE.getIntegerSCEV(0, Ty);
320 AddRecs.push_back(SE.getAddRecExpr(Zero,
321 A->getStepRecurrence(SE),
323 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
325 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
326 e += Add->getNumOperands();
331 if (!AddRecs.empty()) {
332 // Add the addrecs onto the end of the list.
333 Ops.insert(Ops.end(), AddRecs.begin(), AddRecs.end());
334 // Resort the operand list, moving any constants to the front.
335 SimplifyAddOperands(Ops, Ty, SE);
339 /// expandAddToGEP - Expand an addition expression with a pointer type into
340 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
341 /// BasicAliasAnalysis and other passes analyze the result. See the rules
342 /// for getelementptr vs. inttoptr in
343 /// http://llvm.org/docs/LangRef.html#pointeraliasing
346 /// Design note: The correctness of using getelementptr here depends on
347 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
348 /// they may introduce pointer arithmetic which may not be safely converted
349 /// into getelementptr.
351 /// Design note: It might seem desirable for this function to be more
352 /// loop-aware. If some of the indices are loop-invariant while others
353 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
354 /// loop-invariant portions of the overall computation outside the loop.
355 /// However, there are a few reasons this is not done here. Hoisting simple
356 /// arithmetic is a low-level optimization that often isn't very
357 /// important until late in the optimization process. In fact, passes
358 /// like InstructionCombining will combine GEPs, even if it means
359 /// pushing loop-invariant computation down into loops, so even if the
360 /// GEPs were split here, the work would quickly be undone. The
361 /// LoopStrengthReduction pass, which is usually run quite late (and
362 /// after the last InstructionCombining pass), takes care of hoisting
363 /// loop-invariant portions of expressions, after considering what
364 /// can be folded using target addressing modes.
366 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
367 const SCEV *const *op_end,
368 const PointerType *PTy,
371 const Type *ElTy = PTy->getElementType();
372 SmallVector<Value *, 4> GepIndices;
373 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
374 bool AnyNonZeroIndices = false;
376 // Split AddRecs up into parts as either of the parts may be usable
377 // without the other.
378 SplitAddRecs(Ops, Ty, SE);
380 // Descend down the pointer's type and attempt to convert the other
381 // operands into GEP indices, at each level. The first index in a GEP
382 // indexes into the array implied by the pointer operand; the rest of
383 // the indices index into the element or field type selected by the
386 // If the scale size is not 0, attempt to factor out a scale for
388 SmallVector<const SCEV *, 8> ScaledOps;
389 if (ElTy->isSized()) {
390 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
391 if (!ElSize->isZero()) {
392 SmallVector<const SCEV *, 8> NewOps;
393 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
394 const SCEV *Op = Ops[i];
395 const SCEV *Remainder = SE.getIntegerSCEV(0, Ty);
396 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
397 // Op now has ElSize factored out.
398 ScaledOps.push_back(Op);
399 if (!Remainder->isZero())
400 NewOps.push_back(Remainder);
401 AnyNonZeroIndices = true;
403 // The operand was not divisible, so add it to the list of operands
404 // we'll scan next iteration.
405 NewOps.push_back(Ops[i]);
408 // If we made any changes, update Ops.
409 if (!ScaledOps.empty()) {
411 SimplifyAddOperands(Ops, Ty, SE);
416 // Record the scaled array index for this level of the type. If
417 // we didn't find any operands that could be factored, tentatively
418 // assume that element zero was selected (since the zero offset
419 // would obviously be folded away).
420 Value *Scaled = ScaledOps.empty() ?
421 Constant::getNullValue(Ty) :
422 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
423 GepIndices.push_back(Scaled);
425 // Collect struct field index operands.
426 while (const StructType *STy = dyn_cast<StructType>(ElTy)) {
427 bool FoundFieldNo = false;
428 // An empty struct has no fields.
429 if (STy->getNumElements() == 0) break;
431 // With TargetData, field offsets are known. See if a constant offset
432 // falls within any of the struct fields.
433 if (Ops.empty()) break;
434 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
435 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
436 const StructLayout &SL = *SE.TD->getStructLayout(STy);
437 uint64_t FullOffset = C->getValue()->getZExtValue();
438 if (FullOffset < SL.getSizeInBytes()) {
439 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
440 GepIndices.push_back(
441 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
442 ElTy = STy->getTypeAtIndex(ElIdx);
444 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
445 AnyNonZeroIndices = true;
450 // Without TargetData, just check for an offsetof expression of the
451 // appropriate struct type.
452 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
453 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
456 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
457 GepIndices.push_back(FieldNo);
459 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
460 Ops[i] = SE.getConstant(Ty, 0);
461 AnyNonZeroIndices = true;
467 // If no struct field offsets were found, tentatively assume that
468 // field zero was selected (since the zero offset would obviously
471 ElTy = STy->getTypeAtIndex(0u);
472 GepIndices.push_back(
473 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
477 if (const ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
478 ElTy = ATy->getElementType();
483 // If none of the operands were convertible to proper GEP indices, cast
484 // the base to i8* and do an ugly getelementptr with that. It's still
485 // better than ptrtoint+arithmetic+inttoptr at least.
486 if (!AnyNonZeroIndices) {
487 // Cast the base to i8*.
488 V = InsertNoopCastOfTo(V,
489 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
491 // Expand the operands for a plain byte offset.
492 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
494 // Fold a GEP with constant operands.
495 if (Constant *CLHS = dyn_cast<Constant>(V))
496 if (Constant *CRHS = dyn_cast<Constant>(Idx))
497 return ConstantExpr::getGetElementPtr(CLHS, &CRHS, 1);
499 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
500 unsigned ScanLimit = 6;
501 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
502 // Scanning starts from the last instruction before the insertion point.
503 BasicBlock::iterator IP = Builder.GetInsertPoint();
504 if (IP != BlockBegin) {
506 for (; ScanLimit; --IP, --ScanLimit) {
507 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
509 if (isa<DbgInfoIntrinsic>(IP))
511 if (IP->getOpcode() == Instruction::GetElementPtr &&
512 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
514 if (IP == BlockBegin) break;
518 // Save the original insertion point so we can restore it when we're done.
519 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
520 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
522 // Move the insertion point out of as many loops as we can.
523 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
524 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
525 BasicBlock *Preheader = L->getLoopPreheader();
526 if (!Preheader) break;
528 // Ok, move up a level.
529 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
533 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
534 rememberInstruction(GEP);
536 // Restore the original insert point.
538 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
543 // Save the original insertion point so we can restore it when we're done.
544 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
545 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
547 // Move the insertion point out of as many loops as we can.
548 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
549 if (!L->isLoopInvariant(V)) break;
551 bool AnyIndexNotLoopInvariant = false;
552 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
553 E = GepIndices.end(); I != E; ++I)
554 if (!L->isLoopInvariant(*I)) {
555 AnyIndexNotLoopInvariant = true;
558 if (AnyIndexNotLoopInvariant)
561 BasicBlock *Preheader = L->getLoopPreheader();
562 if (!Preheader) break;
564 // Ok, move up a level.
565 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
568 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
569 // because ScalarEvolution may have changed the address arithmetic to
570 // compute a value which is beyond the end of the allocated object.
572 if (V->getType() != PTy)
573 Casted = InsertNoopCastOfTo(Casted, PTy);
574 Value *GEP = Builder.CreateGEP(Casted,
578 Ops.push_back(SE.getUnknown(GEP));
579 rememberInstruction(GEP);
581 // Restore the original insert point.
583 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
585 return expand(SE.getAddExpr(Ops));
588 /// isNonConstantNegative - Return true if the specified scev is negated, but
590 static bool isNonConstantNegative(const SCEV *F) {
591 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(F);
592 if (!Mul) return false;
594 // If there is a constant factor, it will be first.
595 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
596 if (!SC) return false;
598 // Return true if the value is negative, this matches things like (-42 * V).
599 return SC->getValue()->getValue().isNegative();
602 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
603 /// SCEV expansion. If they are nested, this is the most nested. If they are
604 /// neighboring, pick the later.
605 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
609 if (A->contains(B)) return B;
610 if (B->contains(A)) return A;
611 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
612 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
613 return A; // Arbitrarily break the tie.
616 /// GetRelevantLoop - Get the most relevant loop associated with the given
617 /// expression, according to PickMostRelevantLoop.
618 static const Loop *GetRelevantLoop(const SCEV *S, LoopInfo &LI,
620 if (isa<SCEVConstant>(S))
622 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
623 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
624 return LI.getLoopFor(I->getParent());
627 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
629 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
631 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
633 L = PickMostRelevantLoop(L, GetRelevantLoop(*I, LI, DT), DT);
636 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
637 return GetRelevantLoop(C->getOperand(), LI, DT);
638 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S))
639 return PickMostRelevantLoop(GetRelevantLoop(D->getLHS(), LI, DT),
640 GetRelevantLoop(D->getRHS(), LI, DT),
642 llvm_unreachable("Unexpected SCEV type!");
645 /// LoopCompare - Compare loops by PickMostRelevantLoop.
649 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
651 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
652 std::pair<const Loop *, const SCEV *> RHS) const {
653 // Compare loops with PickMostRelevantLoop.
654 if (LHS.first != RHS.first)
655 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
657 // If one operand is a non-constant negative and the other is not,
658 // put the non-constant negative on the right so that a sub can
659 // be used instead of a negate and add.
660 if (isNonConstantNegative(LHS.second)) {
661 if (!isNonConstantNegative(RHS.second))
663 } else if (isNonConstantNegative(RHS.second))
666 // Otherwise they are equivalent according to this comparison.
671 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
672 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
674 // Collect all the add operands in a loop, along with their associated loops.
675 // Iterate in reverse so that constants are emitted last, all else equal, and
676 // so that pointer operands are inserted first, which the code below relies on
677 // to form more involved GEPs.
678 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
679 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
680 E(S->op_begin()); I != E; ++I)
681 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
684 // Sort by loop. Use a stable sort so that constants follow non-constants and
685 // pointer operands precede non-pointer operands.
686 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
688 // Emit instructions to add all the operands. Hoist as much as possible
689 // out of loops, and form meaningful getelementptrs where possible.
691 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
692 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
693 const Loop *CurLoop = I->first;
694 const SCEV *Op = I->second;
696 // This is the first operand. Just expand it.
699 } else if (const PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
700 // The running sum expression is a pointer. Try to form a getelementptr
701 // at this level with that as the base.
702 SmallVector<const SCEV *, 4> NewOps;
703 for (; I != E && I->first == CurLoop; ++I)
704 NewOps.push_back(I->second);
705 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
706 } else if (const PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
707 // The running sum is an integer, and there's a pointer at this level.
708 // Try to form a getelementptr.
709 SmallVector<const SCEV *, 4> NewOps;
710 NewOps.push_back(SE.getUnknown(Sum));
711 for (++I; I != E && I->first == CurLoop; ++I)
712 NewOps.push_back(I->second);
713 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
714 } else if (isNonConstantNegative(Op)) {
715 // Instead of doing a negate and add, just do a subtract.
716 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
717 Sum = InsertNoopCastOfTo(Sum, Ty);
718 Sum = InsertBinop(Instruction::Sub, Sum, W);
722 Value *W = expandCodeFor(Op, Ty);
723 Sum = InsertNoopCastOfTo(Sum, Ty);
724 // Canonicalize a constant to the RHS.
725 if (isa<Constant>(Sum)) std::swap(Sum, W);
726 Sum = InsertBinop(Instruction::Add, Sum, W);
734 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
735 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
737 // Collect all the mul operands in a loop, along with their associated loops.
738 // Iterate in reverse so that constants are emitted last, all else equal.
739 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
740 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
741 E(S->op_begin()); I != E; ++I)
742 OpsAndLoops.push_back(std::make_pair(GetRelevantLoop(*I, *SE.LI, *SE.DT),
745 // Sort by loop. Use a stable sort so that constants follow non-constants.
746 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
748 // Emit instructions to mul all the operands. Hoist as much as possible
751 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
752 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
753 const SCEV *Op = I->second;
755 // This is the first operand. Just expand it.
758 } else if (Op->isAllOnesValue()) {
759 // Instead of doing a multiply by negative one, just do a negate.
760 Prod = InsertNoopCastOfTo(Prod, Ty);
761 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
765 Value *W = expandCodeFor(Op, Ty);
766 Prod = InsertNoopCastOfTo(Prod, Ty);
767 // Canonicalize a constant to the RHS.
768 if (isa<Constant>(Prod)) std::swap(Prod, W);
769 Prod = InsertBinop(Instruction::Mul, Prod, W);
777 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
778 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
780 Value *LHS = expandCodeFor(S->getLHS(), Ty);
781 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
782 const APInt &RHS = SC->getValue()->getValue();
783 if (RHS.isPowerOf2())
784 return InsertBinop(Instruction::LShr, LHS,
785 ConstantInt::get(Ty, RHS.logBase2()));
788 Value *RHS = expandCodeFor(S->getRHS(), Ty);
789 return InsertBinop(Instruction::UDiv, LHS, RHS);
792 /// Move parts of Base into Rest to leave Base with the minimal
793 /// expression that provides a pointer operand suitable for a
795 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
796 ScalarEvolution &SE) {
797 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
798 Base = A->getStart();
799 Rest = SE.getAddExpr(Rest,
800 SE.getAddRecExpr(SE.getIntegerSCEV(0, A->getType()),
801 A->getStepRecurrence(SE),
804 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
805 Base = A->getOperand(A->getNumOperands()-1);
806 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
807 NewAddOps.back() = Rest;
808 Rest = SE.getAddExpr(NewAddOps);
809 ExposePointerBase(Base, Rest, SE);
813 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
814 /// the base addrec, which is the addrec without any non-loop-dominating
815 /// values, and return the PHI.
817 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
819 const Type *ExpandTy,
821 // Reuse a previously-inserted PHI, if present.
822 for (BasicBlock::iterator I = L->getHeader()->begin();
823 PHINode *PN = dyn_cast<PHINode>(I); ++I)
824 if (SE.isSCEVable(PN->getType()) &&
825 (SE.getEffectiveSCEVType(PN->getType()) ==
826 SE.getEffectiveSCEVType(Normalized->getType())) &&
827 SE.getSCEV(PN) == Normalized)
828 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
830 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
832 // Determine if this is a well-behaved chain of instructions leading
833 // back to the PHI. It probably will be, if we're scanning an inner
834 // loop already visited by LSR for example, but it wouldn't have
837 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV)) {
841 // If any of the operands don't dominate the insert position, bail.
842 // Addrec operands are always loop-invariant, so this can only happen
843 // if there are instructions which haven't been hoisted.
844 for (User::op_iterator OI = IncV->op_begin()+1,
845 OE = IncV->op_end(); OI != OE; ++OI)
846 if (Instruction *OInst = dyn_cast<Instruction>(OI))
847 if (!SE.DT->dominates(OInst, IVIncInsertPos)) {
853 // Advance to the next instruction.
854 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
857 if (IncV->mayHaveSideEffects()) {
861 } while (IncV != PN);
864 // Ok, the add recurrence looks usable.
865 // Remember this PHI, even in post-inc mode.
866 InsertedValues.insert(PN);
867 // Remember the increment.
868 IncV = cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
869 rememberInstruction(IncV);
870 if (L == IVIncInsertLoop)
872 if (SE.DT->dominates(IncV, IVIncInsertPos))
874 // Make sure the increment is where we want it. But don't move it
875 // down past a potential existing post-inc user.
876 IncV->moveBefore(IVIncInsertPos);
877 IVIncInsertPos = IncV;
878 IncV = cast<Instruction>(IncV->getOperand(0));
879 } while (IncV != PN);
884 // Save the original insertion point so we can restore it when we're done.
885 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
886 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
888 // Expand code for the start value.
889 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
890 L->getHeader()->begin());
892 // Expand code for the step value. Insert instructions right before the
893 // terminator corresponding to the back-edge. Do this before creating the PHI
894 // so that PHI reuse code doesn't see an incomplete PHI. If the stride is
895 // negative, insert a sub instead of an add for the increment (unless it's a
896 // constant, because subtracts of constants are canonicalized to adds).
897 const SCEV *Step = Normalized->getStepRecurrence(SE);
898 bool isPointer = ExpandTy->isPointerTy();
899 bool isNegative = !isPointer && isNonConstantNegative(Step);
901 Step = SE.getNegativeSCEV(Step);
902 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
905 Builder.SetInsertPoint(L->getHeader(), L->getHeader()->begin());
906 PHINode *PN = Builder.CreatePHI(ExpandTy, "lsr.iv");
907 rememberInstruction(PN);
909 // Create the step instructions and populate the PHI.
910 BasicBlock *Header = L->getHeader();
911 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
913 BasicBlock *Pred = *HPI;
915 // Add a start value.
916 if (!L->contains(Pred)) {
917 PN->addIncoming(StartV, Pred);
921 // Create a step value and add it to the PHI. If IVIncInsertLoop is
922 // non-null and equal to the addrec's loop, insert the instructions
923 // at IVIncInsertPos.
924 Instruction *InsertPos = L == IVIncInsertLoop ?
925 IVIncInsertPos : Pred->getTerminator();
926 Builder.SetInsertPoint(InsertPos->getParent(), InsertPos);
928 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
930 const PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
931 // If the step isn't constant, don't use an implicitly scaled GEP, because
932 // that would require a multiply inside the loop.
933 if (!isa<ConstantInt>(StepV))
934 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
935 GEPPtrTy->getAddressSpace());
936 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
937 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
938 if (IncV->getType() != PN->getType()) {
939 IncV = Builder.CreateBitCast(IncV, PN->getType(), "tmp");
940 rememberInstruction(IncV);
944 Builder.CreateSub(PN, StepV, "lsr.iv.next") :
945 Builder.CreateAdd(PN, StepV, "lsr.iv.next");
946 rememberInstruction(IncV);
948 PN->addIncoming(IncV, Pred);
951 // Restore the original insert point.
953 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
955 // Remember this PHI, even in post-inc mode.
956 InsertedValues.insert(PN);
961 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
962 const Type *STy = S->getType();
963 const Type *IntTy = SE.getEffectiveSCEVType(STy);
964 const Loop *L = S->getLoop();
966 // Determine a normalized form of this expression, which is the expression
967 // before any post-inc adjustment is made.
968 const SCEVAddRecExpr *Normalized = S;
969 if (L == PostIncLoop) {
970 const SCEV *Step = S->getStepRecurrence(SE);
971 Normalized = cast<SCEVAddRecExpr>(SE.getMinusSCEV(S, Step));
974 // Strip off any non-loop-dominating component from the addrec start.
975 const SCEV *Start = Normalized->getStart();
976 const SCEV *PostLoopOffset = 0;
977 if (!Start->properlyDominates(L->getHeader(), SE.DT)) {
978 PostLoopOffset = Start;
979 Start = SE.getIntegerSCEV(0, Normalized->getType());
981 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start,
982 Normalized->getStepRecurrence(SE),
983 Normalized->getLoop()));
986 // Strip off any non-loop-dominating component from the addrec step.
987 const SCEV *Step = Normalized->getStepRecurrence(SE);
988 const SCEV *PostLoopScale = 0;
989 if (!Step->hasComputableLoopEvolution(L) &&
990 !Step->dominates(L->getHeader(), SE.DT)) {
991 PostLoopScale = Step;
992 Step = SE.getIntegerSCEV(1, Normalized->getType());
994 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
995 Normalized->getLoop()));
998 // Expand the core addrec. If we need post-loop scaling, force it to
999 // expand to an integer type to avoid the need for additional casting.
1000 const Type *ExpandTy = PostLoopScale ? IntTy : STy;
1001 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1003 // Accommodate post-inc mode, if necessary.
1005 if (L != PostIncLoop)
1008 // In PostInc mode, use the post-incremented value.
1009 BasicBlock *LatchBlock = L->getLoopLatch();
1010 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1011 Result = PN->getIncomingValueForBlock(LatchBlock);
1014 // Re-apply any non-loop-dominating scale.
1015 if (PostLoopScale) {
1016 Result = InsertNoopCastOfTo(Result, IntTy);
1017 Result = Builder.CreateMul(Result,
1018 expandCodeFor(PostLoopScale, IntTy));
1019 rememberInstruction(Result);
1022 // Re-apply any non-loop-dominating offset.
1023 if (PostLoopOffset) {
1024 if (const PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1025 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1026 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1028 Result = InsertNoopCastOfTo(Result, IntTy);
1029 Result = Builder.CreateAdd(Result,
1030 expandCodeFor(PostLoopOffset, IntTy));
1031 rememberInstruction(Result);
1038 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1039 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1041 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1042 const Loop *L = S->getLoop();
1044 // First check for an existing canonical IV in a suitable type.
1045 PHINode *CanonicalIV = 0;
1046 if (PHINode *PN = L->getCanonicalInductionVariable())
1047 if (SE.isSCEVable(PN->getType()) &&
1048 SE.getEffectiveSCEVType(PN->getType())->isIntegerTy() &&
1049 SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1052 // Rewrite an AddRec in terms of the canonical induction variable, if
1053 // its type is more narrow.
1055 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1056 SE.getTypeSizeInBits(Ty)) {
1057 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1058 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1059 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1060 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop()));
1061 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1062 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1063 BasicBlock::iterator NewInsertPt =
1064 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1065 while (isa<PHINode>(NewInsertPt)) ++NewInsertPt;
1066 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1068 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1072 // {X,+,F} --> X + {0,+,F}
1073 if (!S->getStart()->isZero()) {
1074 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1075 NewOps[0] = SE.getIntegerSCEV(0, Ty);
1076 const SCEV *Rest = SE.getAddRecExpr(NewOps, L);
1078 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1079 // comments on expandAddToGEP for details.
1080 const SCEV *Base = S->getStart();
1081 const SCEV *RestArray[1] = { Rest };
1082 // Dig into the expression to find the pointer base for a GEP.
1083 ExposePointerBase(Base, RestArray[0], SE);
1084 // If we found a pointer, expand the AddRec with a GEP.
1085 if (const PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1086 // Make sure the Base isn't something exotic, such as a multiplied
1087 // or divided pointer value. In those cases, the result type isn't
1088 // actually a pointer type.
1089 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1090 Value *StartV = expand(Base);
1091 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1092 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1096 // Just do a normal add. Pre-expand the operands to suppress folding.
1097 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1098 SE.getUnknown(expand(Rest))));
1101 // {0,+,1} --> Insert a canonical induction variable into the loop!
1102 if (S->isAffine() &&
1103 S->getOperand(1) == SE.getIntegerSCEV(1, Ty)) {
1104 // If there's a canonical IV, just use it.
1106 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1107 "IVs with types different from the canonical IV should "
1108 "already have been handled!");
1112 // Create and insert the PHI node for the induction variable in the
1114 BasicBlock *Header = L->getHeader();
1115 PHINode *PN = PHINode::Create(Ty, "indvar", Header->begin());
1116 rememberInstruction(PN);
1118 Constant *One = ConstantInt::get(Ty, 1);
1119 for (pred_iterator HPI = pred_begin(Header), HPE = pred_end(Header);
1121 if (L->contains(*HPI)) {
1122 // Insert a unit add instruction right before the terminator
1123 // corresponding to the back-edge.
1124 Instruction *Add = BinaryOperator::CreateAdd(PN, One, "indvar.next",
1125 (*HPI)->getTerminator());
1126 rememberInstruction(Add);
1127 PN->addIncoming(Add, *HPI);
1129 PN->addIncoming(Constant::getNullValue(Ty), *HPI);
1133 // {0,+,F} --> {0,+,1} * F
1134 // Get the canonical induction variable I for this loop.
1135 Value *I = CanonicalIV ?
1137 getOrInsertCanonicalInductionVariable(L, Ty);
1139 // If this is a simple linear addrec, emit it now as a special case.
1140 if (S->isAffine()) // {0,+,F} --> i*F
1142 expand(SE.getTruncateOrNoop(
1143 SE.getMulExpr(SE.getUnknown(I),
1144 SE.getNoopOrAnyExtend(S->getOperand(1),
1148 // If this is a chain of recurrences, turn it into a closed form, using the
1149 // folders, then expandCodeFor the closed form. This allows the folders to
1150 // simplify the expression without having to build a bunch of special code
1151 // into this folder.
1152 const SCEV *IH = SE.getUnknown(I); // Get I as a "symbolic" SCEV.
1154 // Promote S up to the canonical IV type, if the cast is foldable.
1155 const SCEV *NewS = S;
1156 const SCEV *Ext = SE.getNoopOrAnyExtend(S, I->getType());
1157 if (isa<SCEVAddRecExpr>(Ext))
1160 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1161 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1163 // Truncate the result down to the original type, if needed.
1164 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1168 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1169 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1170 Value *V = expandCodeFor(S->getOperand(),
1171 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1172 Value *I = Builder.CreateTrunc(V, Ty, "tmp");
1173 rememberInstruction(I);
1177 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1178 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1179 Value *V = expandCodeFor(S->getOperand(),
1180 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1181 Value *I = Builder.CreateZExt(V, Ty, "tmp");
1182 rememberInstruction(I);
1186 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1187 const Type *Ty = SE.getEffectiveSCEVType(S->getType());
1188 Value *V = expandCodeFor(S->getOperand(),
1189 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1190 Value *I = Builder.CreateSExt(V, Ty, "tmp");
1191 rememberInstruction(I);
1195 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1196 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1197 const Type *Ty = LHS->getType();
1198 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1199 // In the case of mixed integer and pointer types, do the
1200 // rest of the comparisons as integer.
1201 if (S->getOperand(i)->getType() != Ty) {
1202 Ty = SE.getEffectiveSCEVType(Ty);
1203 LHS = InsertNoopCastOfTo(LHS, Ty);
1205 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1206 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS, "tmp");
1207 rememberInstruction(ICmp);
1208 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1209 rememberInstruction(Sel);
1212 // In the case of mixed integer and pointer types, cast the
1213 // final result back to the pointer type.
1214 if (LHS->getType() != S->getType())
1215 LHS = InsertNoopCastOfTo(LHS, S->getType());
1219 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1220 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1221 const Type *Ty = LHS->getType();
1222 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1223 // In the case of mixed integer and pointer types, do the
1224 // rest of the comparisons as integer.
1225 if (S->getOperand(i)->getType() != Ty) {
1226 Ty = SE.getEffectiveSCEVType(Ty);
1227 LHS = InsertNoopCastOfTo(LHS, Ty);
1229 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1230 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS, "tmp");
1231 rememberInstruction(ICmp);
1232 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1233 rememberInstruction(Sel);
1236 // In the case of mixed integer and pointer types, cast the
1237 // final result back to the pointer type.
1238 if (LHS->getType() != S->getType())
1239 LHS = InsertNoopCastOfTo(LHS, S->getType());
1243 Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty,
1245 BasicBlock::iterator IP = I;
1246 while (isInsertedInstruction(IP) || isa<DbgInfoIntrinsic>(IP))
1248 Builder.SetInsertPoint(IP->getParent(), IP);
1249 return expandCodeFor(SH, Ty);
1252 Value *SCEVExpander::expandCodeFor(const SCEV *SH, const Type *Ty) {
1253 // Expand the code for this SCEV.
1254 Value *V = expand(SH);
1256 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1257 "non-trivial casts should be done with the SCEVs directly!");
1258 V = InsertNoopCastOfTo(V, Ty);
1263 Value *SCEVExpander::expand(const SCEV *S) {
1264 // Compute an insertion point for this SCEV object. Hoist the instructions
1265 // as far out in the loop nest as possible.
1266 Instruction *InsertPt = Builder.GetInsertPoint();
1267 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
1268 L = L->getParentLoop())
1269 if (S->isLoopInvariant(L)) {
1271 if (BasicBlock *Preheader = L->getLoopPreheader()) {
1272 InsertPt = Preheader->getTerminator();
1273 BasicBlock::iterator IP = InsertPt;
1274 // Back past any debug info instructions. Sometimes we inserted
1275 // something earlier before debug info but after any real instructions.
1276 // This should behave the same as if debug info was not present.
1277 while (IP != Preheader->begin()) {
1279 if (!isa<DbgInfoIntrinsic>(IP))
1285 // If the SCEV is computable at this level, insert it into the header
1286 // after the PHIs (and after any other instructions that we've inserted
1287 // there) so that it is guaranteed to dominate any user inside the loop.
1288 if (L && S->hasComputableLoopEvolution(L) && L != PostIncLoop)
1289 InsertPt = L->getHeader()->getFirstNonPHI();
1290 while (isInsertedInstruction(InsertPt) || isa<DbgInfoIntrinsic>(InsertPt))
1291 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1295 // Check to see if we already expanded this here.
1296 std::map<std::pair<const SCEV *, Instruction *>,
1297 AssertingVH<Value> >::iterator I =
1298 InsertedExpressions.find(std::make_pair(S, InsertPt));
1299 if (I != InsertedExpressions.end())
1302 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1303 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1304 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1306 // Expand the expression into instructions.
1307 Value *V = visit(S);
1309 // Remember the expanded value for this SCEV at this location.
1311 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1313 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1317 void SCEVExpander::rememberInstruction(Value *I) {
1319 InsertedValues.insert(I);
1321 // If we just claimed an existing instruction and that instruction had
1322 // been the insert point, adjust the insert point forward so that
1323 // subsequently inserted code will be dominated.
1324 if (Builder.GetInsertPoint() == I) {
1325 BasicBlock::iterator It = cast<Instruction>(I);
1326 do { ++It; } while (isInsertedInstruction(It) ||
1327 isa<DbgInfoIntrinsic>(It));
1328 Builder.SetInsertPoint(Builder.GetInsertBlock(), It);
1332 void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
1333 // If we acquired more instructions since the old insert point was saved,
1334 // advance past them.
1335 while (isInsertedInstruction(I) || isa<DbgInfoIntrinsic>(I)) ++I;
1337 Builder.SetInsertPoint(BB, I);
1340 /// getOrInsertCanonicalInductionVariable - This method returns the
1341 /// canonical induction variable of the specified type for the specified
1342 /// loop (inserting one if there is none). A canonical induction variable
1343 /// starts at zero and steps by one on each iteration.
1345 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1347 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1348 const SCEV *H = SE.getAddRecExpr(SE.getIntegerSCEV(0, Ty),
1349 SE.getIntegerSCEV(1, Ty), L);
1350 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1351 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1352 Value *V = expandCodeFor(H, 0, L->getHeader()->begin());
1354 restoreInsertPoint(SaveInsertBB, SaveInsertPt);