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/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
32 using namespace PatternMatch;
34 /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
35 /// reusing an existing cast if a suitable one exists, moving an existing
36 /// cast if a suitable one exists but isn't in the right place, or
37 /// creating a new one.
38 Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
39 Instruction::CastOps Op,
40 BasicBlock::iterator IP) {
41 // This function must be called with the builder having a valid insertion
42 // point. It doesn't need to be the actual IP where the uses of the returned
43 // cast will be added, but it must dominate such IP.
44 // We use this precondition to produce a cast that will dominate all its
45 // uses. In particular, this is crucial for the case where the builder's
46 // insertion point *is* the point where we were asked to put the cast.
47 // Since we don't know the builder's insertion point is actually
48 // where the uses will be added (only that it dominates it), we are
49 // not allowed to move it.
50 BasicBlock::iterator BIP = Builder.GetInsertPoint();
52 Instruction *Ret = nullptr;
54 // Check to see if there is already a cast!
55 for (User *U : V->users())
56 if (U->getType() == Ty)
57 if (CastInst *CI = dyn_cast<CastInst>(U))
58 if (CI->getOpcode() == Op) {
59 // If the cast isn't where we want it, create a new cast at IP.
60 // Likewise, do not reuse a cast at BIP because it must dominate
61 // instructions that might be inserted before BIP.
62 if (BasicBlock::iterator(CI) != IP || BIP == IP) {
63 // Create a new cast, and leave the old cast in place in case
64 // it is being used as an insert point. Clear its operand
65 // so that it doesn't hold anything live.
66 Ret = CastInst::Create(Op, V, Ty, "", &*IP);
68 CI->replaceAllUsesWith(Ret);
69 CI->setOperand(0, UndefValue::get(V->getType()));
78 Ret = CastInst::Create(Op, V, Ty, V->getName(), &*IP);
80 // We assert at the end of the function since IP might point to an
81 // instruction with different dominance properties than a cast
82 // (an invoke for example) and not dominate BIP (but the cast does).
83 assert(SE.DT.dominates(Ret, &*BIP));
85 rememberInstruction(Ret);
89 static BasicBlock::iterator findInsertPointAfter(Instruction *I,
90 BasicBlock *MustDominate) {
91 BasicBlock::iterator IP = ++I->getIterator();
92 if (auto *II = dyn_cast<InvokeInst>(I))
93 IP = II->getNormalDest()->begin();
95 while (isa<PHINode>(IP))
98 while (IP->isEHPad()) {
99 if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
101 } else if (auto *TPI = dyn_cast<TerminatePadInst>(IP)) {
102 IP = TPI->getUnwindDest()->getFirstNonPHI()->getIterator();
103 } else if (isa<CatchSwitchInst>(IP)) {
104 IP = MustDominate->getFirstInsertionPt();
106 llvm_unreachable("unexpected eh pad!");
113 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
114 /// which must be possible with a noop cast, doing what we can to share
116 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
117 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
118 assert((Op == Instruction::BitCast ||
119 Op == Instruction::PtrToInt ||
120 Op == Instruction::IntToPtr) &&
121 "InsertNoopCastOfTo cannot perform non-noop casts!");
122 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
123 "InsertNoopCastOfTo cannot change sizes!");
125 // Short-circuit unnecessary bitcasts.
126 if (Op == Instruction::BitCast) {
127 if (V->getType() == Ty)
129 if (CastInst *CI = dyn_cast<CastInst>(V)) {
130 if (CI->getOperand(0)->getType() == Ty)
131 return CI->getOperand(0);
134 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
135 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
136 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
137 if (CastInst *CI = dyn_cast<CastInst>(V))
138 if ((CI->getOpcode() == Instruction::PtrToInt ||
139 CI->getOpcode() == Instruction::IntToPtr) &&
140 SE.getTypeSizeInBits(CI->getType()) ==
141 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
142 return CI->getOperand(0);
143 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
144 if ((CE->getOpcode() == Instruction::PtrToInt ||
145 CE->getOpcode() == Instruction::IntToPtr) &&
146 SE.getTypeSizeInBits(CE->getType()) ==
147 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
148 return CE->getOperand(0);
151 // Fold a cast of a constant.
152 if (Constant *C = dyn_cast<Constant>(V))
153 return ConstantExpr::getCast(Op, C, Ty);
155 // Cast the argument at the beginning of the entry block, after
156 // any bitcasts of other arguments.
157 if (Argument *A = dyn_cast<Argument>(V)) {
158 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
159 while ((isa<BitCastInst>(IP) &&
160 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
161 cast<BitCastInst>(IP)->getOperand(0) != A) ||
162 isa<DbgInfoIntrinsic>(IP))
164 return ReuseOrCreateCast(A, Ty, Op, IP);
167 // Cast the instruction immediately after the instruction.
168 Instruction *I = cast<Instruction>(V);
169 BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
170 return ReuseOrCreateCast(I, Ty, Op, IP);
173 /// InsertBinop - Insert the specified binary operator, doing a small amount
174 /// of work to avoid inserting an obviously redundant operation.
175 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
176 Value *LHS, Value *RHS) {
177 // Fold a binop with constant operands.
178 if (Constant *CLHS = dyn_cast<Constant>(LHS))
179 if (Constant *CRHS = dyn_cast<Constant>(RHS))
180 return ConstantExpr::get(Opcode, CLHS, CRHS);
182 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
183 unsigned ScanLimit = 6;
184 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
185 // Scanning starts from the last instruction before the insertion point.
186 BasicBlock::iterator IP = Builder.GetInsertPoint();
187 if (IP != BlockBegin) {
189 for (; ScanLimit; --IP, --ScanLimit) {
190 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
192 if (isa<DbgInfoIntrinsic>(IP))
194 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
195 IP->getOperand(1) == RHS)
197 if (IP == BlockBegin) break;
201 // Save the original insertion point so we can restore it when we're done.
202 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
203 BuilderType::InsertPointGuard Guard(Builder);
205 // Move the insertion point out of as many loops as we can.
206 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
207 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
208 BasicBlock *Preheader = L->getLoopPreheader();
209 if (!Preheader) break;
211 // Ok, move up a level.
212 Builder.SetInsertPoint(Preheader->getTerminator());
215 // If we haven't found this binop, insert it.
216 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
217 BO->setDebugLoc(Loc);
218 rememberInstruction(BO);
223 /// FactorOutConstant - Test if S is divisible by Factor, using signed
224 /// division. If so, update S with Factor divided out and return true.
225 /// S need not be evenly divisible if a reasonable remainder can be
227 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
228 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
229 /// check to see if the divide was folded.
230 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
231 const SCEV *Factor, ScalarEvolution &SE,
232 const DataLayout &DL) {
233 // Everything is divisible by one.
239 S = SE.getConstant(S->getType(), 1);
243 // For a Constant, check for a multiple of the given factor.
244 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
248 // Check for divisibility.
249 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
251 ConstantInt::get(SE.getContext(),
252 C->getValue()->getValue().sdiv(
253 FC->getValue()->getValue()));
254 // If the quotient is zero and the remainder is non-zero, reject
255 // the value at this scale. It will be considered for subsequent
258 const SCEV *Div = SE.getConstant(CI);
261 SE.getAddExpr(Remainder,
262 SE.getConstant(C->getValue()->getValue().srem(
263 FC->getValue()->getValue())));
269 // In a Mul, check if there is a constant operand which is a multiple
270 // of the given factor.
271 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
272 // Size is known, check if there is a constant operand which is a multiple
273 // of the given factor. If so, we can factor it.
274 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
275 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
276 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
277 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
278 NewMulOps[0] = SE.getConstant(
279 C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
280 S = SE.getMulExpr(NewMulOps);
285 // In an AddRec, check if both start and step are divisible.
286 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
287 const SCEV *Step = A->getStepRecurrence(SE);
288 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
289 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
291 if (!StepRem->isZero())
293 const SCEV *Start = A->getStart();
294 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
296 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
297 A->getNoWrapFlags(SCEV::FlagNW));
304 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
305 /// is the number of SCEVAddRecExprs present, which are kept at the end of
308 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
310 ScalarEvolution &SE) {
311 unsigned NumAddRecs = 0;
312 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
314 // Group Ops into non-addrecs and addrecs.
315 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
316 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
317 // Let ScalarEvolution sort and simplify the non-addrecs list.
318 const SCEV *Sum = NoAddRecs.empty() ?
319 SE.getConstant(Ty, 0) :
320 SE.getAddExpr(NoAddRecs);
321 // If it returned an add, use the operands. Otherwise it simplified
322 // the sum into a single value, so just use that.
324 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
325 Ops.append(Add->op_begin(), Add->op_end());
326 else if (!Sum->isZero())
328 // Then append the addrecs.
329 Ops.append(AddRecs.begin(), AddRecs.end());
332 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
333 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
334 /// This helps expose more opportunities for folding parts of the expressions
335 /// into GEP indices.
337 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
339 ScalarEvolution &SE) {
341 SmallVector<const SCEV *, 8> AddRecs;
342 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
343 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
344 const SCEV *Start = A->getStart();
345 if (Start->isZero()) break;
346 const SCEV *Zero = SE.getConstant(Ty, 0);
347 AddRecs.push_back(SE.getAddRecExpr(Zero,
348 A->getStepRecurrence(SE),
350 A->getNoWrapFlags(SCEV::FlagNW)));
351 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
353 Ops.append(Add->op_begin(), Add->op_end());
354 e += Add->getNumOperands();
359 if (!AddRecs.empty()) {
360 // Add the addrecs onto the end of the list.
361 Ops.append(AddRecs.begin(), AddRecs.end());
362 // Resort the operand list, moving any constants to the front.
363 SimplifyAddOperands(Ops, Ty, SE);
367 /// expandAddToGEP - Expand an addition expression with a pointer type into
368 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
369 /// BasicAliasAnalysis and other passes analyze the result. See the rules
370 /// for getelementptr vs. inttoptr in
371 /// http://llvm.org/docs/LangRef.html#pointeraliasing
374 /// Design note: The correctness of using getelementptr here depends on
375 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
376 /// they may introduce pointer arithmetic which may not be safely converted
377 /// into getelementptr.
379 /// Design note: It might seem desirable for this function to be more
380 /// loop-aware. If some of the indices are loop-invariant while others
381 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
382 /// loop-invariant portions of the overall computation outside the loop.
383 /// However, there are a few reasons this is not done here. Hoisting simple
384 /// arithmetic is a low-level optimization that often isn't very
385 /// important until late in the optimization process. In fact, passes
386 /// like InstructionCombining will combine GEPs, even if it means
387 /// pushing loop-invariant computation down into loops, so even if the
388 /// GEPs were split here, the work would quickly be undone. The
389 /// LoopStrengthReduction pass, which is usually run quite late (and
390 /// after the last InstructionCombining pass), takes care of hoisting
391 /// loop-invariant portions of expressions, after considering what
392 /// can be folded using target addressing modes.
394 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
395 const SCEV *const *op_end,
399 Type *OriginalElTy = PTy->getElementType();
400 Type *ElTy = OriginalElTy;
401 SmallVector<Value *, 4> GepIndices;
402 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
403 bool AnyNonZeroIndices = false;
405 // Split AddRecs up into parts as either of the parts may be usable
406 // without the other.
407 SplitAddRecs(Ops, Ty, SE);
409 Type *IntPtrTy = DL.getIntPtrType(PTy);
411 // Descend down the pointer's type and attempt to convert the other
412 // operands into GEP indices, at each level. The first index in a GEP
413 // indexes into the array implied by the pointer operand; the rest of
414 // the indices index into the element or field type selected by the
417 // If the scale size is not 0, attempt to factor out a scale for
419 SmallVector<const SCEV *, 8> ScaledOps;
420 if (ElTy->isSized()) {
421 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
422 if (!ElSize->isZero()) {
423 SmallVector<const SCEV *, 8> NewOps;
424 for (const SCEV *Op : Ops) {
425 const SCEV *Remainder = SE.getConstant(Ty, 0);
426 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
427 // Op now has ElSize factored out.
428 ScaledOps.push_back(Op);
429 if (!Remainder->isZero())
430 NewOps.push_back(Remainder);
431 AnyNonZeroIndices = true;
433 // The operand was not divisible, so add it to the list of operands
434 // we'll scan next iteration.
435 NewOps.push_back(Op);
438 // If we made any changes, update Ops.
439 if (!ScaledOps.empty()) {
441 SimplifyAddOperands(Ops, Ty, SE);
446 // Record the scaled array index for this level of the type. If
447 // we didn't find any operands that could be factored, tentatively
448 // assume that element zero was selected (since the zero offset
449 // would obviously be folded away).
450 Value *Scaled = ScaledOps.empty() ?
451 Constant::getNullValue(Ty) :
452 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
453 GepIndices.push_back(Scaled);
455 // Collect struct field index operands.
456 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
457 bool FoundFieldNo = false;
458 // An empty struct has no fields.
459 if (STy->getNumElements() == 0) break;
460 // Field offsets are known. See if a constant offset falls within any of
461 // the struct fields.
464 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
465 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
466 const StructLayout &SL = *DL.getStructLayout(STy);
467 uint64_t FullOffset = C->getValue()->getZExtValue();
468 if (FullOffset < SL.getSizeInBytes()) {
469 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
470 GepIndices.push_back(
471 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
472 ElTy = STy->getTypeAtIndex(ElIdx);
474 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
475 AnyNonZeroIndices = true;
479 // If no struct field offsets were found, tentatively assume that
480 // field zero was selected (since the zero offset would obviously
483 ElTy = STy->getTypeAtIndex(0u);
484 GepIndices.push_back(
485 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
489 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
490 ElTy = ATy->getElementType();
495 // If none of the operands were convertible to proper GEP indices, cast
496 // the base to i8* and do an ugly getelementptr with that. It's still
497 // better than ptrtoint+arithmetic+inttoptr at least.
498 if (!AnyNonZeroIndices) {
499 // Cast the base to i8*.
500 V = InsertNoopCastOfTo(V,
501 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
503 assert(!isa<Instruction>(V) ||
504 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
506 // Expand the operands for a plain byte offset.
507 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
509 // Fold a GEP with constant operands.
510 if (Constant *CLHS = dyn_cast<Constant>(V))
511 if (Constant *CRHS = dyn_cast<Constant>(Idx))
512 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
515 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
516 unsigned ScanLimit = 6;
517 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
518 // Scanning starts from the last instruction before the insertion point.
519 BasicBlock::iterator IP = Builder.GetInsertPoint();
520 if (IP != BlockBegin) {
522 for (; ScanLimit; --IP, --ScanLimit) {
523 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
525 if (isa<DbgInfoIntrinsic>(IP))
527 if (IP->getOpcode() == Instruction::GetElementPtr &&
528 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
530 if (IP == BlockBegin) break;
534 // Save the original insertion point so we can restore it when we're done.
535 BuilderType::InsertPointGuard Guard(Builder);
537 // Move the insertion point out of as many loops as we can.
538 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
539 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
540 BasicBlock *Preheader = L->getLoopPreheader();
541 if (!Preheader) break;
543 // Ok, move up a level.
544 Builder.SetInsertPoint(Preheader->getTerminator());
548 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
549 rememberInstruction(GEP);
554 // Save the original insertion point so we can restore it when we're done.
555 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
557 // Move the insertion point out of as many loops as we can.
558 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
559 if (!L->isLoopInvariant(V)) break;
561 bool AnyIndexNotLoopInvariant =
562 std::any_of(GepIndices.begin(), GepIndices.end(),
563 [L](Value *Op) { return !L->isLoopInvariant(Op); });
565 if (AnyIndexNotLoopInvariant)
568 BasicBlock *Preheader = L->getLoopPreheader();
569 if (!Preheader) break;
571 // Ok, move up a level.
572 Builder.SetInsertPoint(Preheader->getTerminator());
575 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
576 // because ScalarEvolution may have changed the address arithmetic to
577 // compute a value which is beyond the end of the allocated object.
579 if (V->getType() != PTy)
580 Casted = InsertNoopCastOfTo(Casted, PTy);
581 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
582 Ops.push_back(SE.getUnknown(GEP));
583 rememberInstruction(GEP);
585 // Restore the original insert point.
586 Builder.restoreIP(SaveInsertPt);
588 return expand(SE.getAddExpr(Ops));
591 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
592 /// SCEV expansion. If they are nested, this is the most nested. If they are
593 /// neighboring, pick the later.
594 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
598 if (A->contains(B)) return B;
599 if (B->contains(A)) return A;
600 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
601 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
602 return A; // Arbitrarily break the tie.
605 /// getRelevantLoop - Get the most relevant loop associated with the given
606 /// expression, according to PickMostRelevantLoop.
607 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
608 // Test whether we've already computed the most relevant loop for this SCEV.
609 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
611 return Pair.first->second;
613 if (isa<SCEVConstant>(S))
614 // A constant has no relevant loops.
616 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
617 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
618 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
619 // A non-instruction has no relevant loops.
622 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
623 const Loop *L = nullptr;
624 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
626 for (const SCEV *Op : N->operands())
627 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
628 return RelevantLoops[N] = L;
630 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
631 const Loop *Result = getRelevantLoop(C->getOperand());
632 return RelevantLoops[C] = Result;
634 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
635 const Loop *Result = PickMostRelevantLoop(
636 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
637 return RelevantLoops[D] = Result;
639 llvm_unreachable("Unexpected SCEV type!");
644 /// LoopCompare - Compare loops by PickMostRelevantLoop.
648 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
650 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
651 std::pair<const Loop *, const SCEV *> RHS) const {
652 // Keep pointer operands sorted at the end.
653 if (LHS.second->getType()->isPointerTy() !=
654 RHS.second->getType()->isPointerTy())
655 return LHS.second->getType()->isPointerTy();
657 // Compare loops with PickMostRelevantLoop.
658 if (LHS.first != RHS.first)
659 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
661 // If one operand is a non-constant negative and the other is not,
662 // put the non-constant negative on the right so that a sub can
663 // be used instead of a negate and add.
664 if (LHS.second->isNonConstantNegative()) {
665 if (!RHS.second->isNonConstantNegative())
667 } else if (RHS.second->isNonConstantNegative())
670 // Otherwise they are equivalent according to this comparison.
677 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
678 Type *Ty = SE.getEffectiveSCEVType(S->getType());
680 // Collect all the add operands in a loop, along with their associated loops.
681 // Iterate in reverse so that constants are emitted last, all else equal, and
682 // so that pointer operands are inserted first, which the code below relies on
683 // to form more involved GEPs.
684 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
685 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
686 E(S->op_begin()); I != E; ++I)
687 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
689 // Sort by loop. Use a stable sort so that constants follow non-constants and
690 // pointer operands precede non-pointer operands.
691 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
693 // Emit instructions to add all the operands. Hoist as much as possible
694 // out of loops, and form meaningful getelementptrs where possible.
695 Value *Sum = nullptr;
696 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
697 const Loop *CurLoop = I->first;
698 const SCEV *Op = I->second;
700 // This is the first operand. Just expand it.
703 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
704 // The running sum expression is a pointer. Try to form a getelementptr
705 // at this level with that as the base.
706 SmallVector<const SCEV *, 4> NewOps;
707 for (; I != E && I->first == CurLoop; ++I) {
708 // If the operand is SCEVUnknown and not instructions, peek through
709 // it, to enable more of it to be folded into the GEP.
710 const SCEV *X = I->second;
711 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
712 if (!isa<Instruction>(U->getValue()))
713 X = SE.getSCEV(U->getValue());
716 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
717 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
718 // The running sum is an integer, and there's a pointer at this level.
719 // Try to form a getelementptr. If the running sum is instructions,
720 // use a SCEVUnknown to avoid re-analyzing them.
721 SmallVector<const SCEV *, 4> NewOps;
722 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
724 for (++I; I != E && I->first == CurLoop; ++I)
725 NewOps.push_back(I->second);
726 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
727 } else if (Op->isNonConstantNegative()) {
728 // Instead of doing a negate and add, just do a subtract.
729 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
730 Sum = InsertNoopCastOfTo(Sum, Ty);
731 Sum = InsertBinop(Instruction::Sub, Sum, W);
735 Value *W = expandCodeFor(Op, Ty);
736 Sum = InsertNoopCastOfTo(Sum, Ty);
737 // Canonicalize a constant to the RHS.
738 if (isa<Constant>(Sum)) std::swap(Sum, W);
739 Sum = InsertBinop(Instruction::Add, Sum, W);
747 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
748 Type *Ty = SE.getEffectiveSCEVType(S->getType());
750 // Collect all the mul operands in a loop, along with their associated loops.
751 // Iterate in reverse so that constants are emitted last, all else equal.
752 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
753 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
754 E(S->op_begin()); I != E; ++I)
755 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
757 // Sort by loop. Use a stable sort so that constants follow non-constants.
758 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
760 // Emit instructions to mul all the operands. Hoist as much as possible
762 Value *Prod = nullptr;
763 for (const auto &I : OpsAndLoops) {
764 const SCEV *Op = I.second;
766 // This is the first operand. Just expand it.
768 } else if (Op->isAllOnesValue()) {
769 // Instead of doing a multiply by negative one, just do a negate.
770 Prod = InsertNoopCastOfTo(Prod, Ty);
771 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
774 Value *W = expandCodeFor(Op, Ty);
775 Prod = InsertNoopCastOfTo(Prod, Ty);
776 // Canonicalize a constant to the RHS.
777 if (isa<Constant>(Prod)) std::swap(Prod, W);
779 if (match(W, m_Power2(RHS))) {
780 // Canonicalize Prod*(1<<C) to Prod<<C.
781 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
782 Prod = InsertBinop(Instruction::Shl, Prod,
783 ConstantInt::get(Ty, RHS->logBase2()));
785 Prod = InsertBinop(Instruction::Mul, Prod, W);
793 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
794 Type *Ty = SE.getEffectiveSCEVType(S->getType());
796 Value *LHS = expandCodeFor(S->getLHS(), Ty);
797 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
798 const APInt &RHS = SC->getValue()->getValue();
799 if (RHS.isPowerOf2())
800 return InsertBinop(Instruction::LShr, LHS,
801 ConstantInt::get(Ty, RHS.logBase2()));
804 Value *RHS = expandCodeFor(S->getRHS(), Ty);
805 return InsertBinop(Instruction::UDiv, LHS, RHS);
808 /// Move parts of Base into Rest to leave Base with the minimal
809 /// expression that provides a pointer operand suitable for a
811 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
812 ScalarEvolution &SE) {
813 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
814 Base = A->getStart();
815 Rest = SE.getAddExpr(Rest,
816 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
817 A->getStepRecurrence(SE),
819 A->getNoWrapFlags(SCEV::FlagNW)));
821 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
822 Base = A->getOperand(A->getNumOperands()-1);
823 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
824 NewAddOps.back() = Rest;
825 Rest = SE.getAddExpr(NewAddOps);
826 ExposePointerBase(Base, Rest, SE);
830 /// Determine if this is a well-behaved chain of instructions leading back to
831 /// the PHI. If so, it may be reused by expanded expressions.
832 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
834 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
835 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
837 // If any of the operands don't dominate the insert position, bail.
838 // Addrec operands are always loop-invariant, so this can only happen
839 // if there are instructions which haven't been hoisted.
840 if (L == IVIncInsertLoop) {
841 for (User::op_iterator OI = IncV->op_begin()+1,
842 OE = IncV->op_end(); OI != OE; ++OI)
843 if (Instruction *OInst = dyn_cast<Instruction>(OI))
844 if (!SE.DT.dominates(OInst, IVIncInsertPos))
847 // Advance to the next instruction.
848 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
852 if (IncV->mayHaveSideEffects())
858 return isNormalAddRecExprPHI(PN, IncV, L);
861 /// getIVIncOperand returns an induction variable increment's induction
862 /// variable operand.
864 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
865 /// operands dominate InsertPos.
867 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
868 /// simple patterns generated by getAddRecExprPHILiterally and
869 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
870 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
871 Instruction *InsertPos,
873 if (IncV == InsertPos)
876 switch (IncV->getOpcode()) {
879 // Check for a simple Add/Sub or GEP of a loop invariant step.
880 case Instruction::Add:
881 case Instruction::Sub: {
882 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
883 if (!OInst || SE.DT.dominates(OInst, InsertPos))
884 return dyn_cast<Instruction>(IncV->getOperand(0));
887 case Instruction::BitCast:
888 return dyn_cast<Instruction>(IncV->getOperand(0));
889 case Instruction::GetElementPtr:
890 for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
891 if (isa<Constant>(*I))
893 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
894 if (!SE.DT.dominates(OInst, InsertPos))
898 // allow any kind of GEP as long as it can be hoisted.
901 // This must be a pointer addition of constants (pretty), which is already
902 // handled, or some number of address-size elements (ugly). Ugly geps
903 // have 2 operands. i1* is used by the expander to represent an
904 // address-size element.
905 if (IncV->getNumOperands() != 2)
907 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
908 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
909 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
913 return dyn_cast<Instruction>(IncV->getOperand(0));
917 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
918 /// it available to other uses in this loop. Recursively hoist any operands,
919 /// until we reach a value that dominates InsertPos.
920 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
921 if (SE.DT.dominates(IncV, InsertPos))
924 // InsertPos must itself dominate IncV so that IncV's new position satisfies
925 // its existing users.
926 if (isa<PHINode>(InsertPos) ||
927 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
930 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
933 // Check that the chain of IV operands leading back to Phi can be hoisted.
934 SmallVector<Instruction*, 4> IVIncs;
936 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
939 // IncV is safe to hoist.
940 IVIncs.push_back(IncV);
942 if (SE.DT.dominates(IncV, InsertPos))
945 for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
946 (*I)->moveBefore(InsertPos);
951 /// Determine if this cyclic phi is in a form that would have been generated by
952 /// LSR. We don't care if the phi was actually expanded in this pass, as long
953 /// as it is in a low-cost form, for example, no implied multiplication. This
954 /// should match any patterns generated by getAddRecExprPHILiterally and
956 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
958 for(Instruction *IVOper = IncV;
959 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
960 /*allowScale=*/false));) {
967 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
968 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
969 /// need to materialize IV increments elsewhere to handle difficult situations.
970 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
971 Type *ExpandTy, Type *IntTy,
974 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
975 if (ExpandTy->isPointerTy()) {
976 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
977 // If the step isn't constant, don't use an implicitly scaled GEP, because
978 // that would require a multiply inside the loop.
979 if (!isa<ConstantInt>(StepV))
980 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
981 GEPPtrTy->getAddressSpace());
982 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
983 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
984 if (IncV->getType() != PN->getType()) {
985 IncV = Builder.CreateBitCast(IncV, PN->getType());
986 rememberInstruction(IncV);
990 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
991 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
992 rememberInstruction(IncV);
997 /// \brief Hoist the addrec instruction chain rooted in the loop phi above the
998 /// position. This routine assumes that this is possible (has been checked).
999 static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
1000 Instruction *Pos, PHINode *LoopPhi) {
1002 if (DT->dominates(InstToHoist, Pos))
1004 // Make sure the increment is where we want it. But don't move it
1005 // down past a potential existing post-inc user.
1006 InstToHoist->moveBefore(Pos);
1008 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1009 } while (InstToHoist != LoopPhi);
1012 /// \brief Check whether we can cheaply express the requested SCEV in terms of
1013 /// the available PHI SCEV by truncation and/or inversion of the step.
1014 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1015 const SCEVAddRecExpr *Phi,
1016 const SCEVAddRecExpr *Requested,
1018 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1019 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1021 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1024 // Try truncate it if necessary.
1025 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1029 // Check whether truncation will help.
1030 if (Phi == Requested) {
1035 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1036 if (SE.getAddExpr(Requested->getStart(),
1037 SE.getNegativeSCEV(Requested)) == Phi) {
1045 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1046 if (!isa<IntegerType>(AR->getType()))
1049 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1050 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1051 const SCEV *Step = AR->getStepRecurrence(SE);
1052 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1053 SE.getSignExtendExpr(AR, WideTy));
1054 const SCEV *ExtendAfterOp =
1055 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1056 return ExtendAfterOp == OpAfterExtend;
1059 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1060 if (!isa<IntegerType>(AR->getType()))
1063 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1064 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1065 const SCEV *Step = AR->getStepRecurrence(SE);
1066 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1067 SE.getZeroExtendExpr(AR, WideTy));
1068 const SCEV *ExtendAfterOp =
1069 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1070 return ExtendAfterOp == OpAfterExtend;
1073 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1074 /// the base addrec, which is the addrec without any non-loop-dominating
1075 /// values, and return the PHI.
1077 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1083 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1085 // Reuse a previously-inserted PHI, if present.
1086 BasicBlock *LatchBlock = L->getLoopLatch();
1088 PHINode *AddRecPhiMatch = nullptr;
1089 Instruction *IncV = nullptr;
1093 // Only try partially matching scevs that need truncation and/or
1094 // step-inversion if we know this loop is outside the current loop.
1095 bool TryNonMatchingSCEV =
1097 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1099 for (auto &I : *L->getHeader()) {
1100 auto *PN = dyn_cast<PHINode>(&I);
1101 if (!PN || !SE.isSCEVable(PN->getType()))
1104 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1108 bool IsMatchingSCEV = PhiSCEV == Normalized;
1109 // We only handle truncation and inversion of phi recurrences for the
1110 // expanded expression if the expanded expression's loop dominates the
1111 // loop we insert to. Check now, so we can bail out early.
1112 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1115 Instruction *TempIncV =
1116 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1118 // Check whether we can reuse this PHI node.
1120 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
1122 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1125 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
1129 // Stop if we have found an exact match SCEV.
1130 if (IsMatchingSCEV) {
1134 AddRecPhiMatch = PN;
1138 // Try whether the phi can be translated into the requested form
1139 // (truncated and/or offset by a constant).
1140 if ((!TruncTy || InvertStep) &&
1141 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1142 // Record the phi node. But don't stop we might find an exact match
1144 AddRecPhiMatch = PN;
1146 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1150 if (AddRecPhiMatch) {
1151 // Potentially, move the increment. We have made sure in
1152 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1153 if (L == IVIncInsertLoop)
1154 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1156 // Ok, the add recurrence looks usable.
1157 // Remember this PHI, even in post-inc mode.
1158 InsertedValues.insert(AddRecPhiMatch);
1159 // Remember the increment.
1160 rememberInstruction(IncV);
1161 return AddRecPhiMatch;
1165 // Save the original insertion point so we can restore it when we're done.
1166 BuilderType::InsertPointGuard Guard(Builder);
1168 // Another AddRec may need to be recursively expanded below. For example, if
1169 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1170 // loop. Remove this loop from the PostIncLoops set before expanding such
1171 // AddRecs. Otherwise, we cannot find a valid position for the step
1172 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1173 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1174 // so it's not worth implementing SmallPtrSet::swap.
1175 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1176 PostIncLoops.clear();
1178 // Expand code for the start value.
1180 expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
1182 // StartV must be hoisted into L's preheader to dominate the new phi.
1183 assert(!isa<Instruction>(StartV) ||
1184 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1187 // Expand code for the step value. Do this before creating the PHI so that PHI
1188 // reuse code doesn't see an incomplete PHI.
1189 const SCEV *Step = Normalized->getStepRecurrence(SE);
1190 // If the stride is negative, insert a sub instead of an add for the increment
1191 // (unless it's a constant, because subtracts of constants are canonicalized
1193 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1195 Step = SE.getNegativeSCEV(Step);
1196 // Expand the step somewhere that dominates the loop header.
1197 Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1199 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1200 // we actually do emit an addition. It does not apply if we emit a
1202 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1203 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1206 BasicBlock *Header = L->getHeader();
1207 Builder.SetInsertPoint(Header, Header->begin());
1208 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1209 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1210 Twine(IVName) + ".iv");
1211 rememberInstruction(PN);
1213 // Create the step instructions and populate the PHI.
1214 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1215 BasicBlock *Pred = *HPI;
1217 // Add a start value.
1218 if (!L->contains(Pred)) {
1219 PN->addIncoming(StartV, Pred);
1223 // Create a step value and add it to the PHI.
1224 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1225 // instructions at IVIncInsertPos.
1226 Instruction *InsertPos = L == IVIncInsertLoop ?
1227 IVIncInsertPos : Pred->getTerminator();
1228 Builder.SetInsertPoint(InsertPos);
1229 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1231 if (isa<OverflowingBinaryOperator>(IncV)) {
1233 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1235 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1237 PN->addIncoming(IncV, Pred);
1240 // After expanding subexpressions, restore the PostIncLoops set so the caller
1241 // can ensure that IVIncrement dominates the current uses.
1242 PostIncLoops = SavedPostIncLoops;
1244 // Remember this PHI, even in post-inc mode.
1245 InsertedValues.insert(PN);
1250 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1251 Type *STy = S->getType();
1252 Type *IntTy = SE.getEffectiveSCEVType(STy);
1253 const Loop *L = S->getLoop();
1255 // Determine a normalized form of this expression, which is the expression
1256 // before any post-inc adjustment is made.
1257 const SCEVAddRecExpr *Normalized = S;
1258 if (PostIncLoops.count(L)) {
1259 PostIncLoopSet Loops;
1261 Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1262 Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
1265 // Strip off any non-loop-dominating component from the addrec start.
1266 const SCEV *Start = Normalized->getStart();
1267 const SCEV *PostLoopOffset = nullptr;
1268 if (!SE.properlyDominates(Start, L->getHeader())) {
1269 PostLoopOffset = Start;
1270 Start = SE.getConstant(Normalized->getType(), 0);
1271 Normalized = cast<SCEVAddRecExpr>(
1272 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1273 Normalized->getLoop(),
1274 Normalized->getNoWrapFlags(SCEV::FlagNW)));
1277 // Strip off any non-loop-dominating component from the addrec step.
1278 const SCEV *Step = Normalized->getStepRecurrence(SE);
1279 const SCEV *PostLoopScale = nullptr;
1280 if (!SE.dominates(Step, L->getHeader())) {
1281 PostLoopScale = Step;
1282 Step = SE.getConstant(Normalized->getType(), 1);
1284 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1285 Start, Step, Normalized->getLoop(),
1286 Normalized->getNoWrapFlags(SCEV::FlagNW)));
1289 // Expand the core addrec. If we need post-loop scaling, force it to
1290 // expand to an integer type to avoid the need for additional casting.
1291 Type *ExpandTy = PostLoopScale ? IntTy : STy;
1292 // In some cases, we decide to reuse an existing phi node but need to truncate
1293 // it and/or invert the step.
1294 Type *TruncTy = nullptr;
1295 bool InvertStep = false;
1296 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1297 TruncTy, InvertStep);
1299 // Accommodate post-inc mode, if necessary.
1301 if (!PostIncLoops.count(L))
1304 // In PostInc mode, use the post-incremented value.
1305 BasicBlock *LatchBlock = L->getLoopLatch();
1306 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1307 Result = PN->getIncomingValueForBlock(LatchBlock);
1309 // For an expansion to use the postinc form, the client must call
1310 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1311 // or dominated by IVIncInsertPos.
1312 if (isa<Instruction>(Result) &&
1313 !SE.DT.dominates(cast<Instruction>(Result),
1314 &*Builder.GetInsertPoint())) {
1315 // The induction variable's postinc expansion does not dominate this use.
1316 // IVUsers tries to prevent this case, so it is rare. However, it can
1317 // happen when an IVUser outside the loop is not dominated by the latch
1318 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1319 // all cases. Consider a phi outide whose operand is replaced during
1320 // expansion with the value of the postinc user. Without fundamentally
1321 // changing the way postinc users are tracked, the only remedy is
1322 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1323 // but hopefully expandCodeFor handles that.
1325 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1327 Step = SE.getNegativeSCEV(Step);
1330 // Expand the step somewhere that dominates the loop header.
1331 BuilderType::InsertPointGuard Guard(Builder);
1332 StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1334 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1338 // We have decided to reuse an induction variable of a dominating loop. Apply
1339 // truncation and/or invertion of the step.
1341 Type *ResTy = Result->getType();
1342 // Normalize the result type.
1343 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1344 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1345 // Truncate the result.
1346 if (TruncTy != Result->getType()) {
1347 Result = Builder.CreateTrunc(Result, TruncTy);
1348 rememberInstruction(Result);
1350 // Invert the result.
1352 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1354 rememberInstruction(Result);
1358 // Re-apply any non-loop-dominating scale.
1359 if (PostLoopScale) {
1360 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1361 Result = InsertNoopCastOfTo(Result, IntTy);
1362 Result = Builder.CreateMul(Result,
1363 expandCodeFor(PostLoopScale, IntTy));
1364 rememberInstruction(Result);
1367 // Re-apply any non-loop-dominating offset.
1368 if (PostLoopOffset) {
1369 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1370 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1371 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1373 Result = InsertNoopCastOfTo(Result, IntTy);
1374 Result = Builder.CreateAdd(Result,
1375 expandCodeFor(PostLoopOffset, IntTy));
1376 rememberInstruction(Result);
1383 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1384 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1386 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1387 const Loop *L = S->getLoop();
1389 // First check for an existing canonical IV in a suitable type.
1390 PHINode *CanonicalIV = nullptr;
1391 if (PHINode *PN = L->getCanonicalInductionVariable())
1392 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1395 // Rewrite an AddRec in terms of the canonical induction variable, if
1396 // its type is more narrow.
1398 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1399 SE.getTypeSizeInBits(Ty)) {
1400 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1401 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1402 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1403 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1404 S->getNoWrapFlags(SCEV::FlagNW)));
1405 BasicBlock::iterator NewInsertPt =
1406 findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1407 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1412 // {X,+,F} --> X + {0,+,F}
1413 if (!S->getStart()->isZero()) {
1414 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1415 NewOps[0] = SE.getConstant(Ty, 0);
1416 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1417 S->getNoWrapFlags(SCEV::FlagNW));
1419 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1420 // comments on expandAddToGEP for details.
1421 const SCEV *Base = S->getStart();
1422 const SCEV *RestArray[1] = { Rest };
1423 // Dig into the expression to find the pointer base for a GEP.
1424 ExposePointerBase(Base, RestArray[0], SE);
1425 // If we found a pointer, expand the AddRec with a GEP.
1426 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1427 // Make sure the Base isn't something exotic, such as a multiplied
1428 // or divided pointer value. In those cases, the result type isn't
1429 // actually a pointer type.
1430 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1431 Value *StartV = expand(Base);
1432 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1433 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1437 // Just do a normal add. Pre-expand the operands to suppress folding.
1438 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1439 SE.getUnknown(expand(Rest))));
1442 // If we don't yet have a canonical IV, create one.
1444 // Create and insert the PHI node for the induction variable in the
1446 BasicBlock *Header = L->getHeader();
1447 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1448 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1450 rememberInstruction(CanonicalIV);
1452 SmallSet<BasicBlock *, 4> PredSeen;
1453 Constant *One = ConstantInt::get(Ty, 1);
1454 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1455 BasicBlock *HP = *HPI;
1456 if (!PredSeen.insert(HP).second) {
1457 // There must be an incoming value for each predecessor, even the
1459 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1463 if (L->contains(HP)) {
1464 // Insert a unit add instruction right before the terminator
1465 // corresponding to the back-edge.
1466 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1468 HP->getTerminator());
1469 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1470 rememberInstruction(Add);
1471 CanonicalIV->addIncoming(Add, HP);
1473 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1478 // {0,+,1} --> Insert a canonical induction variable into the loop!
1479 if (S->isAffine() && S->getOperand(1)->isOne()) {
1480 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1481 "IVs with types different from the canonical IV should "
1482 "already have been handled!");
1486 // {0,+,F} --> {0,+,1} * F
1488 // If this is a simple linear addrec, emit it now as a special case.
1489 if (S->isAffine()) // {0,+,F} --> i*F
1491 expand(SE.getTruncateOrNoop(
1492 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1493 SE.getNoopOrAnyExtend(S->getOperand(1),
1494 CanonicalIV->getType())),
1497 // If this is a chain of recurrences, turn it into a closed form, using the
1498 // folders, then expandCodeFor the closed form. This allows the folders to
1499 // simplify the expression without having to build a bunch of special code
1500 // into this folder.
1501 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1503 // Promote S up to the canonical IV type, if the cast is foldable.
1504 const SCEV *NewS = S;
1505 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1506 if (isa<SCEVAddRecExpr>(Ext))
1509 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1510 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1512 // Truncate the result down to the original type, if needed.
1513 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1517 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1518 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1519 Value *V = expandCodeFor(S->getOperand(),
1520 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1521 Value *I = Builder.CreateTrunc(V, Ty);
1522 rememberInstruction(I);
1526 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1527 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1528 Value *V = expandCodeFor(S->getOperand(),
1529 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1530 Value *I = Builder.CreateZExt(V, Ty);
1531 rememberInstruction(I);
1535 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1536 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1537 Value *V = expandCodeFor(S->getOperand(),
1538 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1539 Value *I = Builder.CreateSExt(V, Ty);
1540 rememberInstruction(I);
1544 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1545 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1546 Type *Ty = LHS->getType();
1547 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1548 // In the case of mixed integer and pointer types, do the
1549 // rest of the comparisons as integer.
1550 if (S->getOperand(i)->getType() != Ty) {
1551 Ty = SE.getEffectiveSCEVType(Ty);
1552 LHS = InsertNoopCastOfTo(LHS, Ty);
1554 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1555 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1556 rememberInstruction(ICmp);
1557 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1558 rememberInstruction(Sel);
1561 // In the case of mixed integer and pointer types, cast the
1562 // final result back to the pointer type.
1563 if (LHS->getType() != S->getType())
1564 LHS = InsertNoopCastOfTo(LHS, S->getType());
1568 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1569 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1570 Type *Ty = LHS->getType();
1571 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1572 // In the case of mixed integer and pointer types, do the
1573 // rest of the comparisons as integer.
1574 if (S->getOperand(i)->getType() != Ty) {
1575 Ty = SE.getEffectiveSCEVType(Ty);
1576 LHS = InsertNoopCastOfTo(LHS, Ty);
1578 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1579 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1580 rememberInstruction(ICmp);
1581 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1582 rememberInstruction(Sel);
1585 // In the case of mixed integer and pointer types, cast the
1586 // final result back to the pointer type.
1587 if (LHS->getType() != S->getType())
1588 LHS = InsertNoopCastOfTo(LHS, S->getType());
1592 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1595 Builder.SetInsertPoint(IP);
1596 return expandCodeFor(SH, Ty);
1599 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1600 // Expand the code for this SCEV.
1601 Value *V = expand(SH);
1603 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1604 "non-trivial casts should be done with the SCEVs directly!");
1605 V = InsertNoopCastOfTo(V, Ty);
1610 Value *SCEVExpander::expand(const SCEV *S) {
1611 // Compute an insertion point for this SCEV object. Hoist the instructions
1612 // as far out in the loop nest as possible.
1613 Instruction *InsertPt = &*Builder.GetInsertPoint();
1614 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1615 L = L->getParentLoop())
1616 if (SE.isLoopInvariant(S, L)) {
1618 if (BasicBlock *Preheader = L->getLoopPreheader())
1619 InsertPt = Preheader->getTerminator();
1621 // LSR sets the insertion point for AddRec start/step values to the
1622 // block start to simplify value reuse, even though it's an invalid
1623 // position. SCEVExpander must correct for this in all cases.
1624 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1627 // If the SCEV is computable at this level, insert it into the header
1628 // after the PHIs (and after any other instructions that we've inserted
1629 // there) so that it is guaranteed to dominate any user inside the loop.
1630 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1631 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1632 while (InsertPt != Builder.GetInsertPoint()
1633 && (isInsertedInstruction(InsertPt)
1634 || isa<DbgInfoIntrinsic>(InsertPt))) {
1635 InsertPt = &*std::next(InsertPt->getIterator());
1640 // Check to see if we already expanded this here.
1641 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1642 if (I != InsertedExpressions.end())
1645 BuilderType::InsertPointGuard Guard(Builder);
1646 Builder.SetInsertPoint(InsertPt);
1648 // Expand the expression into instructions.
1649 Value *V = visit(S);
1651 // Remember the expanded value for this SCEV at this location.
1653 // This is independent of PostIncLoops. The mapped value simply materializes
1654 // the expression at this insertion point. If the mapped value happened to be
1655 // a postinc expansion, it could be reused by a non-postinc user, but only if
1656 // its insertion point was already at the head of the loop.
1657 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1661 void SCEVExpander::rememberInstruction(Value *I) {
1662 if (!PostIncLoops.empty())
1663 InsertedPostIncValues.insert(I);
1665 InsertedValues.insert(I);
1668 /// getOrInsertCanonicalInductionVariable - This method returns the
1669 /// canonical induction variable of the specified type for the specified
1670 /// loop (inserting one if there is none). A canonical induction variable
1671 /// starts at zero and steps by one on each iteration.
1673 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1675 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1677 // Build a SCEV for {0,+,1}<L>.
1678 // Conservatively use FlagAnyWrap for now.
1679 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1680 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1682 // Emit code for it.
1683 BuilderType::InsertPointGuard Guard(Builder);
1685 cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1690 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1691 /// replace them with their most canonical representative. Return the number of
1692 /// phis eliminated.
1694 /// This does not depend on any SCEVExpander state but should be used in
1695 /// the same context that SCEVExpander is used.
1696 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1697 SmallVectorImpl<WeakVH> &DeadInsts,
1698 const TargetTransformInfo *TTI) {
1699 // Find integer phis in order of increasing width.
1700 SmallVector<PHINode*, 8> Phis;
1701 for (auto &I : *L->getHeader()) {
1702 if (auto *PN = dyn_cast<PHINode>(&I))
1709 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1710 // Put pointers at the back and make sure pointer < pointer = false.
1711 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1712 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1713 return RHS->getType()->getPrimitiveSizeInBits() <
1714 LHS->getType()->getPrimitiveSizeInBits();
1717 unsigned NumElim = 0;
1718 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1719 // Process phis from wide to narrow. Map wide phis to their truncation
1720 // so narrow phis can reuse them.
1721 for (PHINode *Phi : Phis) {
1722 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1723 if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1725 if (!SE.isSCEVable(PN->getType()))
1727 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1730 return Const->getValue();
1733 // Fold constant phis. They may be congruent to other constant phis and
1734 // would confuse the logic below that expects proper IVs.
1735 if (Value *V = SimplifyPHINode(Phi)) {
1736 if (V->getType() != Phi->getType())
1738 Phi->replaceAllUsesWith(V);
1739 DeadInsts.emplace_back(Phi);
1741 DEBUG_WITH_TYPE(DebugType, dbgs()
1742 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1746 if (!SE.isSCEVable(Phi->getType()))
1749 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1752 if (Phi->getType()->isIntegerTy() && TTI
1753 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1754 // This phi can be freely truncated to the narrowest phi type. Map the
1755 // truncated expression to it so it will be reused for narrow types.
1756 const SCEV *TruncExpr =
1757 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1758 ExprToIVMap[TruncExpr] = Phi;
1763 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1765 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1768 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1769 Instruction *OrigInc =
1770 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1771 Instruction *IsomorphicInc =
1772 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1774 // If this phi has the same width but is more canonical, replace the
1775 // original with it. As part of the "more canonical" determination,
1776 // respect a prior decision to use an IV chain.
1777 if (OrigPhiRef->getType() == Phi->getType()
1778 && !(ChainedPhis.count(Phi)
1779 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1780 && (ChainedPhis.count(Phi)
1781 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1782 std::swap(OrigPhiRef, Phi);
1783 std::swap(OrigInc, IsomorphicInc);
1785 // Replacing the congruent phi is sufficient because acyclic redundancy
1786 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1787 // that a phi is congruent, it's often the head of an IV user cycle that
1788 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1789 // common case of a single IV increment so that DeleteDeadPHIs can remove
1790 // cycles that had postinc uses.
1791 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1792 IsomorphicInc->getType());
1793 if (OrigInc != IsomorphicInc
1794 && TruncExpr == SE.getSCEV(IsomorphicInc)
1795 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1796 || hoistIVInc(OrigInc, IsomorphicInc))) {
1797 DEBUG_WITH_TYPE(DebugType, dbgs()
1798 << "INDVARS: Eliminated congruent iv.inc: "
1799 << *IsomorphicInc << '\n');
1800 Value *NewInc = OrigInc;
1801 if (OrigInc->getType() != IsomorphicInc->getType()) {
1802 Instruction *IP = nullptr;
1803 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1804 IP = &*PN->getParent()->getFirstInsertionPt();
1806 IP = OrigInc->getNextNode();
1808 IRBuilder<> Builder(IP);
1809 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1811 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1813 IsomorphicInc->replaceAllUsesWith(NewInc);
1814 DeadInsts.emplace_back(IsomorphicInc);
1817 DEBUG_WITH_TYPE(DebugType, dbgs()
1818 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1820 Value *NewIV = OrigPhiRef;
1821 if (OrigPhiRef->getType() != Phi->getType()) {
1822 IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
1823 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1824 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1826 Phi->replaceAllUsesWith(NewIV);
1827 DeadInsts.emplace_back(Phi);
1832 Value *SCEVExpander::findExistingExpansion(const SCEV *S,
1833 const Instruction *At, Loop *L) {
1834 using namespace llvm::PatternMatch;
1836 SmallVector<BasicBlock *, 4> ExitingBlocks;
1837 L->getExitingBlocks(ExitingBlocks);
1839 // Look for suitable value in simple conditions at the loop exits.
1840 for (BasicBlock *BB : ExitingBlocks) {
1841 ICmpInst::Predicate Pred;
1842 Instruction *LHS, *RHS;
1843 BasicBlock *TrueBB, *FalseBB;
1845 if (!match(BB->getTerminator(),
1846 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1850 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1853 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1857 // There is potential to make this significantly smarter, but this simple
1858 // heuristic already gets some interesting cases.
1860 // Can not find suitable value.
1864 bool SCEVExpander::isHighCostExpansionHelper(
1865 const SCEV *S, Loop *L, const Instruction *At,
1866 SmallPtrSetImpl<const SCEV *> &Processed) {
1868 // If we can find an existing value for this scev avaliable at the point "At"
1869 // then consider the expression cheap.
1870 if (At && findExistingExpansion(S, At, L) != nullptr)
1873 // Zero/One operand expressions
1874 switch (S->getSCEVType()) {
1879 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1882 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1885 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1889 if (!Processed.insert(S).second)
1892 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1893 // If the divisor is a power of two and the SCEV type fits in a native
1894 // integer, consider the division cheap irrespective of whether it occurs in
1895 // the user code since it can be lowered into a right shift.
1896 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1897 if (SC->getValue()->getValue().isPowerOf2()) {
1898 const DataLayout &DL =
1899 L->getHeader()->getParent()->getParent()->getDataLayout();
1900 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1901 return DL.isIllegalInteger(Width);
1904 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1905 // HowManyLessThans produced to compute a precise expression, rather than a
1906 // UDiv from the user's code. If we can't find a UDiv in the code with some
1907 // simple searching, assume the former consider UDivExpr expensive to
1909 BasicBlock *ExitingBB = L->getExitingBlock();
1913 // At the beginning of this function we already tried to find existing value
1914 // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1915 // involving division. This is just a simple search heuristic.
1917 At = &ExitingBB->back();
1918 if (!findExistingExpansion(
1919 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
1923 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1924 // the exit condition.
1925 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1928 // Recurse past nary expressions, which commonly occur in the
1929 // BackedgeTakenCount. They may already exist in program code, and if not,
1930 // they are not too expensive rematerialize.
1931 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1932 for (auto *Op : NAry->operands())
1933 if (isHighCostExpansionHelper(Op, L, At, Processed))
1937 // If we haven't recognized an expensive SCEV pattern, assume it's an
1938 // expression produced by program code.
1942 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
1945 switch (Pred->getKind()) {
1946 case SCEVPredicate::P_Union:
1947 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
1948 case SCEVPredicate::P_Equal:
1949 return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
1951 llvm_unreachable("Unknown SCEV predicate type");
1954 Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
1956 Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
1957 Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
1959 Builder.SetInsertPoint(IP);
1960 auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
1964 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
1966 auto *BoolType = IntegerType::get(IP->getContext(), 1);
1967 Value *Check = ConstantInt::getNullValue(BoolType);
1969 // Loop over all checks in this set.
1970 for (auto Pred : Union->getPredicates()) {
1971 auto *NextCheck = expandCodeForPredicate(Pred, IP);
1972 Builder.SetInsertPoint(IP);
1973 Check = Builder.CreateOr(Check, NextCheck);
1980 // Search for a SCEV subexpression that is not safe to expand. Any expression
1981 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1982 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
1983 // instruction, but the important thing is that we prove the denominator is
1984 // nonzero before expansion.
1986 // IVUsers already checks that IV-derived expressions are safe. So this check is
1987 // only needed when the expression includes some subexpression that is not IV
1990 // Currently, we only allow division by a nonzero constant here. If this is
1991 // inadequate, we could easily allow division by SCEVUnknown by using
1992 // ValueTracking to check isKnownNonZero().
1994 // We cannot generally expand recurrences unless the step dominates the loop
1995 // header. The expander handles the special case of affine recurrences by
1996 // scaling the recurrence outside the loop, but this technique isn't generally
1997 // applicable. Expanding a nested recurrence outside a loop requires computing
1998 // binomial coefficients. This could be done, but the recurrence has to be in a
1999 // perfectly reduced form, which can't be guaranteed.
2000 struct SCEVFindUnsafe {
2001 ScalarEvolution &SE;
2004 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
2006 bool follow(const SCEV *S) {
2007 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2008 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2009 if (!SC || SC->getValue()->isZero()) {
2014 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2015 const SCEV *Step = AR->getStepRecurrence(SE);
2016 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2023 bool isDone() const { return IsUnsafe; }
2028 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2029 SCEVFindUnsafe Search(SE);
2030 visitAll(S, Search);
2031 return !Search.IsUnsafe;