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/Support/Debug.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/ADT/STLExtras.h"
27 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
28 /// reusing an existing cast if a suitable one exists, moving an existing
29 /// cast if a suitable one exists but isn't in the right place, or
30 /// creating a new one.
31 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
32 Instruction::CastOps Op,
33 BasicBlock::iterator IP) {
34 // All new or reused instructions must strictly dominate their uses.
35 // It would be nice to assert this here, but we don't always know where
36 // the next instructions will be added as the the caller can move the
37 // Builder's InsertPt before creating them and we might be called with
38 // an invalid InsertPt.
40 // Check to see if there is already a cast!
41 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
44 if (U->getType() == Ty)
45 if (CastInst *CI = dyn_cast<CastInst>(U))
46 if (CI->getOpcode() == Op) {
47 // If the cast isn't where we want it, fix it.
48 if (BasicBlock::iterator(CI) != IP) {
49 // Create a new cast, and leave the old cast in place in case
50 // it is being used as an insert point. Clear its operand
51 // so that it doesn't hold anything live.
52 Instruction *NewCI = CastInst::Create(Op, V, Ty, "", IP);
54 CI->replaceAllUsesWith(NewCI);
55 CI->setOperand(0, UndefValue::get(V->getType()));
56 rememberInstruction(NewCI);
59 rememberInstruction(CI);
65 Instruction *I = CastInst::Create(Op, V, Ty, V->getName(), IP);
66 rememberInstruction(I);
70 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
71 /// which must be possible with a noop cast, doing what we can to share
73 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
74 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
75 assert((Op == Instruction::BitCast ||
76 Op == Instruction::PtrToInt ||
77 Op == Instruction::IntToPtr) &&
78 "InsertNoopCastOfTo cannot perform non-noop casts!");
79 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
80 "InsertNoopCastOfTo cannot change sizes!");
82 // Short-circuit unnecessary bitcasts.
83 if (Op == Instruction::BitCast) {
84 if (V->getType() == Ty)
86 if (CastInst *CI = dyn_cast<CastInst>(V)) {
87 if (CI->getOperand(0)->getType() == Ty)
88 return CI->getOperand(0);
91 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
92 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
93 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
94 if (CastInst *CI = dyn_cast<CastInst>(V))
95 if ((CI->getOpcode() == Instruction::PtrToInt ||
96 CI->getOpcode() == Instruction::IntToPtr) &&
97 SE.getTypeSizeInBits(CI->getType()) ==
98 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
99 return CI->getOperand(0);
100 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
101 if ((CE->getOpcode() == Instruction::PtrToInt ||
102 CE->getOpcode() == Instruction::IntToPtr) &&
103 SE.getTypeSizeInBits(CE->getType()) ==
104 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
105 return CE->getOperand(0);
108 // Fold a cast of a constant.
109 if (Constant *C = dyn_cast<Constant>(V))
110 return ConstantExpr::getCast(Op, C, Ty);
112 // Cast the argument at the beginning of the entry block, after
113 // any bitcasts of other arguments.
114 if (Argument *A = dyn_cast<Argument>(V)) {
115 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
116 while ((isa<BitCastInst>(IP) &&
117 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
118 cast<BitCastInst>(IP)->getOperand(0) != A) ||
119 isa<DbgInfoIntrinsic>(IP) ||
120 isa<LandingPadInst>(IP))
122 return ReuseOrCreateCast(A, Ty, Op, IP);
125 // Cast the instruction immediately after the instruction.
126 Instruction *I = cast<Instruction>(V);
127 BasicBlock::iterator IP = I; ++IP;
128 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
129 IP = II->getNormalDest()->begin();
130 while (isa<PHINode>(IP) || isa<LandingPadInst>(IP))
132 return ReuseOrCreateCast(I, Ty, Op, IP);
135 /// InsertBinop - Insert the specified binary operator, doing a small amount
136 /// of work to avoid inserting an obviously redundant operation.
137 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
138 Value *LHS, Value *RHS) {
139 // Fold a binop with constant operands.
140 if (Constant *CLHS = dyn_cast<Constant>(LHS))
141 if (Constant *CRHS = dyn_cast<Constant>(RHS))
142 return ConstantExpr::get(Opcode, CLHS, CRHS);
144 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
145 unsigned ScanLimit = 6;
146 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
147 // Scanning starts from the last instruction before the insertion point.
148 BasicBlock::iterator IP = Builder.GetInsertPoint();
149 if (IP != BlockBegin) {
151 for (; ScanLimit; --IP, --ScanLimit) {
152 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
154 if (isa<DbgInfoIntrinsic>(IP))
156 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
157 IP->getOperand(1) == RHS)
159 if (IP == BlockBegin) break;
163 // Save the original insertion point so we can restore it when we're done.
164 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
165 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
167 // Move the insertion point out of as many loops as we can.
168 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
169 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
170 BasicBlock *Preheader = L->getLoopPreheader();
171 if (!Preheader) break;
173 // Ok, move up a level.
174 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
177 // If we haven't found this binop, insert it.
178 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
179 BO->setDebugLoc(SaveInsertPt->getDebugLoc());
180 rememberInstruction(BO);
182 // Restore the original insert point.
184 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
189 /// FactorOutConstant - Test if S is divisible by Factor, using signed
190 /// division. If so, update S with Factor divided out and return true.
191 /// S need not be evenly divisible if a reasonable remainder can be
193 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
194 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
195 /// check to see if the divide was folded.
196 static bool FactorOutConstant(const SCEV *&S,
197 const SCEV *&Remainder,
200 const TargetData *TD) {
201 // Everything is divisible by one.
207 S = SE.getConstant(S->getType(), 1);
211 // For a Constant, check for a multiple of the given factor.
212 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
216 // Check for divisibility.
217 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
219 ConstantInt::get(SE.getContext(),
220 C->getValue()->getValue().sdiv(
221 FC->getValue()->getValue()));
222 // If the quotient is zero and the remainder is non-zero, reject
223 // the value at this scale. It will be considered for subsequent
226 const SCEV *Div = SE.getConstant(CI);
229 SE.getAddExpr(Remainder,
230 SE.getConstant(C->getValue()->getValue().srem(
231 FC->getValue()->getValue())));
237 // In a Mul, check if there is a constant operand which is a multiple
238 // of the given factor.
239 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
241 // With TargetData, the size is known. Check if there is a constant
242 // operand which is a multiple of the given factor. If so, we can
244 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
245 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
246 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
247 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
249 SE.getConstant(C->getValue()->getValue().sdiv(
250 FC->getValue()->getValue()));
251 S = SE.getMulExpr(NewMulOps);
255 // Without TargetData, check if Factor can be factored out of any of the
256 // Mul's operands. If so, we can just remove it.
257 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
258 const SCEV *SOp = M->getOperand(i);
259 const SCEV *Remainder = SE.getConstant(SOp->getType(), 0);
260 if (FactorOutConstant(SOp, Remainder, Factor, SE, TD) &&
261 Remainder->isZero()) {
262 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
264 S = SE.getMulExpr(NewMulOps);
271 // In an AddRec, check if both start and step are divisible.
272 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
273 const SCEV *Step = A->getStepRecurrence(SE);
274 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
275 if (!FactorOutConstant(Step, StepRem, Factor, SE, TD))
277 if (!StepRem->isZero())
279 const SCEV *Start = A->getStart();
280 if (!FactorOutConstant(Start, Remainder, Factor, SE, TD))
282 // FIXME: can use A->getNoWrapFlags(FlagNW)
283 S = SE.getAddRecExpr(Start, Step, A->getLoop(), SCEV::FlagAnyWrap);
290 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
291 /// is the number of SCEVAddRecExprs present, which are kept at the end of
294 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
296 ScalarEvolution &SE) {
297 unsigned NumAddRecs = 0;
298 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
300 // Group Ops into non-addrecs and addrecs.
301 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
302 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
303 // Let ScalarEvolution sort and simplify the non-addrecs list.
304 const SCEV *Sum = NoAddRecs.empty() ?
305 SE.getConstant(Ty, 0) :
306 SE.getAddExpr(NoAddRecs);
307 // If it returned an add, use the operands. Otherwise it simplified
308 // the sum into a single value, so just use that.
310 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
311 Ops.append(Add->op_begin(), Add->op_end());
312 else if (!Sum->isZero())
314 // Then append the addrecs.
315 Ops.append(AddRecs.begin(), AddRecs.end());
318 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
319 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
320 /// This helps expose more opportunities for folding parts of the expressions
321 /// into GEP indices.
323 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
325 ScalarEvolution &SE) {
327 SmallVector<const SCEV *, 8> AddRecs;
328 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
329 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
330 const SCEV *Start = A->getStart();
331 if (Start->isZero()) break;
332 const SCEV *Zero = SE.getConstant(Ty, 0);
333 AddRecs.push_back(SE.getAddRecExpr(Zero,
334 A->getStepRecurrence(SE),
336 // FIXME: A->getNoWrapFlags(FlagNW)
338 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
340 Ops.append(Add->op_begin(), Add->op_end());
341 e += Add->getNumOperands();
346 if (!AddRecs.empty()) {
347 // Add the addrecs onto the end of the list.
348 Ops.append(AddRecs.begin(), AddRecs.end());
349 // Resort the operand list, moving any constants to the front.
350 SimplifyAddOperands(Ops, Ty, SE);
354 /// expandAddToGEP - Expand an addition expression with a pointer type into
355 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
356 /// BasicAliasAnalysis and other passes analyze the result. See the rules
357 /// for getelementptr vs. inttoptr in
358 /// http://llvm.org/docs/LangRef.html#pointeraliasing
361 /// Design note: The correctness of using getelementptr here depends on
362 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
363 /// they may introduce pointer arithmetic which may not be safely converted
364 /// into getelementptr.
366 /// Design note: It might seem desirable for this function to be more
367 /// loop-aware. If some of the indices are loop-invariant while others
368 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
369 /// loop-invariant portions of the overall computation outside the loop.
370 /// However, there are a few reasons this is not done here. Hoisting simple
371 /// arithmetic is a low-level optimization that often isn't very
372 /// important until late in the optimization process. In fact, passes
373 /// like InstructionCombining will combine GEPs, even if it means
374 /// pushing loop-invariant computation down into loops, so even if the
375 /// GEPs were split here, the work would quickly be undone. The
376 /// LoopStrengthReduction pass, which is usually run quite late (and
377 /// after the last InstructionCombining pass), takes care of hoisting
378 /// loop-invariant portions of expressions, after considering what
379 /// can be folded using target addressing modes.
381 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
382 const SCEV *const *op_end,
386 Type *ElTy = PTy->getElementType();
387 SmallVector<Value *, 4> GepIndices;
388 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
389 bool AnyNonZeroIndices = false;
391 // Split AddRecs up into parts as either of the parts may be usable
392 // without the other.
393 SplitAddRecs(Ops, Ty, SE);
395 // Descend down the pointer's type and attempt to convert the other
396 // operands into GEP indices, at each level. The first index in a GEP
397 // indexes into the array implied by the pointer operand; the rest of
398 // the indices index into the element or field type selected by the
401 // If the scale size is not 0, attempt to factor out a scale for
403 SmallVector<const SCEV *, 8> ScaledOps;
404 if (ElTy->isSized()) {
405 const SCEV *ElSize = SE.getSizeOfExpr(ElTy);
406 if (!ElSize->isZero()) {
407 SmallVector<const SCEV *, 8> NewOps;
408 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
409 const SCEV *Op = Ops[i];
410 const SCEV *Remainder = SE.getConstant(Ty, 0);
411 if (FactorOutConstant(Op, Remainder, ElSize, SE, SE.TD)) {
412 // Op now has ElSize factored out.
413 ScaledOps.push_back(Op);
414 if (!Remainder->isZero())
415 NewOps.push_back(Remainder);
416 AnyNonZeroIndices = true;
418 // The operand was not divisible, so add it to the list of operands
419 // we'll scan next iteration.
420 NewOps.push_back(Ops[i]);
423 // If we made any changes, update Ops.
424 if (!ScaledOps.empty()) {
426 SimplifyAddOperands(Ops, Ty, SE);
431 // Record the scaled array index for this level of the type. If
432 // we didn't find any operands that could be factored, tentatively
433 // assume that element zero was selected (since the zero offset
434 // would obviously be folded away).
435 Value *Scaled = ScaledOps.empty() ?
436 Constant::getNullValue(Ty) :
437 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
438 GepIndices.push_back(Scaled);
440 // Collect struct field index operands.
441 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
442 bool FoundFieldNo = false;
443 // An empty struct has no fields.
444 if (STy->getNumElements() == 0) break;
446 // With TargetData, field offsets are known. See if a constant offset
447 // falls within any of the struct fields.
448 if (Ops.empty()) break;
449 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
450 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
451 const StructLayout &SL = *SE.TD->getStructLayout(STy);
452 uint64_t FullOffset = C->getValue()->getZExtValue();
453 if (FullOffset < SL.getSizeInBytes()) {
454 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
455 GepIndices.push_back(
456 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
457 ElTy = STy->getTypeAtIndex(ElIdx);
459 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
460 AnyNonZeroIndices = true;
465 // Without TargetData, just check for an offsetof expression of the
466 // appropriate struct type.
467 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
468 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Ops[i])) {
471 if (U->isOffsetOf(CTy, FieldNo) && CTy == STy) {
472 GepIndices.push_back(FieldNo);
474 STy->getTypeAtIndex(cast<ConstantInt>(FieldNo)->getZExtValue());
475 Ops[i] = SE.getConstant(Ty, 0);
476 AnyNonZeroIndices = true;
482 // If no struct field offsets were found, tentatively assume that
483 // field zero was selected (since the zero offset would obviously
486 ElTy = STy->getTypeAtIndex(0u);
487 GepIndices.push_back(
488 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
492 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
493 ElTy = ATy->getElementType();
498 // If none of the operands were convertible to proper GEP indices, cast
499 // the base to i8* and do an ugly getelementptr with that. It's still
500 // better than ptrtoint+arithmetic+inttoptr at least.
501 if (!AnyNonZeroIndices) {
502 // Cast the base to i8*.
503 V = InsertNoopCastOfTo(V,
504 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
506 Instruction *Inst = dyn_cast<Instruction>(V);
507 assert(!Inst || SE.DT->properlyDominates(Inst, Builder.GetInsertPoint()));
509 // Expand the operands for a plain byte offset.
510 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
512 // Fold a GEP with constant operands.
513 if (Constant *CLHS = dyn_cast<Constant>(V))
514 if (Constant *CRHS = dyn_cast<Constant>(Idx))
515 return ConstantExpr::getGetElementPtr(CLHS, CRHS);
517 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
518 unsigned ScanLimit = 6;
519 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
520 // Scanning starts from the last instruction before the insertion point.
521 BasicBlock::iterator IP = Builder.GetInsertPoint();
522 if (IP != BlockBegin) {
524 for (; ScanLimit; --IP, --ScanLimit) {
525 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
527 if (isa<DbgInfoIntrinsic>(IP))
529 if (IP->getOpcode() == Instruction::GetElementPtr &&
530 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
532 if (IP == BlockBegin) break;
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) || !L->isLoopInvariant(Idx)) break;
543 BasicBlock *Preheader = L->getLoopPreheader();
544 if (!Preheader) break;
546 // Ok, move up a level.
547 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
551 Value *GEP = Builder.CreateGEP(V, Idx, "uglygep");
552 rememberInstruction(GEP);
554 // Restore the original insert point.
556 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
561 // Save the original insertion point so we can restore it when we're done.
562 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
563 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
565 // Move the insertion point out of as many loops as we can.
566 while (const Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock())) {
567 if (!L->isLoopInvariant(V)) break;
569 bool AnyIndexNotLoopInvariant = false;
570 for (SmallVectorImpl<Value *>::const_iterator I = GepIndices.begin(),
571 E = GepIndices.end(); I != E; ++I)
572 if (!L->isLoopInvariant(*I)) {
573 AnyIndexNotLoopInvariant = true;
576 if (AnyIndexNotLoopInvariant)
579 BasicBlock *Preheader = L->getLoopPreheader();
580 if (!Preheader) break;
582 // Ok, move up a level.
583 Builder.SetInsertPoint(Preheader, Preheader->getTerminator());
586 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
587 // because ScalarEvolution may have changed the address arithmetic to
588 // compute a value which is beyond the end of the allocated object.
590 if (V->getType() != PTy)
591 Casted = InsertNoopCastOfTo(Casted, PTy);
592 Value *GEP = Builder.CreateGEP(Casted,
595 Ops.push_back(SE.getUnknown(GEP));
596 rememberInstruction(GEP);
598 // Restore the original insert point.
600 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
602 return expand(SE.getAddExpr(Ops));
605 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
606 /// SCEV expansion. If they are nested, this is the most nested. If they are
607 /// neighboring, pick the later.
608 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
612 if (A->contains(B)) return B;
613 if (B->contains(A)) return A;
614 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
615 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
616 return A; // Arbitrarily break the tie.
619 /// getRelevantLoop - Get the most relevant loop associated with the given
620 /// expression, according to PickMostRelevantLoop.
621 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
622 // Test whether we've already computed the most relevant loop for this SCEV.
623 std::pair<DenseMap<const SCEV *, const Loop *>::iterator, bool> Pair =
624 RelevantLoops.insert(std::make_pair(S, static_cast<const Loop *>(0)));
626 return Pair.first->second;
628 if (isa<SCEVConstant>(S))
629 // A constant has no relevant loops.
631 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
632 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
633 return Pair.first->second = SE.LI->getLoopFor(I->getParent());
634 // A non-instruction has no relevant loops.
637 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
639 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
641 for (SCEVNAryExpr::op_iterator I = N->op_begin(), E = N->op_end();
643 L = PickMostRelevantLoop(L, getRelevantLoop(*I), *SE.DT);
644 return RelevantLoops[N] = L;
646 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
647 const Loop *Result = getRelevantLoop(C->getOperand());
648 return RelevantLoops[C] = Result;
650 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
652 PickMostRelevantLoop(getRelevantLoop(D->getLHS()),
653 getRelevantLoop(D->getRHS()),
655 return RelevantLoops[D] = Result;
657 llvm_unreachable("Unexpected SCEV type!");
662 /// LoopCompare - Compare loops by PickMostRelevantLoop.
666 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
668 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
669 std::pair<const Loop *, const SCEV *> RHS) const {
670 // Keep pointer operands sorted at the end.
671 if (LHS.second->getType()->isPointerTy() !=
672 RHS.second->getType()->isPointerTy())
673 return LHS.second->getType()->isPointerTy();
675 // Compare loops with PickMostRelevantLoop.
676 if (LHS.first != RHS.first)
677 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
679 // If one operand is a non-constant negative and the other is not,
680 // put the non-constant negative on the right so that a sub can
681 // be used instead of a negate and add.
682 if (LHS.second->isNonConstantNegative()) {
683 if (!RHS.second->isNonConstantNegative())
685 } else if (RHS.second->isNonConstantNegative())
688 // Otherwise they are equivalent according to this comparison.
695 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
696 Type *Ty = SE.getEffectiveSCEVType(S->getType());
698 // Collect all the add operands in a loop, along with their associated loops.
699 // Iterate in reverse so that constants are emitted last, all else equal, and
700 // so that pointer operands are inserted first, which the code below relies on
701 // to form more involved GEPs.
702 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
703 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
704 E(S->op_begin()); I != E; ++I)
705 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
707 // Sort by loop. Use a stable sort so that constants follow non-constants and
708 // pointer operands precede non-pointer operands.
709 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
711 // Emit instructions to add all the operands. Hoist as much as possible
712 // out of loops, and form meaningful getelementptrs where possible.
714 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
715 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
716 const Loop *CurLoop = I->first;
717 const SCEV *Op = I->second;
719 // This is the first operand. Just expand it.
722 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
723 // The running sum expression is a pointer. Try to form a getelementptr
724 // at this level with that as the base.
725 SmallVector<const SCEV *, 4> NewOps;
726 for (; I != E && I->first == CurLoop; ++I) {
727 // If the operand is SCEVUnknown and not instructions, peek through
728 // it, to enable more of it to be folded into the GEP.
729 const SCEV *X = I->second;
730 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
731 if (!isa<Instruction>(U->getValue()))
732 X = SE.getSCEV(U->getValue());
735 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
736 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
737 // The running sum is an integer, and there's a pointer at this level.
738 // Try to form a getelementptr. If the running sum is instructions,
739 // use a SCEVUnknown to avoid re-analyzing them.
740 SmallVector<const SCEV *, 4> NewOps;
741 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
743 for (++I; I != E && I->first == CurLoop; ++I)
744 NewOps.push_back(I->second);
745 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
746 } else if (Op->isNonConstantNegative()) {
747 // Instead of doing a negate and add, just do a subtract.
748 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
749 Sum = InsertNoopCastOfTo(Sum, Ty);
750 Sum = InsertBinop(Instruction::Sub, Sum, W);
754 Value *W = expandCodeFor(Op, Ty);
755 Sum = InsertNoopCastOfTo(Sum, Ty);
756 // Canonicalize a constant to the RHS.
757 if (isa<Constant>(Sum)) std::swap(Sum, W);
758 Sum = InsertBinop(Instruction::Add, Sum, W);
766 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
767 Type *Ty = SE.getEffectiveSCEVType(S->getType());
769 // Collect all the mul operands in a loop, along with their associated loops.
770 // Iterate in reverse so that constants are emitted last, all else equal.
771 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
772 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
773 E(S->op_begin()); I != E; ++I)
774 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
776 // Sort by loop. Use a stable sort so that constants follow non-constants.
777 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(*SE.DT));
779 // Emit instructions to mul all the operands. Hoist as much as possible
782 for (SmallVectorImpl<std::pair<const Loop *, const SCEV *> >::iterator
783 I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E; ) {
784 const SCEV *Op = I->second;
786 // This is the first operand. Just expand it.
789 } else if (Op->isAllOnesValue()) {
790 // Instead of doing a multiply by negative one, just do a negate.
791 Prod = InsertNoopCastOfTo(Prod, Ty);
792 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
796 Value *W = expandCodeFor(Op, Ty);
797 Prod = InsertNoopCastOfTo(Prod, Ty);
798 // Canonicalize a constant to the RHS.
799 if (isa<Constant>(Prod)) std::swap(Prod, W);
800 Prod = InsertBinop(Instruction::Mul, Prod, W);
808 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
809 Type *Ty = SE.getEffectiveSCEVType(S->getType());
811 Value *LHS = expandCodeFor(S->getLHS(), Ty);
812 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
813 const APInt &RHS = SC->getValue()->getValue();
814 if (RHS.isPowerOf2())
815 return InsertBinop(Instruction::LShr, LHS,
816 ConstantInt::get(Ty, RHS.logBase2()));
819 Value *RHS = expandCodeFor(S->getRHS(), Ty);
820 return InsertBinop(Instruction::UDiv, LHS, RHS);
823 /// Move parts of Base into Rest to leave Base with the minimal
824 /// expression that provides a pointer operand suitable for a
826 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
827 ScalarEvolution &SE) {
828 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
829 Base = A->getStart();
830 Rest = SE.getAddExpr(Rest,
831 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
832 A->getStepRecurrence(SE),
834 // FIXME: A->getNoWrapFlags(FlagNW)
837 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
838 Base = A->getOperand(A->getNumOperands()-1);
839 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
840 NewAddOps.back() = Rest;
841 Rest = SE.getAddExpr(NewAddOps);
842 ExposePointerBase(Base, Rest, SE);
846 /// Determine if this is a well-behaved chain of instructions leading back to
847 /// the PHI. If so, it may be reused by expanded expressions.
848 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
850 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
851 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
853 // If any of the operands don't dominate the insert position, bail.
854 // Addrec operands are always loop-invariant, so this can only happen
855 // if there are instructions which haven't been hoisted.
856 if (L == IVIncInsertLoop) {
857 for (User::op_iterator OI = IncV->op_begin()+1,
858 OE = IncV->op_end(); OI != OE; ++OI)
859 if (Instruction *OInst = dyn_cast<Instruction>(OI))
860 if (!SE.DT->dominates(OInst, IVIncInsertPos))
863 // Advance to the next instruction.
864 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
868 if (IncV->mayHaveSideEffects())
874 return isNormalAddRecExprPHI(PN, IncV, L);
877 /// getIVIncOperand returns an induction variable increment's induction
878 /// variable operand.
880 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
881 /// operands dominate InsertPos.
883 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
884 /// simple patterns generated by getAddRecExprPHILiterally and
885 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
886 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
887 Instruction *InsertPos,
889 if (IncV == InsertPos)
892 switch (IncV->getOpcode()) {
895 // Check for a simple Add/Sub or GEP of a loop invariant step.
896 case Instruction::Add:
897 case Instruction::Sub: {
898 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
899 if (!OInst || SE.DT->properlyDominates(OInst, InsertPos))
900 return dyn_cast<Instruction>(IncV->getOperand(0));
903 case Instruction::BitCast:
904 return dyn_cast<Instruction>(IncV->getOperand(0));
905 case Instruction::GetElementPtr:
906 for (Instruction::op_iterator I = IncV->op_begin()+1, E = IncV->op_end();
908 if (isa<Constant>(*I))
910 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
911 if (!SE.DT->properlyDominates(OInst, InsertPos))
915 // allow any kind of GEP as long as it can be hoisted.
918 // This must be a pointer addition of constants (pretty), which is already
919 // handled, or some number of address-size elements (ugly). Ugly geps
920 // have 2 operands. i1* is used by the expander to represent an
921 // address-size element.
922 if (IncV->getNumOperands() != 2)
924 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
925 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
926 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
930 return dyn_cast<Instruction>(IncV->getOperand(0));
934 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
935 /// it available to other uses in this loop. Recursively hoist any operands,
936 /// until we reach a value that dominates InsertPos.
937 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
938 if (SE.DT->properlyDominates(IncV, InsertPos))
941 // InsertPos must itself dominate IncV so that IncV's new position satisfies
942 // its existing users.
943 if (!SE.DT->dominates(InsertPos->getParent(), IncV->getParent()))
946 // Check that the chain of IV operands leading back to Phi can be hoisted.
947 SmallVector<Instruction*, 4> IVIncs;
949 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
952 // IncV is safe to hoist.
953 IVIncs.push_back(IncV);
955 if (SE.DT->properlyDominates(IncV, InsertPos))
958 for (SmallVectorImpl<Instruction*>::reverse_iterator I = IVIncs.rbegin(),
959 E = IVIncs.rend(); I != E; ++I) {
960 (*I)->moveBefore(InsertPos);
965 /// Determine if this cyclic phi is in a form that would have been generated by
966 /// LSR. We don't care if the phi was actually expanded in this pass, as long
967 /// as it is in a low-cost form, for example, no implied multiplication. This
968 /// should match any patterns generated by getAddRecExprPHILiterally and
970 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
972 for(Instruction *IVOper = IncV;
973 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
974 /*allowScale=*/false));) {
981 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
982 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
983 /// need to materialize IV increments elsewhere to handle difficult situations.
984 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
985 Type *ExpandTy, Type *IntTy,
988 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
989 if (ExpandTy->isPointerTy()) {
990 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
991 // If the step isn't constant, don't use an implicitly scaled GEP, because
992 // that would require a multiply inside the loop.
993 if (!isa<ConstantInt>(StepV))
994 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
995 GEPPtrTy->getAddressSpace());
996 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
997 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
998 if (IncV->getType() != PN->getType()) {
999 IncV = Builder.CreateBitCast(IncV, PN->getType());
1000 rememberInstruction(IncV);
1003 IncV = useSubtract ?
1004 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
1005 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
1006 rememberInstruction(IncV);
1011 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1012 /// the base addrec, which is the addrec without any non-loop-dominating
1013 /// values, and return the PHI.
1015 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1019 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1021 // Reuse a previously-inserted PHI, if present.
1022 BasicBlock *LatchBlock = L->getLoopLatch();
1024 for (BasicBlock::iterator I = L->getHeader()->begin();
1025 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1026 if (!SE.isSCEVable(PN->getType()) ||
1027 (SE.getEffectiveSCEVType(PN->getType()) !=
1028 SE.getEffectiveSCEVType(Normalized->getType())) ||
1029 SE.getSCEV(PN) != Normalized)
1033 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1036 if (!isExpandedAddRecExprPHI(PN, IncV, L))
1038 if (L == IVIncInsertLoop && !hoistIVInc(IncV, IVIncInsertPos))
1042 if (!isNormalAddRecExprPHI(PN, IncV, L))
1044 if (L == IVIncInsertLoop)
1046 if (SE.DT->dominates(IncV, IVIncInsertPos))
1048 // Make sure the increment is where we want it. But don't move it
1049 // down past a potential existing post-inc user.
1050 IncV->moveBefore(IVIncInsertPos);
1051 IVIncInsertPos = IncV;
1052 IncV = cast<Instruction>(IncV->getOperand(0));
1053 } while (IncV != PN);
1055 // Ok, the add recurrence looks usable.
1056 // Remember this PHI, even in post-inc mode.
1057 InsertedValues.insert(PN);
1058 // Remember the increment.
1059 rememberInstruction(IncV);
1064 // Save the original insertion point so we can restore it when we're done.
1065 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1066 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1068 // Another AddRec may need to be recursively expanded below. For example, if
1069 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1070 // loop. Remove this loop from the PostIncLoops set before expanding such
1071 // AddRecs. Otherwise, we cannot find a valid position for the step
1072 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1073 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1074 // so it's not worth implementing SmallPtrSet::swap.
1075 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1076 PostIncLoops.clear();
1078 // Expand code for the start value.
1079 Value *StartV = expandCodeFor(Normalized->getStart(), ExpandTy,
1080 L->getHeader()->begin());
1082 // StartV must be hoisted into L's preheader to dominate the new phi.
1083 assert(!isa<Instruction>(StartV) ||
1084 SE.DT->properlyDominates(cast<Instruction>(StartV)->getParent(),
1087 // Expand code for the step value. Do this before creating the PHI so that PHI
1088 // reuse code doesn't see an incomplete PHI.
1089 const SCEV *Step = Normalized->getStepRecurrence(SE);
1090 // If the stride is negative, insert a sub instead of an add for the increment
1091 // (unless it's a constant, because subtracts of constants are canonicalized
1093 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1095 Step = SE.getNegativeSCEV(Step);
1096 // Expand the step somewhere that dominates the loop header.
1097 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1100 BasicBlock *Header = L->getHeader();
1101 Builder.SetInsertPoint(Header, Header->begin());
1102 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1103 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1104 Twine(IVName) + ".iv");
1105 rememberInstruction(PN);
1107 // Create the step instructions and populate the PHI.
1108 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1109 BasicBlock *Pred = *HPI;
1111 // Add a start value.
1112 if (!L->contains(Pred)) {
1113 PN->addIncoming(StartV, Pred);
1117 // Create a step value and add it to the PHI.
1118 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1119 // instructions at IVIncInsertPos.
1120 Instruction *InsertPos = L == IVIncInsertLoop ?
1121 IVIncInsertPos : Pred->getTerminator();
1122 Builder.SetInsertPoint(InsertPos);
1123 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1125 PN->addIncoming(IncV, Pred);
1128 // Restore the original insert point.
1130 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1132 // After expanding subexpressions, restore the PostIncLoops set so the caller
1133 // can ensure that IVIncrement dominates the current uses.
1134 PostIncLoops = SavedPostIncLoops;
1136 // Remember this PHI, even in post-inc mode.
1137 InsertedValues.insert(PN);
1142 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1143 Type *STy = S->getType();
1144 Type *IntTy = SE.getEffectiveSCEVType(STy);
1145 const Loop *L = S->getLoop();
1147 // Determine a normalized form of this expression, which is the expression
1148 // before any post-inc adjustment is made.
1149 const SCEVAddRecExpr *Normalized = S;
1150 if (PostIncLoops.count(L)) {
1151 PostIncLoopSet Loops;
1154 cast<SCEVAddRecExpr>(TransformForPostIncUse(Normalize, S, 0, 0,
1155 Loops, SE, *SE.DT));
1158 // Strip off any non-loop-dominating component from the addrec start.
1159 const SCEV *Start = Normalized->getStart();
1160 const SCEV *PostLoopOffset = 0;
1161 if (!SE.properlyDominates(Start, L->getHeader())) {
1162 PostLoopOffset = Start;
1163 Start = SE.getConstant(Normalized->getType(), 0);
1164 Normalized = cast<SCEVAddRecExpr>(
1165 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1166 Normalized->getLoop(),
1167 // FIXME: Normalized->getNoWrapFlags(FlagNW)
1168 SCEV::FlagAnyWrap));
1171 // Strip off any non-loop-dominating component from the addrec step.
1172 const SCEV *Step = Normalized->getStepRecurrence(SE);
1173 const SCEV *PostLoopScale = 0;
1174 if (!SE.dominates(Step, L->getHeader())) {
1175 PostLoopScale = Step;
1176 Step = SE.getConstant(Normalized->getType(), 1);
1178 cast<SCEVAddRecExpr>(SE.getAddRecExpr(Start, Step,
1179 Normalized->getLoop(),
1180 // FIXME: Normalized
1181 // ->getNoWrapFlags(FlagNW)
1182 SCEV::FlagAnyWrap));
1185 // Expand the core addrec. If we need post-loop scaling, force it to
1186 // expand to an integer type to avoid the need for additional casting.
1187 Type *ExpandTy = PostLoopScale ? IntTy : STy;
1188 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy);
1190 // Accommodate post-inc mode, if necessary.
1192 if (!PostIncLoops.count(L))
1195 // In PostInc mode, use the post-incremented value.
1196 BasicBlock *LatchBlock = L->getLoopLatch();
1197 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1198 Result = PN->getIncomingValueForBlock(LatchBlock);
1200 // For an expansion to use the postinc form, the client must call
1201 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1202 // or dominated by IVIncInsertPos.
1203 if (isa<Instruction>(Result)
1204 && !SE.DT->dominates(cast<Instruction>(Result),
1205 Builder.GetInsertPoint())) {
1206 // The induction variable's postinc expansion does not dominate this use.
1207 // IVUsers tries to prevent this case, so it is rare. However, it can
1208 // happen when an IVUser outside the loop is not dominated by the latch
1209 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1210 // all cases. Consider a phi outide whose operand is replaced during
1211 // expansion with the value of the postinc user. Without fundamentally
1212 // changing the way postinc users are tracked, the only remedy is
1213 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1214 // but hopefully expandCodeFor handles that.
1216 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1218 Step = SE.getNegativeSCEV(Step);
1219 // Expand the step somewhere that dominates the loop header.
1220 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1221 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1222 Value *StepV = expandCodeFor(Step, IntTy, L->getHeader()->begin());
1223 // Restore the insertion point to the place where the caller has
1224 // determined dominates all uses.
1225 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1226 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1230 // Re-apply any non-loop-dominating scale.
1231 if (PostLoopScale) {
1232 Result = InsertNoopCastOfTo(Result, IntTy);
1233 Result = Builder.CreateMul(Result,
1234 expandCodeFor(PostLoopScale, IntTy));
1235 rememberInstruction(Result);
1238 // Re-apply any non-loop-dominating offset.
1239 if (PostLoopOffset) {
1240 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1241 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1242 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1244 Result = InsertNoopCastOfTo(Result, IntTy);
1245 Result = Builder.CreateAdd(Result,
1246 expandCodeFor(PostLoopOffset, IntTy));
1247 rememberInstruction(Result);
1254 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1255 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1257 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1258 const Loop *L = S->getLoop();
1260 // First check for an existing canonical IV in a suitable type.
1261 PHINode *CanonicalIV = 0;
1262 if (PHINode *PN = L->getCanonicalInductionVariable())
1263 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1266 // Rewrite an AddRec in terms of the canonical induction variable, if
1267 // its type is more narrow.
1269 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1270 SE.getTypeSizeInBits(Ty)) {
1271 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1272 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1273 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1274 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1275 // FIXME: S->getNoWrapFlags(FlagNW)
1276 SCEV::FlagAnyWrap));
1277 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1278 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1279 BasicBlock::iterator NewInsertPt =
1280 llvm::next(BasicBlock::iterator(cast<Instruction>(V)));
1281 while (isa<PHINode>(NewInsertPt) || isa<DbgInfoIntrinsic>(NewInsertPt) ||
1282 isa<LandingPadInst>(NewInsertPt))
1284 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), 0,
1286 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1290 // {X,+,F} --> X + {0,+,F}
1291 if (!S->getStart()->isZero()) {
1292 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1293 NewOps[0] = SE.getConstant(Ty, 0);
1294 // FIXME: can use S->getNoWrapFlags()
1295 const SCEV *Rest = SE.getAddRecExpr(NewOps, L, SCEV::FlagAnyWrap);
1297 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1298 // comments on expandAddToGEP for details.
1299 const SCEV *Base = S->getStart();
1300 const SCEV *RestArray[1] = { Rest };
1301 // Dig into the expression to find the pointer base for a GEP.
1302 ExposePointerBase(Base, RestArray[0], SE);
1303 // If we found a pointer, expand the AddRec with a GEP.
1304 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1305 // Make sure the Base isn't something exotic, such as a multiplied
1306 // or divided pointer value. In those cases, the result type isn't
1307 // actually a pointer type.
1308 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1309 Value *StartV = expand(Base);
1310 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1311 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1315 // Just do a normal add. Pre-expand the operands to suppress folding.
1316 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1317 SE.getUnknown(expand(Rest))));
1320 // If we don't yet have a canonical IV, create one.
1322 // Create and insert the PHI node for the induction variable in the
1324 BasicBlock *Header = L->getHeader();
1325 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1326 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1328 rememberInstruction(CanonicalIV);
1330 Constant *One = ConstantInt::get(Ty, 1);
1331 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1332 BasicBlock *HP = *HPI;
1333 if (L->contains(HP)) {
1334 // Insert a unit add instruction right before the terminator
1335 // corresponding to the back-edge.
1336 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1338 HP->getTerminator());
1339 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1340 rememberInstruction(Add);
1341 CanonicalIV->addIncoming(Add, HP);
1343 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1348 // {0,+,1} --> Insert a canonical induction variable into the loop!
1349 if (S->isAffine() && S->getOperand(1)->isOne()) {
1350 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1351 "IVs with types different from the canonical IV should "
1352 "already have been handled!");
1356 // {0,+,F} --> {0,+,1} * F
1358 // If this is a simple linear addrec, emit it now as a special case.
1359 if (S->isAffine()) // {0,+,F} --> i*F
1361 expand(SE.getTruncateOrNoop(
1362 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1363 SE.getNoopOrAnyExtend(S->getOperand(1),
1364 CanonicalIV->getType())),
1367 // If this is a chain of recurrences, turn it into a closed form, using the
1368 // folders, then expandCodeFor the closed form. This allows the folders to
1369 // simplify the expression without having to build a bunch of special code
1370 // into this folder.
1371 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1373 // Promote S up to the canonical IV type, if the cast is foldable.
1374 const SCEV *NewS = S;
1375 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1376 if (isa<SCEVAddRecExpr>(Ext))
1379 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1380 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1382 // Truncate the result down to the original type, if needed.
1383 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1387 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1388 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1389 Value *V = expandCodeFor(S->getOperand(),
1390 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1391 Value *I = Builder.CreateTrunc(V, Ty);
1392 rememberInstruction(I);
1396 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1397 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1398 Value *V = expandCodeFor(S->getOperand(),
1399 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1400 Value *I = Builder.CreateZExt(V, Ty);
1401 rememberInstruction(I);
1405 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1406 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1407 Value *V = expandCodeFor(S->getOperand(),
1408 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1409 Value *I = Builder.CreateSExt(V, Ty);
1410 rememberInstruction(I);
1414 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1415 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1416 Type *Ty = LHS->getType();
1417 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1418 // In the case of mixed integer and pointer types, do the
1419 // rest of the comparisons as integer.
1420 if (S->getOperand(i)->getType() != Ty) {
1421 Ty = SE.getEffectiveSCEVType(Ty);
1422 LHS = InsertNoopCastOfTo(LHS, Ty);
1424 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1425 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1426 rememberInstruction(ICmp);
1427 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1428 rememberInstruction(Sel);
1431 // In the case of mixed integer and pointer types, cast the
1432 // final result back to the pointer type.
1433 if (LHS->getType() != S->getType())
1434 LHS = InsertNoopCastOfTo(LHS, S->getType());
1438 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1439 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1440 Type *Ty = LHS->getType();
1441 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1442 // In the case of mixed integer and pointer types, do the
1443 // rest of the comparisons as integer.
1444 if (S->getOperand(i)->getType() != Ty) {
1445 Ty = SE.getEffectiveSCEVType(Ty);
1446 LHS = InsertNoopCastOfTo(LHS, Ty);
1448 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1449 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1450 rememberInstruction(ICmp);
1451 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1452 rememberInstruction(Sel);
1455 // In the case of mixed integer and pointer types, cast the
1456 // final result back to the pointer type.
1457 if (LHS->getType() != S->getType())
1458 LHS = InsertNoopCastOfTo(LHS, S->getType());
1462 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1464 Builder.SetInsertPoint(IP->getParent(), IP);
1465 return expandCodeFor(SH, Ty);
1468 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1469 // Expand the code for this SCEV.
1470 Value *V = expand(SH);
1472 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1473 "non-trivial casts should be done with the SCEVs directly!");
1474 V = InsertNoopCastOfTo(V, Ty);
1479 Value *SCEVExpander::expand(const SCEV *S) {
1480 // Compute an insertion point for this SCEV object. Hoist the instructions
1481 // as far out in the loop nest as possible.
1482 Instruction *InsertPt = Builder.GetInsertPoint();
1483 for (Loop *L = SE.LI->getLoopFor(Builder.GetInsertBlock()); ;
1484 L = L->getParentLoop())
1485 if (SE.isLoopInvariant(S, L)) {
1487 if (BasicBlock *Preheader = L->getLoopPreheader())
1488 InsertPt = Preheader->getTerminator();
1490 // LSR sets the insertion point for AddRec start/step values to the
1491 // block start to simplify value reuse, even though it's an invalid
1492 // position. SCEVExpander must correct for this in all cases.
1493 InsertPt = L->getHeader()->getFirstInsertionPt();
1496 // If the SCEV is computable at this level, insert it into the header
1497 // after the PHIs (and after any other instructions that we've inserted
1498 // there) so that it is guaranteed to dominate any user inside the loop.
1499 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1500 InsertPt = L->getHeader()->getFirstInsertionPt();
1501 while (InsertPt != Builder.GetInsertPoint()
1502 && (isInsertedInstruction(InsertPt)
1503 || isa<DbgInfoIntrinsic>(InsertPt))) {
1504 InsertPt = llvm::next(BasicBlock::iterator(InsertPt));
1509 // Check to see if we already expanded this here.
1510 std::map<std::pair<const SCEV *, Instruction *>,
1511 AssertingVH<Value> >::iterator I =
1512 InsertedExpressions.find(std::make_pair(S, InsertPt));
1513 if (I != InsertedExpressions.end())
1516 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1517 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1518 Builder.SetInsertPoint(InsertPt->getParent(), InsertPt);
1520 // Expand the expression into instructions.
1521 Value *V = visit(S);
1523 // Remember the expanded value for this SCEV at this location.
1525 // This is independent of PostIncLoops. The mapped value simply materializes
1526 // the expression at this insertion point. If the mapped value happened to be
1527 // a postinc expansion, it could be reused by a non postinc user, but only if
1528 // its insertion point was already at the head of the loop.
1529 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1531 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1535 void SCEVExpander::rememberInstruction(Value *I) {
1536 if (!PostIncLoops.empty())
1537 InsertedPostIncValues.insert(I);
1539 InsertedValues.insert(I);
1542 void SCEVExpander::restoreInsertPoint(BasicBlock *BB, BasicBlock::iterator I) {
1543 Builder.SetInsertPoint(BB, I);
1546 /// getOrInsertCanonicalInductionVariable - This method returns the
1547 /// canonical induction variable of the specified type for the specified
1548 /// loop (inserting one if there is none). A canonical induction variable
1549 /// starts at zero and steps by one on each iteration.
1551 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1553 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1555 // Build a SCEV for {0,+,1}<L>.
1556 // Conservatively use FlagAnyWrap for now.
1557 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1558 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1560 // Emit code for it.
1561 BasicBlock *SaveInsertBB = Builder.GetInsertBlock();
1562 BasicBlock::iterator SaveInsertPt = Builder.GetInsertPoint();
1563 PHINode *V = cast<PHINode>(expandCodeFor(H, 0, L->getHeader()->begin()));
1565 restoreInsertPoint(SaveInsertBB, SaveInsertPt);
1570 /// Sort values by integer width for replaceCongruentIVs.
1571 static bool width_descending(Value *lhs, Value *rhs) {
1572 // Put pointers at the back and make sure pointer < pointer = false.
1573 if (!lhs->getType()->isIntegerTy() || !rhs->getType()->isIntegerTy())
1574 return rhs->getType()->isIntegerTy() && !lhs->getType()->isIntegerTy();
1575 return rhs->getType()->getPrimitiveSizeInBits()
1576 < lhs->getType()->getPrimitiveSizeInBits();
1579 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1580 /// replace them with their most canonical representative. Return the number of
1581 /// phis eliminated.
1583 /// This does not depend on any SCEVExpander state but should be used in
1584 /// the same context that SCEVExpander is used.
1585 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1586 SmallVectorImpl<WeakVH> &DeadInsts,
1587 const TargetLowering *TLI) {
1588 // Find integer phis in order of increasing width.
1589 SmallVector<PHINode*, 8> Phis;
1590 for (BasicBlock::iterator I = L->getHeader()->begin();
1591 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
1592 Phis.push_back(Phi);
1595 std::sort(Phis.begin(), Phis.end(), width_descending);
1597 unsigned NumElim = 0;
1598 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1599 // Process phis from wide to narrow. Mapping wide phis to the their truncation
1600 // so narrow phis can reuse them.
1601 for (SmallVectorImpl<PHINode*>::const_iterator PIter = Phis.begin(),
1602 PEnd = Phis.end(); PIter != PEnd; ++PIter) {
1603 PHINode *Phi = *PIter;
1605 if (!SE.isSCEVable(Phi->getType()))
1608 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1611 if (Phi->getType()->isIntegerTy() && TLI
1612 && TLI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1613 // This phi can be freely truncated to the narrowest phi type. Map the
1614 // truncated expression to it so it will be reused for narrow types.
1615 const SCEV *TruncExpr =
1616 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1617 ExprToIVMap[TruncExpr] = Phi;
1622 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1624 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1627 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1628 Instruction *OrigInc =
1629 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1630 Instruction *IsomorphicInc =
1631 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1633 // If this phi has the same width but is more canonical, replace the
1634 // original with it. As part of the "more canonical" determination,
1635 // respect a prior decision to use an IV chain.
1636 if (OrigPhiRef->getType() == Phi->getType()
1637 && !(ChainedPhis.count(Phi)
1638 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1639 && (ChainedPhis.count(Phi)
1640 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1641 std::swap(OrigPhiRef, Phi);
1642 std::swap(OrigInc, IsomorphicInc);
1644 // Replacing the congruent phi is sufficient because acyclic redundancy
1645 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1646 // that a phi is congruent, it's often the head of an IV user cycle that
1647 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1648 // common case of a single IV increment so that DeleteDeadPHIs can remove
1649 // cycles that had postinc uses.
1650 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1651 IsomorphicInc->getType());
1652 if (OrigInc != IsomorphicInc
1653 && TruncExpr == SE.getSCEV(IsomorphicInc)
1654 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1655 || hoistIVInc(OrigInc, IsomorphicInc))) {
1656 DEBUG_WITH_TYPE(DebugType, dbgs()
1657 << "INDVARS: Eliminated congruent iv.inc: "
1658 << *IsomorphicInc << '\n');
1659 Value *NewInc = OrigInc;
1660 if (OrigInc->getType() != IsomorphicInc->getType()) {
1661 Instruction *IP = isa<PHINode>(OrigInc)
1662 ? (Instruction*)L->getHeader()->getFirstInsertionPt()
1663 : OrigInc->getNextNode();
1664 IRBuilder<> Builder(IP);
1665 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1667 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1669 IsomorphicInc->replaceAllUsesWith(NewInc);
1670 DeadInsts.push_back(IsomorphicInc);
1673 DEBUG_WITH_TYPE(DebugType, dbgs()
1674 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1676 Value *NewIV = OrigPhiRef;
1677 if (OrigPhiRef->getType() != Phi->getType()) {
1678 IRBuilder<> Builder(L->getHeader()->getFirstInsertionPt());
1679 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1680 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1682 Phi->replaceAllUsesWith(NewIV);
1683 DeadInsts.push_back(Phi);