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 (isa<CatchSwitchInst>(IP)) {
102 IP = MustDominate->getFirstInsertionPt();
104 llvm_unreachable("unexpected eh pad!");
111 /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
112 /// which must be possible with a noop cast, doing what we can to share
114 Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
115 Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
116 assert((Op == Instruction::BitCast ||
117 Op == Instruction::PtrToInt ||
118 Op == Instruction::IntToPtr) &&
119 "InsertNoopCastOfTo cannot perform non-noop casts!");
120 assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
121 "InsertNoopCastOfTo cannot change sizes!");
123 // Short-circuit unnecessary bitcasts.
124 if (Op == Instruction::BitCast) {
125 if (V->getType() == Ty)
127 if (CastInst *CI = dyn_cast<CastInst>(V)) {
128 if (CI->getOperand(0)->getType() == Ty)
129 return CI->getOperand(0);
132 // Short-circuit unnecessary inttoptr<->ptrtoint casts.
133 if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
134 SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
135 if (CastInst *CI = dyn_cast<CastInst>(V))
136 if ((CI->getOpcode() == Instruction::PtrToInt ||
137 CI->getOpcode() == Instruction::IntToPtr) &&
138 SE.getTypeSizeInBits(CI->getType()) ==
139 SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
140 return CI->getOperand(0);
141 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
142 if ((CE->getOpcode() == Instruction::PtrToInt ||
143 CE->getOpcode() == Instruction::IntToPtr) &&
144 SE.getTypeSizeInBits(CE->getType()) ==
145 SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
146 return CE->getOperand(0);
149 // Fold a cast of a constant.
150 if (Constant *C = dyn_cast<Constant>(V))
151 return ConstantExpr::getCast(Op, C, Ty);
153 // Cast the argument at the beginning of the entry block, after
154 // any bitcasts of other arguments.
155 if (Argument *A = dyn_cast<Argument>(V)) {
156 BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
157 while ((isa<BitCastInst>(IP) &&
158 isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
159 cast<BitCastInst>(IP)->getOperand(0) != A) ||
160 isa<DbgInfoIntrinsic>(IP))
162 return ReuseOrCreateCast(A, Ty, Op, IP);
165 // Cast the instruction immediately after the instruction.
166 Instruction *I = cast<Instruction>(V);
167 BasicBlock::iterator IP = findInsertPointAfter(I, Builder.GetInsertBlock());
168 return ReuseOrCreateCast(I, Ty, Op, IP);
171 /// InsertBinop - Insert the specified binary operator, doing a small amount
172 /// of work to avoid inserting an obviously redundant operation.
173 Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
174 Value *LHS, Value *RHS) {
175 // Fold a binop with constant operands.
176 if (Constant *CLHS = dyn_cast<Constant>(LHS))
177 if (Constant *CRHS = dyn_cast<Constant>(RHS))
178 return ConstantExpr::get(Opcode, CLHS, CRHS);
180 // Do a quick scan to see if we have this binop nearby. If so, reuse it.
181 unsigned ScanLimit = 6;
182 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
183 // Scanning starts from the last instruction before the insertion point.
184 BasicBlock::iterator IP = Builder.GetInsertPoint();
185 if (IP != BlockBegin) {
187 for (; ScanLimit; --IP, --ScanLimit) {
188 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
190 if (isa<DbgInfoIntrinsic>(IP))
192 if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
193 IP->getOperand(1) == RHS)
195 if (IP == BlockBegin) break;
199 // Save the original insertion point so we can restore it when we're done.
200 DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
201 BuilderType::InsertPointGuard Guard(Builder);
203 // Move the insertion point out of as many loops as we can.
204 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
205 if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
206 BasicBlock *Preheader = L->getLoopPreheader();
207 if (!Preheader) break;
209 // Ok, move up a level.
210 Builder.SetInsertPoint(Preheader->getTerminator());
213 // If we haven't found this binop, insert it.
214 Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
215 BO->setDebugLoc(Loc);
216 rememberInstruction(BO);
221 /// FactorOutConstant - Test if S is divisible by Factor, using signed
222 /// division. If so, update S with Factor divided out and return true.
223 /// S need not be evenly divisible if a reasonable remainder can be
225 /// TODO: When ScalarEvolution gets a SCEVSDivExpr, this can be made
226 /// unnecessary; in its place, just signed-divide Ops[i] by the scale and
227 /// check to see if the divide was folded.
228 static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
229 const SCEV *Factor, ScalarEvolution &SE,
230 const DataLayout &DL) {
231 // Everything is divisible by one.
237 S = SE.getConstant(S->getType(), 1);
241 // For a Constant, check for a multiple of the given factor.
242 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
246 // Check for divisibility.
247 if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
249 ConstantInt::get(SE.getContext(),
250 C->getValue()->getValue().sdiv(
251 FC->getValue()->getValue()));
252 // If the quotient is zero and the remainder is non-zero, reject
253 // the value at this scale. It will be considered for subsequent
256 const SCEV *Div = SE.getConstant(CI);
259 SE.getAddExpr(Remainder,
260 SE.getConstant(C->getValue()->getValue().srem(
261 FC->getValue()->getValue())));
267 // In a Mul, check if there is a constant operand which is a multiple
268 // of the given factor.
269 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
270 // Size is known, check if there is a constant operand which is a multiple
271 // of the given factor. If so, we can factor it.
272 const SCEVConstant *FC = cast<SCEVConstant>(Factor);
273 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
274 if (!C->getValue()->getValue().srem(FC->getValue()->getValue())) {
275 SmallVector<const SCEV *, 4> NewMulOps(M->op_begin(), M->op_end());
276 NewMulOps[0] = SE.getConstant(
277 C->getValue()->getValue().sdiv(FC->getValue()->getValue()));
278 S = SE.getMulExpr(NewMulOps);
283 // In an AddRec, check if both start and step are divisible.
284 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
285 const SCEV *Step = A->getStepRecurrence(SE);
286 const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
287 if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
289 if (!StepRem->isZero())
291 const SCEV *Start = A->getStart();
292 if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
294 S = SE.getAddRecExpr(Start, Step, A->getLoop(),
295 A->getNoWrapFlags(SCEV::FlagNW));
302 /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
303 /// is the number of SCEVAddRecExprs present, which are kept at the end of
306 static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
308 ScalarEvolution &SE) {
309 unsigned NumAddRecs = 0;
310 for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
312 // Group Ops into non-addrecs and addrecs.
313 SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
314 SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
315 // Let ScalarEvolution sort and simplify the non-addrecs list.
316 const SCEV *Sum = NoAddRecs.empty() ?
317 SE.getConstant(Ty, 0) :
318 SE.getAddExpr(NoAddRecs);
319 // If it returned an add, use the operands. Otherwise it simplified
320 // the sum into a single value, so just use that.
322 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
323 Ops.append(Add->op_begin(), Add->op_end());
324 else if (!Sum->isZero())
326 // Then append the addrecs.
327 Ops.append(AddRecs.begin(), AddRecs.end());
330 /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
331 /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
332 /// This helps expose more opportunities for folding parts of the expressions
333 /// into GEP indices.
335 static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
337 ScalarEvolution &SE) {
339 SmallVector<const SCEV *, 8> AddRecs;
340 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
341 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
342 const SCEV *Start = A->getStart();
343 if (Start->isZero()) break;
344 const SCEV *Zero = SE.getConstant(Ty, 0);
345 AddRecs.push_back(SE.getAddRecExpr(Zero,
346 A->getStepRecurrence(SE),
348 A->getNoWrapFlags(SCEV::FlagNW)));
349 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
351 Ops.append(Add->op_begin(), Add->op_end());
352 e += Add->getNumOperands();
357 if (!AddRecs.empty()) {
358 // Add the addrecs onto the end of the list.
359 Ops.append(AddRecs.begin(), AddRecs.end());
360 // Resort the operand list, moving any constants to the front.
361 SimplifyAddOperands(Ops, Ty, SE);
365 /// expandAddToGEP - Expand an addition expression with a pointer type into
366 /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
367 /// BasicAliasAnalysis and other passes analyze the result. See the rules
368 /// for getelementptr vs. inttoptr in
369 /// http://llvm.org/docs/LangRef.html#pointeraliasing
372 /// Design note: The correctness of using getelementptr here depends on
373 /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
374 /// they may introduce pointer arithmetic which may not be safely converted
375 /// into getelementptr.
377 /// Design note: It might seem desirable for this function to be more
378 /// loop-aware. If some of the indices are loop-invariant while others
379 /// aren't, it might seem desirable to emit multiple GEPs, keeping the
380 /// loop-invariant portions of the overall computation outside the loop.
381 /// However, there are a few reasons this is not done here. Hoisting simple
382 /// arithmetic is a low-level optimization that often isn't very
383 /// important until late in the optimization process. In fact, passes
384 /// like InstructionCombining will combine GEPs, even if it means
385 /// pushing loop-invariant computation down into loops, so even if the
386 /// GEPs were split here, the work would quickly be undone. The
387 /// LoopStrengthReduction pass, which is usually run quite late (and
388 /// after the last InstructionCombining pass), takes care of hoisting
389 /// loop-invariant portions of expressions, after considering what
390 /// can be folded using target addressing modes.
392 Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
393 const SCEV *const *op_end,
397 Type *OriginalElTy = PTy->getElementType();
398 Type *ElTy = OriginalElTy;
399 SmallVector<Value *, 4> GepIndices;
400 SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
401 bool AnyNonZeroIndices = false;
403 // Split AddRecs up into parts as either of the parts may be usable
404 // without the other.
405 SplitAddRecs(Ops, Ty, SE);
407 Type *IntPtrTy = DL.getIntPtrType(PTy);
409 // Descend down the pointer's type and attempt to convert the other
410 // operands into GEP indices, at each level. The first index in a GEP
411 // indexes into the array implied by the pointer operand; the rest of
412 // the indices index into the element or field type selected by the
415 // If the scale size is not 0, attempt to factor out a scale for
417 SmallVector<const SCEV *, 8> ScaledOps;
418 if (ElTy->isSized()) {
419 const SCEV *ElSize = SE.getSizeOfExpr(IntPtrTy, ElTy);
420 if (!ElSize->isZero()) {
421 SmallVector<const SCEV *, 8> NewOps;
422 for (const SCEV *Op : Ops) {
423 const SCEV *Remainder = SE.getConstant(Ty, 0);
424 if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
425 // Op now has ElSize factored out.
426 ScaledOps.push_back(Op);
427 if (!Remainder->isZero())
428 NewOps.push_back(Remainder);
429 AnyNonZeroIndices = true;
431 // The operand was not divisible, so add it to the list of operands
432 // we'll scan next iteration.
433 NewOps.push_back(Op);
436 // If we made any changes, update Ops.
437 if (!ScaledOps.empty()) {
439 SimplifyAddOperands(Ops, Ty, SE);
444 // Record the scaled array index for this level of the type. If
445 // we didn't find any operands that could be factored, tentatively
446 // assume that element zero was selected (since the zero offset
447 // would obviously be folded away).
448 Value *Scaled = ScaledOps.empty() ?
449 Constant::getNullValue(Ty) :
450 expandCodeFor(SE.getAddExpr(ScaledOps), Ty);
451 GepIndices.push_back(Scaled);
453 // Collect struct field index operands.
454 while (StructType *STy = dyn_cast<StructType>(ElTy)) {
455 bool FoundFieldNo = false;
456 // An empty struct has no fields.
457 if (STy->getNumElements() == 0) break;
458 // Field offsets are known. See if a constant offset falls within any of
459 // the struct fields.
462 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
463 if (SE.getTypeSizeInBits(C->getType()) <= 64) {
464 const StructLayout &SL = *DL.getStructLayout(STy);
465 uint64_t FullOffset = C->getValue()->getZExtValue();
466 if (FullOffset < SL.getSizeInBytes()) {
467 unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
468 GepIndices.push_back(
469 ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
470 ElTy = STy->getTypeAtIndex(ElIdx);
472 SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
473 AnyNonZeroIndices = true;
477 // If no struct field offsets were found, tentatively assume that
478 // field zero was selected (since the zero offset would obviously
481 ElTy = STy->getTypeAtIndex(0u);
482 GepIndices.push_back(
483 Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
487 if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
488 ElTy = ATy->getElementType();
493 // If none of the operands were convertible to proper GEP indices, cast
494 // the base to i8* and do an ugly getelementptr with that. It's still
495 // better than ptrtoint+arithmetic+inttoptr at least.
496 if (!AnyNonZeroIndices) {
497 // Cast the base to i8*.
498 V = InsertNoopCastOfTo(V,
499 Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
501 assert(!isa<Instruction>(V) ||
502 SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
504 // Expand the operands for a plain byte offset.
505 Value *Idx = expandCodeFor(SE.getAddExpr(Ops), Ty);
507 // Fold a GEP with constant operands.
508 if (Constant *CLHS = dyn_cast<Constant>(V))
509 if (Constant *CRHS = dyn_cast<Constant>(Idx))
510 return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
513 // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
514 unsigned ScanLimit = 6;
515 BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
516 // Scanning starts from the last instruction before the insertion point.
517 BasicBlock::iterator IP = Builder.GetInsertPoint();
518 if (IP != BlockBegin) {
520 for (; ScanLimit; --IP, --ScanLimit) {
521 // Don't count dbg.value against the ScanLimit, to avoid perturbing the
523 if (isa<DbgInfoIntrinsic>(IP))
525 if (IP->getOpcode() == Instruction::GetElementPtr &&
526 IP->getOperand(0) == V && IP->getOperand(1) == Idx)
528 if (IP == BlockBegin) break;
532 // Save the original insertion point so we can restore it when we're done.
533 BuilderType::InsertPointGuard Guard(Builder);
535 // Move the insertion point out of as many loops as we can.
536 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
537 if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
538 BasicBlock *Preheader = L->getLoopPreheader();
539 if (!Preheader) break;
541 // Ok, move up a level.
542 Builder.SetInsertPoint(Preheader->getTerminator());
546 Value *GEP = Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
547 rememberInstruction(GEP);
552 // Save the original insertion point so we can restore it when we're done.
553 BuilderType::InsertPoint SaveInsertPt = Builder.saveIP();
555 // Move the insertion point out of as many loops as we can.
556 while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
557 if (!L->isLoopInvariant(V)) break;
559 bool AnyIndexNotLoopInvariant =
560 std::any_of(GepIndices.begin(), GepIndices.end(),
561 [L](Value *Op) { return !L->isLoopInvariant(Op); });
563 if (AnyIndexNotLoopInvariant)
566 BasicBlock *Preheader = L->getLoopPreheader();
567 if (!Preheader) break;
569 // Ok, move up a level.
570 Builder.SetInsertPoint(Preheader->getTerminator());
573 // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
574 // because ScalarEvolution may have changed the address arithmetic to
575 // compute a value which is beyond the end of the allocated object.
577 if (V->getType() != PTy)
578 Casted = InsertNoopCastOfTo(Casted, PTy);
579 Value *GEP = Builder.CreateGEP(OriginalElTy, Casted, GepIndices, "scevgep");
580 Ops.push_back(SE.getUnknown(GEP));
581 rememberInstruction(GEP);
583 // Restore the original insert point.
584 Builder.restoreIP(SaveInsertPt);
586 return expand(SE.getAddExpr(Ops));
589 /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
590 /// SCEV expansion. If they are nested, this is the most nested. If they are
591 /// neighboring, pick the later.
592 static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
596 if (A->contains(B)) return B;
597 if (B->contains(A)) return A;
598 if (DT.dominates(A->getHeader(), B->getHeader())) return B;
599 if (DT.dominates(B->getHeader(), A->getHeader())) return A;
600 return A; // Arbitrarily break the tie.
603 /// getRelevantLoop - Get the most relevant loop associated with the given
604 /// expression, according to PickMostRelevantLoop.
605 const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
606 // Test whether we've already computed the most relevant loop for this SCEV.
607 auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
609 return Pair.first->second;
611 if (isa<SCEVConstant>(S))
612 // A constant has no relevant loops.
614 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
615 if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
616 return Pair.first->second = SE.LI.getLoopFor(I->getParent());
617 // A non-instruction has no relevant loops.
620 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
621 const Loop *L = nullptr;
622 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
624 for (const SCEV *Op : N->operands())
625 L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
626 return RelevantLoops[N] = L;
628 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
629 const Loop *Result = getRelevantLoop(C->getOperand());
630 return RelevantLoops[C] = Result;
632 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
633 const Loop *Result = PickMostRelevantLoop(
634 getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
635 return RelevantLoops[D] = Result;
637 llvm_unreachable("Unexpected SCEV type!");
642 /// LoopCompare - Compare loops by PickMostRelevantLoop.
646 explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
648 bool operator()(std::pair<const Loop *, const SCEV *> LHS,
649 std::pair<const Loop *, const SCEV *> RHS) const {
650 // Keep pointer operands sorted at the end.
651 if (LHS.second->getType()->isPointerTy() !=
652 RHS.second->getType()->isPointerTy())
653 return LHS.second->getType()->isPointerTy();
655 // Compare loops with PickMostRelevantLoop.
656 if (LHS.first != RHS.first)
657 return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
659 // If one operand is a non-constant negative and the other is not,
660 // put the non-constant negative on the right so that a sub can
661 // be used instead of a negate and add.
662 if (LHS.second->isNonConstantNegative()) {
663 if (!RHS.second->isNonConstantNegative())
665 } else if (RHS.second->isNonConstantNegative())
668 // Otherwise they are equivalent according to this comparison.
675 Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
676 Type *Ty = SE.getEffectiveSCEVType(S->getType());
678 // Collect all the add operands in a loop, along with their associated loops.
679 // Iterate in reverse so that constants are emitted last, all else equal, and
680 // so that pointer operands are inserted first, which the code below relies on
681 // to form more involved GEPs.
682 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
683 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(S->op_end()),
684 E(S->op_begin()); I != E; ++I)
685 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
687 // Sort by loop. Use a stable sort so that constants follow non-constants and
688 // pointer operands precede non-pointer operands.
689 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
691 // Emit instructions to add all the operands. Hoist as much as possible
692 // out of loops, and form meaningful getelementptrs where possible.
693 Value *Sum = nullptr;
694 for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
695 const Loop *CurLoop = I->first;
696 const SCEV *Op = I->second;
698 // This is the first operand. Just expand it.
701 } else if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
702 // The running sum expression is a pointer. Try to form a getelementptr
703 // at this level with that as the base.
704 SmallVector<const SCEV *, 4> NewOps;
705 for (; I != E && I->first == CurLoop; ++I) {
706 // If the operand is SCEVUnknown and not instructions, peek through
707 // it, to enable more of it to be folded into the GEP.
708 const SCEV *X = I->second;
709 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
710 if (!isa<Instruction>(U->getValue()))
711 X = SE.getSCEV(U->getValue());
714 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
715 } else if (PointerType *PTy = dyn_cast<PointerType>(Op->getType())) {
716 // The running sum is an integer, and there's a pointer at this level.
717 // Try to form a getelementptr. If the running sum is instructions,
718 // use a SCEVUnknown to avoid re-analyzing them.
719 SmallVector<const SCEV *, 4> NewOps;
720 NewOps.push_back(isa<Instruction>(Sum) ? SE.getUnknown(Sum) :
722 for (++I; I != E && I->first == CurLoop; ++I)
723 NewOps.push_back(I->second);
724 Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, expand(Op));
725 } else if (Op->isNonConstantNegative()) {
726 // Instead of doing a negate and add, just do a subtract.
727 Value *W = expandCodeFor(SE.getNegativeSCEV(Op), Ty);
728 Sum = InsertNoopCastOfTo(Sum, Ty);
729 Sum = InsertBinop(Instruction::Sub, Sum, W);
733 Value *W = expandCodeFor(Op, Ty);
734 Sum = InsertNoopCastOfTo(Sum, Ty);
735 // Canonicalize a constant to the RHS.
736 if (isa<Constant>(Sum)) std::swap(Sum, W);
737 Sum = InsertBinop(Instruction::Add, Sum, W);
745 Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
746 Type *Ty = SE.getEffectiveSCEVType(S->getType());
748 // Collect all the mul operands in a loop, along with their associated loops.
749 // Iterate in reverse so that constants are emitted last, all else equal.
750 SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
751 for (std::reverse_iterator<SCEVMulExpr::op_iterator> I(S->op_end()),
752 E(S->op_begin()); I != E; ++I)
753 OpsAndLoops.push_back(std::make_pair(getRelevantLoop(*I), *I));
755 // Sort by loop. Use a stable sort so that constants follow non-constants.
756 std::stable_sort(OpsAndLoops.begin(), OpsAndLoops.end(), LoopCompare(SE.DT));
758 // Emit instructions to mul all the operands. Hoist as much as possible
760 Value *Prod = nullptr;
761 for (const auto &I : OpsAndLoops) {
762 const SCEV *Op = I.second;
764 // This is the first operand. Just expand it.
766 } else if (Op->isAllOnesValue()) {
767 // Instead of doing a multiply by negative one, just do a negate.
768 Prod = InsertNoopCastOfTo(Prod, Ty);
769 Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod);
772 Value *W = expandCodeFor(Op, Ty);
773 Prod = InsertNoopCastOfTo(Prod, Ty);
774 // Canonicalize a constant to the RHS.
775 if (isa<Constant>(Prod)) std::swap(Prod, W);
777 if (match(W, m_Power2(RHS))) {
778 // Canonicalize Prod*(1<<C) to Prod<<C.
779 assert(!Ty->isVectorTy() && "vector types are not SCEVable");
780 Prod = InsertBinop(Instruction::Shl, Prod,
781 ConstantInt::get(Ty, RHS->logBase2()));
783 Prod = InsertBinop(Instruction::Mul, Prod, W);
791 Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
792 Type *Ty = SE.getEffectiveSCEVType(S->getType());
794 Value *LHS = expandCodeFor(S->getLHS(), Ty);
795 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
796 const APInt &RHS = SC->getValue()->getValue();
797 if (RHS.isPowerOf2())
798 return InsertBinop(Instruction::LShr, LHS,
799 ConstantInt::get(Ty, RHS.logBase2()));
802 Value *RHS = expandCodeFor(S->getRHS(), Ty);
803 return InsertBinop(Instruction::UDiv, LHS, RHS);
806 /// Move parts of Base into Rest to leave Base with the minimal
807 /// expression that provides a pointer operand suitable for a
809 static void ExposePointerBase(const SCEV *&Base, const SCEV *&Rest,
810 ScalarEvolution &SE) {
811 while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Base)) {
812 Base = A->getStart();
813 Rest = SE.getAddExpr(Rest,
814 SE.getAddRecExpr(SE.getConstant(A->getType(), 0),
815 A->getStepRecurrence(SE),
817 A->getNoWrapFlags(SCEV::FlagNW)));
819 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(Base)) {
820 Base = A->getOperand(A->getNumOperands()-1);
821 SmallVector<const SCEV *, 8> NewAddOps(A->op_begin(), A->op_end());
822 NewAddOps.back() = Rest;
823 Rest = SE.getAddExpr(NewAddOps);
824 ExposePointerBase(Base, Rest, SE);
828 /// Determine if this is a well-behaved chain of instructions leading back to
829 /// the PHI. If so, it may be reused by expanded expressions.
830 bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
832 if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
833 (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
835 // If any of the operands don't dominate the insert position, bail.
836 // Addrec operands are always loop-invariant, so this can only happen
837 // if there are instructions which haven't been hoisted.
838 if (L == IVIncInsertLoop) {
839 for (User::op_iterator OI = IncV->op_begin()+1,
840 OE = IncV->op_end(); OI != OE; ++OI)
841 if (Instruction *OInst = dyn_cast<Instruction>(OI))
842 if (!SE.DT.dominates(OInst, IVIncInsertPos))
845 // Advance to the next instruction.
846 IncV = dyn_cast<Instruction>(IncV->getOperand(0));
850 if (IncV->mayHaveSideEffects())
856 return isNormalAddRecExprPHI(PN, IncV, L);
859 /// getIVIncOperand returns an induction variable increment's induction
860 /// variable operand.
862 /// If allowScale is set, any type of GEP is allowed as long as the nonIV
863 /// operands dominate InsertPos.
865 /// If allowScale is not set, ensure that a GEP increment conforms to one of the
866 /// simple patterns generated by getAddRecExprPHILiterally and
867 /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
868 Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
869 Instruction *InsertPos,
871 if (IncV == InsertPos)
874 switch (IncV->getOpcode()) {
877 // Check for a simple Add/Sub or GEP of a loop invariant step.
878 case Instruction::Add:
879 case Instruction::Sub: {
880 Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
881 if (!OInst || SE.DT.dominates(OInst, InsertPos))
882 return dyn_cast<Instruction>(IncV->getOperand(0));
885 case Instruction::BitCast:
886 return dyn_cast<Instruction>(IncV->getOperand(0));
887 case Instruction::GetElementPtr:
888 for (auto I = IncV->op_begin() + 1, E = IncV->op_end(); I != E; ++I) {
889 if (isa<Constant>(*I))
891 if (Instruction *OInst = dyn_cast<Instruction>(*I)) {
892 if (!SE.DT.dominates(OInst, InsertPos))
896 // allow any kind of GEP as long as it can be hoisted.
899 // This must be a pointer addition of constants (pretty), which is already
900 // handled, or some number of address-size elements (ugly). Ugly geps
901 // have 2 operands. i1* is used by the expander to represent an
902 // address-size element.
903 if (IncV->getNumOperands() != 2)
905 unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
906 if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
907 && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
911 return dyn_cast<Instruction>(IncV->getOperand(0));
915 /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
916 /// it available to other uses in this loop. Recursively hoist any operands,
917 /// until we reach a value that dominates InsertPos.
918 bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
919 if (SE.DT.dominates(IncV, InsertPos))
922 // InsertPos must itself dominate IncV so that IncV's new position satisfies
923 // its existing users.
924 if (isa<PHINode>(InsertPos) ||
925 !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
928 if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
931 // Check that the chain of IV operands leading back to Phi can be hoisted.
932 SmallVector<Instruction*, 4> IVIncs;
934 Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
937 // IncV is safe to hoist.
938 IVIncs.push_back(IncV);
940 if (SE.DT.dominates(IncV, InsertPos))
943 for (auto I = IVIncs.rbegin(), E = IVIncs.rend(); I != E; ++I) {
944 (*I)->moveBefore(InsertPos);
949 /// Determine if this cyclic phi is in a form that would have been generated by
950 /// LSR. We don't care if the phi was actually expanded in this pass, as long
951 /// as it is in a low-cost form, for example, no implied multiplication. This
952 /// should match any patterns generated by getAddRecExprPHILiterally and
954 bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
956 for(Instruction *IVOper = IncV;
957 (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
958 /*allowScale=*/false));) {
965 /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
966 /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
967 /// need to materialize IV increments elsewhere to handle difficult situations.
968 Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
969 Type *ExpandTy, Type *IntTy,
972 // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
973 if (ExpandTy->isPointerTy()) {
974 PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
975 // If the step isn't constant, don't use an implicitly scaled GEP, because
976 // that would require a multiply inside the loop.
977 if (!isa<ConstantInt>(StepV))
978 GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
979 GEPPtrTy->getAddressSpace());
980 const SCEV *const StepArray[1] = { SE.getSCEV(StepV) };
981 IncV = expandAddToGEP(StepArray, StepArray+1, GEPPtrTy, IntTy, PN);
982 if (IncV->getType() != PN->getType()) {
983 IncV = Builder.CreateBitCast(IncV, PN->getType());
984 rememberInstruction(IncV);
988 Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
989 Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
990 rememberInstruction(IncV);
995 /// \brief Hoist the addrec instruction chain rooted in the loop phi above the
996 /// position. This routine assumes that this is possible (has been checked).
997 static void hoistBeforePos(DominatorTree *DT, Instruction *InstToHoist,
998 Instruction *Pos, PHINode *LoopPhi) {
1000 if (DT->dominates(InstToHoist, Pos))
1002 // Make sure the increment is where we want it. But don't move it
1003 // down past a potential existing post-inc user.
1004 InstToHoist->moveBefore(Pos);
1006 InstToHoist = cast<Instruction>(InstToHoist->getOperand(0));
1007 } while (InstToHoist != LoopPhi);
1010 /// \brief Check whether we can cheaply express the requested SCEV in terms of
1011 /// the available PHI SCEV by truncation and/or inversion of the step.
1012 static bool canBeCheaplyTransformed(ScalarEvolution &SE,
1013 const SCEVAddRecExpr *Phi,
1014 const SCEVAddRecExpr *Requested,
1016 Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
1017 Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
1019 if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
1022 // Try truncate it if necessary.
1023 Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
1027 // Check whether truncation will help.
1028 if (Phi == Requested) {
1033 // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
1034 if (SE.getAddExpr(Requested->getStart(),
1035 SE.getNegativeSCEV(Requested)) == Phi) {
1043 static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1044 if (!isa<IntegerType>(AR->getType()))
1047 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1048 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1049 const SCEV *Step = AR->getStepRecurrence(SE);
1050 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
1051 SE.getSignExtendExpr(AR, WideTy));
1052 const SCEV *ExtendAfterOp =
1053 SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1054 return ExtendAfterOp == OpAfterExtend;
1057 static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
1058 if (!isa<IntegerType>(AR->getType()))
1061 unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
1062 Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
1063 const SCEV *Step = AR->getStepRecurrence(SE);
1064 const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
1065 SE.getZeroExtendExpr(AR, WideTy));
1066 const SCEV *ExtendAfterOp =
1067 SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
1068 return ExtendAfterOp == OpAfterExtend;
1071 /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
1072 /// the base addrec, which is the addrec without any non-loop-dominating
1073 /// values, and return the PHI.
1075 SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
1081 assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
1083 // Reuse a previously-inserted PHI, if present.
1084 BasicBlock *LatchBlock = L->getLoopLatch();
1086 PHINode *AddRecPhiMatch = nullptr;
1087 Instruction *IncV = nullptr;
1091 // Only try partially matching scevs that need truncation and/or
1092 // step-inversion if we know this loop is outside the current loop.
1093 bool TryNonMatchingSCEV =
1095 SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
1097 for (auto &I : *L->getHeader()) {
1098 auto *PN = dyn_cast<PHINode>(&I);
1099 if (!PN || !SE.isSCEVable(PN->getType()))
1102 const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PN));
1106 bool IsMatchingSCEV = PhiSCEV == Normalized;
1107 // We only handle truncation and inversion of phi recurrences for the
1108 // expanded expression if the expanded expression's loop dominates the
1109 // loop we insert to. Check now, so we can bail out early.
1110 if (!IsMatchingSCEV && !TryNonMatchingSCEV)
1113 Instruction *TempIncV =
1114 cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock));
1116 // Check whether we can reuse this PHI node.
1118 if (!isExpandedAddRecExprPHI(PN, TempIncV, L))
1120 if (L == IVIncInsertLoop && !hoistIVInc(TempIncV, IVIncInsertPos))
1123 if (!isNormalAddRecExprPHI(PN, TempIncV, L))
1127 // Stop if we have found an exact match SCEV.
1128 if (IsMatchingSCEV) {
1132 AddRecPhiMatch = PN;
1136 // Try whether the phi can be translated into the requested form
1137 // (truncated and/or offset by a constant).
1138 if ((!TruncTy || InvertStep) &&
1139 canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
1140 // Record the phi node. But don't stop we might find an exact match
1142 AddRecPhiMatch = PN;
1144 TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
1148 if (AddRecPhiMatch) {
1149 // Potentially, move the increment. We have made sure in
1150 // isExpandedAddRecExprPHI or hoistIVInc that this is possible.
1151 if (L == IVIncInsertLoop)
1152 hoistBeforePos(&SE.DT, IncV, IVIncInsertPos, AddRecPhiMatch);
1154 // Ok, the add recurrence looks usable.
1155 // Remember this PHI, even in post-inc mode.
1156 InsertedValues.insert(AddRecPhiMatch);
1157 // Remember the increment.
1158 rememberInstruction(IncV);
1159 return AddRecPhiMatch;
1163 // Save the original insertion point so we can restore it when we're done.
1164 BuilderType::InsertPointGuard Guard(Builder);
1166 // Another AddRec may need to be recursively expanded below. For example, if
1167 // this AddRec is quadratic, the StepV may itself be an AddRec in this
1168 // loop. Remove this loop from the PostIncLoops set before expanding such
1169 // AddRecs. Otherwise, we cannot find a valid position for the step
1170 // (i.e. StepV can never dominate its loop header). Ideally, we could do
1171 // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
1172 // so it's not worth implementing SmallPtrSet::swap.
1173 PostIncLoopSet SavedPostIncLoops = PostIncLoops;
1174 PostIncLoops.clear();
1176 // Expand code for the start value.
1178 expandCodeFor(Normalized->getStart(), ExpandTy, &L->getHeader()->front());
1180 // StartV must be hoisted into L's preheader to dominate the new phi.
1181 assert(!isa<Instruction>(StartV) ||
1182 SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
1185 // Expand code for the step value. Do this before creating the PHI so that PHI
1186 // reuse code doesn't see an incomplete PHI.
1187 const SCEV *Step = Normalized->getStepRecurrence(SE);
1188 // If the stride is negative, insert a sub instead of an add for the increment
1189 // (unless it's a constant, because subtracts of constants are canonicalized
1191 bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1193 Step = SE.getNegativeSCEV(Step);
1194 // Expand the step somewhere that dominates the loop header.
1195 Value *StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1197 // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
1198 // we actually do emit an addition. It does not apply if we emit a
1200 bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
1201 bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
1204 BasicBlock *Header = L->getHeader();
1205 Builder.SetInsertPoint(Header, Header->begin());
1206 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1207 PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
1208 Twine(IVName) + ".iv");
1209 rememberInstruction(PN);
1211 // Create the step instructions and populate the PHI.
1212 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1213 BasicBlock *Pred = *HPI;
1215 // Add a start value.
1216 if (!L->contains(Pred)) {
1217 PN->addIncoming(StartV, Pred);
1221 // Create a step value and add it to the PHI.
1222 // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
1223 // instructions at IVIncInsertPos.
1224 Instruction *InsertPos = L == IVIncInsertLoop ?
1225 IVIncInsertPos : Pred->getTerminator();
1226 Builder.SetInsertPoint(InsertPos);
1227 Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1229 if (isa<OverflowingBinaryOperator>(IncV)) {
1231 cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
1233 cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
1235 PN->addIncoming(IncV, Pred);
1238 // After expanding subexpressions, restore the PostIncLoops set so the caller
1239 // can ensure that IVIncrement dominates the current uses.
1240 PostIncLoops = SavedPostIncLoops;
1242 // Remember this PHI, even in post-inc mode.
1243 InsertedValues.insert(PN);
1248 Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
1249 Type *STy = S->getType();
1250 Type *IntTy = SE.getEffectiveSCEVType(STy);
1251 const Loop *L = S->getLoop();
1253 // Determine a normalized form of this expression, which is the expression
1254 // before any post-inc adjustment is made.
1255 const SCEVAddRecExpr *Normalized = S;
1256 if (PostIncLoops.count(L)) {
1257 PostIncLoopSet Loops;
1259 Normalized = cast<SCEVAddRecExpr>(TransformForPostIncUse(
1260 Normalize, S, nullptr, nullptr, Loops, SE, SE.DT));
1263 // Strip off any non-loop-dominating component from the addrec start.
1264 const SCEV *Start = Normalized->getStart();
1265 const SCEV *PostLoopOffset = nullptr;
1266 if (!SE.properlyDominates(Start, L->getHeader())) {
1267 PostLoopOffset = Start;
1268 Start = SE.getConstant(Normalized->getType(), 0);
1269 Normalized = cast<SCEVAddRecExpr>(
1270 SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
1271 Normalized->getLoop(),
1272 Normalized->getNoWrapFlags(SCEV::FlagNW)));
1275 // Strip off any non-loop-dominating component from the addrec step.
1276 const SCEV *Step = Normalized->getStepRecurrence(SE);
1277 const SCEV *PostLoopScale = nullptr;
1278 if (!SE.dominates(Step, L->getHeader())) {
1279 PostLoopScale = Step;
1280 Step = SE.getConstant(Normalized->getType(), 1);
1282 cast<SCEVAddRecExpr>(SE.getAddRecExpr(
1283 Start, Step, Normalized->getLoop(),
1284 Normalized->getNoWrapFlags(SCEV::FlagNW)));
1287 // Expand the core addrec. If we need post-loop scaling, force it to
1288 // expand to an integer type to avoid the need for additional casting.
1289 Type *ExpandTy = PostLoopScale ? IntTy : STy;
1290 // In some cases, we decide to reuse an existing phi node but need to truncate
1291 // it and/or invert the step.
1292 Type *TruncTy = nullptr;
1293 bool InvertStep = false;
1294 PHINode *PN = getAddRecExprPHILiterally(Normalized, L, ExpandTy, IntTy,
1295 TruncTy, InvertStep);
1297 // Accommodate post-inc mode, if necessary.
1299 if (!PostIncLoops.count(L))
1302 // In PostInc mode, use the post-incremented value.
1303 BasicBlock *LatchBlock = L->getLoopLatch();
1304 assert(LatchBlock && "PostInc mode requires a unique loop latch!");
1305 Result = PN->getIncomingValueForBlock(LatchBlock);
1307 // For an expansion to use the postinc form, the client must call
1308 // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
1309 // or dominated by IVIncInsertPos.
1310 if (isa<Instruction>(Result) &&
1311 !SE.DT.dominates(cast<Instruction>(Result),
1312 &*Builder.GetInsertPoint())) {
1313 // The induction variable's postinc expansion does not dominate this use.
1314 // IVUsers tries to prevent this case, so it is rare. However, it can
1315 // happen when an IVUser outside the loop is not dominated by the latch
1316 // block. Adjusting IVIncInsertPos before expansion begins cannot handle
1317 // all cases. Consider a phi outide whose operand is replaced during
1318 // expansion with the value of the postinc user. Without fundamentally
1319 // changing the way postinc users are tracked, the only remedy is
1320 // inserting an extra IV increment. StepV might fold into PostLoopOffset,
1321 // but hopefully expandCodeFor handles that.
1323 !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
1325 Step = SE.getNegativeSCEV(Step);
1328 // Expand the step somewhere that dominates the loop header.
1329 BuilderType::InsertPointGuard Guard(Builder);
1330 StepV = expandCodeFor(Step, IntTy, &L->getHeader()->front());
1332 Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
1336 // We have decided to reuse an induction variable of a dominating loop. Apply
1337 // truncation and/or invertion of the step.
1339 Type *ResTy = Result->getType();
1340 // Normalize the result type.
1341 if (ResTy != SE.getEffectiveSCEVType(ResTy))
1342 Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
1343 // Truncate the result.
1344 if (TruncTy != Result->getType()) {
1345 Result = Builder.CreateTrunc(Result, TruncTy);
1346 rememberInstruction(Result);
1348 // Invert the result.
1350 Result = Builder.CreateSub(expandCodeFor(Normalized->getStart(), TruncTy),
1352 rememberInstruction(Result);
1356 // Re-apply any non-loop-dominating scale.
1357 if (PostLoopScale) {
1358 assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
1359 Result = InsertNoopCastOfTo(Result, IntTy);
1360 Result = Builder.CreateMul(Result,
1361 expandCodeFor(PostLoopScale, IntTy));
1362 rememberInstruction(Result);
1365 // Re-apply any non-loop-dominating offset.
1366 if (PostLoopOffset) {
1367 if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
1368 const SCEV *const OffsetArray[1] = { PostLoopOffset };
1369 Result = expandAddToGEP(OffsetArray, OffsetArray+1, PTy, IntTy, Result);
1371 Result = InsertNoopCastOfTo(Result, IntTy);
1372 Result = Builder.CreateAdd(Result,
1373 expandCodeFor(PostLoopOffset, IntTy));
1374 rememberInstruction(Result);
1381 Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
1382 if (!CanonicalMode) return expandAddRecExprLiterally(S);
1384 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1385 const Loop *L = S->getLoop();
1387 // First check for an existing canonical IV in a suitable type.
1388 PHINode *CanonicalIV = nullptr;
1389 if (PHINode *PN = L->getCanonicalInductionVariable())
1390 if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
1393 // Rewrite an AddRec in terms of the canonical induction variable, if
1394 // its type is more narrow.
1396 SE.getTypeSizeInBits(CanonicalIV->getType()) >
1397 SE.getTypeSizeInBits(Ty)) {
1398 SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
1399 for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
1400 NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
1401 Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
1402 S->getNoWrapFlags(SCEV::FlagNW)));
1403 BasicBlock::iterator NewInsertPt =
1404 findInsertPointAfter(cast<Instruction>(V), Builder.GetInsertBlock());
1405 V = expandCodeFor(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
1410 // {X,+,F} --> X + {0,+,F}
1411 if (!S->getStart()->isZero()) {
1412 SmallVector<const SCEV *, 4> NewOps(S->op_begin(), S->op_end());
1413 NewOps[0] = SE.getConstant(Ty, 0);
1414 const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
1415 S->getNoWrapFlags(SCEV::FlagNW));
1417 // Turn things like ptrtoint+arithmetic+inttoptr into GEP. See the
1418 // comments on expandAddToGEP for details.
1419 const SCEV *Base = S->getStart();
1420 const SCEV *RestArray[1] = { Rest };
1421 // Dig into the expression to find the pointer base for a GEP.
1422 ExposePointerBase(Base, RestArray[0], SE);
1423 // If we found a pointer, expand the AddRec with a GEP.
1424 if (PointerType *PTy = dyn_cast<PointerType>(Base->getType())) {
1425 // Make sure the Base isn't something exotic, such as a multiplied
1426 // or divided pointer value. In those cases, the result type isn't
1427 // actually a pointer type.
1428 if (!isa<SCEVMulExpr>(Base) && !isa<SCEVUDivExpr>(Base)) {
1429 Value *StartV = expand(Base);
1430 assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
1431 return expandAddToGEP(RestArray, RestArray+1, PTy, Ty, StartV);
1435 // Just do a normal add. Pre-expand the operands to suppress folding.
1436 return expand(SE.getAddExpr(SE.getUnknown(expand(S->getStart())),
1437 SE.getUnknown(expand(Rest))));
1440 // If we don't yet have a canonical IV, create one.
1442 // Create and insert the PHI node for the induction variable in the
1444 BasicBlock *Header = L->getHeader();
1445 pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
1446 CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
1448 rememberInstruction(CanonicalIV);
1450 SmallSet<BasicBlock *, 4> PredSeen;
1451 Constant *One = ConstantInt::get(Ty, 1);
1452 for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
1453 BasicBlock *HP = *HPI;
1454 if (!PredSeen.insert(HP).second) {
1455 // There must be an incoming value for each predecessor, even the
1457 CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
1461 if (L->contains(HP)) {
1462 // Insert a unit add instruction right before the terminator
1463 // corresponding to the back-edge.
1464 Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
1466 HP->getTerminator());
1467 Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
1468 rememberInstruction(Add);
1469 CanonicalIV->addIncoming(Add, HP);
1471 CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
1476 // {0,+,1} --> Insert a canonical induction variable into the loop!
1477 if (S->isAffine() && S->getOperand(1)->isOne()) {
1478 assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
1479 "IVs with types different from the canonical IV should "
1480 "already have been handled!");
1484 // {0,+,F} --> {0,+,1} * F
1486 // If this is a simple linear addrec, emit it now as a special case.
1487 if (S->isAffine()) // {0,+,F} --> i*F
1489 expand(SE.getTruncateOrNoop(
1490 SE.getMulExpr(SE.getUnknown(CanonicalIV),
1491 SE.getNoopOrAnyExtend(S->getOperand(1),
1492 CanonicalIV->getType())),
1495 // If this is a chain of recurrences, turn it into a closed form, using the
1496 // folders, then expandCodeFor the closed form. This allows the folders to
1497 // simplify the expression without having to build a bunch of special code
1498 // into this folder.
1499 const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
1501 // Promote S up to the canonical IV type, if the cast is foldable.
1502 const SCEV *NewS = S;
1503 const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
1504 if (isa<SCEVAddRecExpr>(Ext))
1507 const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
1508 //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
1510 // Truncate the result down to the original type, if needed.
1511 const SCEV *T = SE.getTruncateOrNoop(V, Ty);
1515 Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
1516 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1517 Value *V = expandCodeFor(S->getOperand(),
1518 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1519 Value *I = Builder.CreateTrunc(V, Ty);
1520 rememberInstruction(I);
1524 Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
1525 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1526 Value *V = expandCodeFor(S->getOperand(),
1527 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1528 Value *I = Builder.CreateZExt(V, Ty);
1529 rememberInstruction(I);
1533 Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
1534 Type *Ty = SE.getEffectiveSCEVType(S->getType());
1535 Value *V = expandCodeFor(S->getOperand(),
1536 SE.getEffectiveSCEVType(S->getOperand()->getType()));
1537 Value *I = Builder.CreateSExt(V, Ty);
1538 rememberInstruction(I);
1542 Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
1543 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1544 Type *Ty = LHS->getType();
1545 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1546 // In the case of mixed integer and pointer types, do the
1547 // rest of the comparisons as integer.
1548 if (S->getOperand(i)->getType() != Ty) {
1549 Ty = SE.getEffectiveSCEVType(Ty);
1550 LHS = InsertNoopCastOfTo(LHS, Ty);
1552 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1553 Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
1554 rememberInstruction(ICmp);
1555 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
1556 rememberInstruction(Sel);
1559 // In the case of mixed integer and pointer types, cast the
1560 // final result back to the pointer type.
1561 if (LHS->getType() != S->getType())
1562 LHS = InsertNoopCastOfTo(LHS, S->getType());
1566 Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
1567 Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
1568 Type *Ty = LHS->getType();
1569 for (int i = S->getNumOperands()-2; i >= 0; --i) {
1570 // In the case of mixed integer and pointer types, do the
1571 // rest of the comparisons as integer.
1572 if (S->getOperand(i)->getType() != Ty) {
1573 Ty = SE.getEffectiveSCEVType(Ty);
1574 LHS = InsertNoopCastOfTo(LHS, Ty);
1576 Value *RHS = expandCodeFor(S->getOperand(i), Ty);
1577 Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
1578 rememberInstruction(ICmp);
1579 Value *Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
1580 rememberInstruction(Sel);
1583 // In the case of mixed integer and pointer types, cast the
1584 // final result back to the pointer type.
1585 if (LHS->getType() != S->getType())
1586 LHS = InsertNoopCastOfTo(LHS, S->getType());
1590 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty,
1593 Builder.SetInsertPoint(IP);
1594 return expandCodeFor(SH, Ty);
1597 Value *SCEVExpander::expandCodeFor(const SCEV *SH, Type *Ty) {
1598 // Expand the code for this SCEV.
1599 Value *V = expand(SH);
1601 assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
1602 "non-trivial casts should be done with the SCEVs directly!");
1603 V = InsertNoopCastOfTo(V, Ty);
1608 Value *SCEVExpander::expand(const SCEV *S) {
1609 // Compute an insertion point for this SCEV object. Hoist the instructions
1610 // as far out in the loop nest as possible.
1611 Instruction *InsertPt = &*Builder.GetInsertPoint();
1612 for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
1613 L = L->getParentLoop())
1614 if (SE.isLoopInvariant(S, L)) {
1616 if (BasicBlock *Preheader = L->getLoopPreheader())
1617 InsertPt = Preheader->getTerminator();
1619 // LSR sets the insertion point for AddRec start/step values to the
1620 // block start to simplify value reuse, even though it's an invalid
1621 // position. SCEVExpander must correct for this in all cases.
1622 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1625 // If the SCEV is computable at this level, insert it into the header
1626 // after the PHIs (and after any other instructions that we've inserted
1627 // there) so that it is guaranteed to dominate any user inside the loop.
1628 if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
1629 InsertPt = &*L->getHeader()->getFirstInsertionPt();
1630 while (InsertPt != Builder.GetInsertPoint()
1631 && (isInsertedInstruction(InsertPt)
1632 || isa<DbgInfoIntrinsic>(InsertPt))) {
1633 InsertPt = &*std::next(InsertPt->getIterator());
1638 // Check to see if we already expanded this here.
1639 auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
1640 if (I != InsertedExpressions.end())
1643 BuilderType::InsertPointGuard Guard(Builder);
1644 Builder.SetInsertPoint(InsertPt);
1646 // Expand the expression into instructions.
1647 Value *V = visit(S);
1649 // Remember the expanded value for this SCEV at this location.
1651 // This is independent of PostIncLoops. The mapped value simply materializes
1652 // the expression at this insertion point. If the mapped value happened to be
1653 // a postinc expansion, it could be reused by a non-postinc user, but only if
1654 // its insertion point was already at the head of the loop.
1655 InsertedExpressions[std::make_pair(S, InsertPt)] = V;
1659 void SCEVExpander::rememberInstruction(Value *I) {
1660 if (!PostIncLoops.empty())
1661 InsertedPostIncValues.insert(I);
1663 InsertedValues.insert(I);
1666 /// getOrInsertCanonicalInductionVariable - This method returns the
1667 /// canonical induction variable of the specified type for the specified
1668 /// loop (inserting one if there is none). A canonical induction variable
1669 /// starts at zero and steps by one on each iteration.
1671 SCEVExpander::getOrInsertCanonicalInductionVariable(const Loop *L,
1673 assert(Ty->isIntegerTy() && "Can only insert integer induction variables!");
1675 // Build a SCEV for {0,+,1}<L>.
1676 // Conservatively use FlagAnyWrap for now.
1677 const SCEV *H = SE.getAddRecExpr(SE.getConstant(Ty, 0),
1678 SE.getConstant(Ty, 1), L, SCEV::FlagAnyWrap);
1680 // Emit code for it.
1681 BuilderType::InsertPointGuard Guard(Builder);
1683 cast<PHINode>(expandCodeFor(H, nullptr, &L->getHeader()->front()));
1688 /// replaceCongruentIVs - Check for congruent phis in this loop header and
1689 /// replace them with their most canonical representative. Return the number of
1690 /// phis eliminated.
1692 /// This does not depend on any SCEVExpander state but should be used in
1693 /// the same context that SCEVExpander is used.
1694 unsigned SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
1695 SmallVectorImpl<WeakVH> &DeadInsts,
1696 const TargetTransformInfo *TTI) {
1697 // Find integer phis in order of increasing width.
1698 SmallVector<PHINode*, 8> Phis;
1699 for (auto &I : *L->getHeader()) {
1700 if (auto *PN = dyn_cast<PHINode>(&I))
1707 std::sort(Phis.begin(), Phis.end(), [](Value *LHS, Value *RHS) {
1708 // Put pointers at the back and make sure pointer < pointer = false.
1709 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
1710 return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
1711 return RHS->getType()->getPrimitiveSizeInBits() <
1712 LHS->getType()->getPrimitiveSizeInBits();
1715 unsigned NumElim = 0;
1716 DenseMap<const SCEV *, PHINode *> ExprToIVMap;
1717 // Process phis from wide to narrow. Map wide phis to their truncation
1718 // so narrow phis can reuse them.
1719 for (PHINode *Phi : Phis) {
1720 auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
1721 if (Value *V = SimplifyInstruction(PN, DL, &SE.TLI, &SE.DT, &SE.AC))
1723 if (!SE.isSCEVable(PN->getType()))
1725 auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
1728 return Const->getValue();
1731 // Fold constant phis. They may be congruent to other constant phis and
1732 // would confuse the logic below that expects proper IVs.
1733 if (Value *V = SimplifyPHINode(Phi)) {
1734 if (V->getType() != Phi->getType())
1736 Phi->replaceAllUsesWith(V);
1737 DeadInsts.emplace_back(Phi);
1739 DEBUG_WITH_TYPE(DebugType, dbgs()
1740 << "INDVARS: Eliminated constant iv: " << *Phi << '\n');
1744 if (!SE.isSCEVable(Phi->getType()))
1747 PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
1750 if (Phi->getType()->isIntegerTy() && TTI
1751 && TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
1752 // This phi can be freely truncated to the narrowest phi type. Map the
1753 // truncated expression to it so it will be reused for narrow types.
1754 const SCEV *TruncExpr =
1755 SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
1756 ExprToIVMap[TruncExpr] = Phi;
1761 // Replacing a pointer phi with an integer phi or vice-versa doesn't make
1763 if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
1766 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1767 Instruction *OrigInc =
1768 cast<Instruction>(OrigPhiRef->getIncomingValueForBlock(LatchBlock));
1769 Instruction *IsomorphicInc =
1770 cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
1772 // If this phi has the same width but is more canonical, replace the
1773 // original with it. As part of the "more canonical" determination,
1774 // respect a prior decision to use an IV chain.
1775 if (OrigPhiRef->getType() == Phi->getType()
1776 && !(ChainedPhis.count(Phi)
1777 || isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L))
1778 && (ChainedPhis.count(Phi)
1779 || isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
1780 std::swap(OrigPhiRef, Phi);
1781 std::swap(OrigInc, IsomorphicInc);
1783 // Replacing the congruent phi is sufficient because acyclic redundancy
1784 // elimination, CSE/GVN, should handle the rest. However, once SCEV proves
1785 // that a phi is congruent, it's often the head of an IV user cycle that
1786 // is isomorphic with the original phi. It's worth eagerly cleaning up the
1787 // common case of a single IV increment so that DeleteDeadPHIs can remove
1788 // cycles that had postinc uses.
1789 const SCEV *TruncExpr = SE.getTruncateOrNoop(SE.getSCEV(OrigInc),
1790 IsomorphicInc->getType());
1791 if (OrigInc != IsomorphicInc
1792 && TruncExpr == SE.getSCEV(IsomorphicInc)
1793 && ((isa<PHINode>(OrigInc) && isa<PHINode>(IsomorphicInc))
1794 || hoistIVInc(OrigInc, IsomorphicInc))) {
1795 DEBUG_WITH_TYPE(DebugType, dbgs()
1796 << "INDVARS: Eliminated congruent iv.inc: "
1797 << *IsomorphicInc << '\n');
1798 Value *NewInc = OrigInc;
1799 if (OrigInc->getType() != IsomorphicInc->getType()) {
1800 Instruction *IP = nullptr;
1801 if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
1802 IP = &*PN->getParent()->getFirstInsertionPt();
1804 IP = OrigInc->getNextNode();
1806 IRBuilder<> Builder(IP);
1807 Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
1809 CreateTruncOrBitCast(OrigInc, IsomorphicInc->getType(), IVName);
1811 IsomorphicInc->replaceAllUsesWith(NewInc);
1812 DeadInsts.emplace_back(IsomorphicInc);
1815 DEBUG_WITH_TYPE(DebugType, dbgs()
1816 << "INDVARS: Eliminated congruent iv: " << *Phi << '\n');
1818 Value *NewIV = OrigPhiRef;
1819 if (OrigPhiRef->getType() != Phi->getType()) {
1820 IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
1821 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
1822 NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
1824 Phi->replaceAllUsesWith(NewIV);
1825 DeadInsts.emplace_back(Phi);
1830 Value *SCEVExpander::findExistingExpansion(const SCEV *S,
1831 const Instruction *At, Loop *L) {
1832 using namespace llvm::PatternMatch;
1834 SmallVector<BasicBlock *, 4> ExitingBlocks;
1835 L->getExitingBlocks(ExitingBlocks);
1837 // Look for suitable value in simple conditions at the loop exits.
1838 for (BasicBlock *BB : ExitingBlocks) {
1839 ICmpInst::Predicate Pred;
1840 Instruction *LHS, *RHS;
1841 BasicBlock *TrueBB, *FalseBB;
1843 if (!match(BB->getTerminator(),
1844 m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
1848 if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
1851 if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
1855 // There is potential to make this significantly smarter, but this simple
1856 // heuristic already gets some interesting cases.
1858 // Can not find suitable value.
1862 bool SCEVExpander::isHighCostExpansionHelper(
1863 const SCEV *S, Loop *L, const Instruction *At,
1864 SmallPtrSetImpl<const SCEV *> &Processed) {
1866 // If we can find an existing value for this scev avaliable at the point "At"
1867 // then consider the expression cheap.
1868 if (At && findExistingExpansion(S, At, L) != nullptr)
1871 // Zero/One operand expressions
1872 switch (S->getSCEVType()) {
1877 return isHighCostExpansionHelper(cast<SCEVTruncateExpr>(S)->getOperand(),
1880 return isHighCostExpansionHelper(cast<SCEVZeroExtendExpr>(S)->getOperand(),
1883 return isHighCostExpansionHelper(cast<SCEVSignExtendExpr>(S)->getOperand(),
1887 if (!Processed.insert(S).second)
1890 if (auto *UDivExpr = dyn_cast<SCEVUDivExpr>(S)) {
1891 // If the divisor is a power of two and the SCEV type fits in a native
1892 // integer, consider the division cheap irrespective of whether it occurs in
1893 // the user code since it can be lowered into a right shift.
1894 if (auto *SC = dyn_cast<SCEVConstant>(UDivExpr->getRHS()))
1895 if (SC->getValue()->getValue().isPowerOf2()) {
1896 const DataLayout &DL =
1897 L->getHeader()->getParent()->getParent()->getDataLayout();
1898 unsigned Width = cast<IntegerType>(UDivExpr->getType())->getBitWidth();
1899 return DL.isIllegalInteger(Width);
1902 // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
1903 // HowManyLessThans produced to compute a precise expression, rather than a
1904 // UDiv from the user's code. If we can't find a UDiv in the code with some
1905 // simple searching, assume the former consider UDivExpr expensive to
1907 BasicBlock *ExitingBB = L->getExitingBlock();
1911 // At the beginning of this function we already tried to find existing value
1912 // for plain 'S'. Now try to lookup 'S + 1' since it is common pattern
1913 // involving division. This is just a simple search heuristic.
1915 At = &ExitingBB->back();
1916 if (!findExistingExpansion(
1917 SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), At, L))
1921 // HowManyLessThans uses a Max expression whenever the loop is not guarded by
1922 // the exit condition.
1923 if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
1926 // Recurse past nary expressions, which commonly occur in the
1927 // BackedgeTakenCount. They may already exist in program code, and if not,
1928 // they are not too expensive rematerialize.
1929 if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(S)) {
1930 for (auto *Op : NAry->operands())
1931 if (isHighCostExpansionHelper(Op, L, At, Processed))
1935 // If we haven't recognized an expensive SCEV pattern, assume it's an
1936 // expression produced by program code.
1940 Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
1943 switch (Pred->getKind()) {
1944 case SCEVPredicate::P_Union:
1945 return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
1946 case SCEVPredicate::P_Equal:
1947 return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
1949 llvm_unreachable("Unknown SCEV predicate type");
1952 Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
1954 Value *Expr0 = expandCodeFor(Pred->getLHS(), Pred->getLHS()->getType(), IP);
1955 Value *Expr1 = expandCodeFor(Pred->getRHS(), Pred->getRHS()->getType(), IP);
1957 Builder.SetInsertPoint(IP);
1958 auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
1962 Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
1964 auto *BoolType = IntegerType::get(IP->getContext(), 1);
1965 Value *Check = ConstantInt::getNullValue(BoolType);
1967 // Loop over all checks in this set.
1968 for (auto Pred : Union->getPredicates()) {
1969 auto *NextCheck = expandCodeForPredicate(Pred, IP);
1970 Builder.SetInsertPoint(IP);
1971 Check = Builder.CreateOr(Check, NextCheck);
1978 // Search for a SCEV subexpression that is not safe to expand. Any expression
1979 // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
1980 // UDiv expressions. We don't know if the UDiv is derived from an IR divide
1981 // instruction, but the important thing is that we prove the denominator is
1982 // nonzero before expansion.
1984 // IVUsers already checks that IV-derived expressions are safe. So this check is
1985 // only needed when the expression includes some subexpression that is not IV
1988 // Currently, we only allow division by a nonzero constant here. If this is
1989 // inadequate, we could easily allow division by SCEVUnknown by using
1990 // ValueTracking to check isKnownNonZero().
1992 // We cannot generally expand recurrences unless the step dominates the loop
1993 // header. The expander handles the special case of affine recurrences by
1994 // scaling the recurrence outside the loop, but this technique isn't generally
1995 // applicable. Expanding a nested recurrence outside a loop requires computing
1996 // binomial coefficients. This could be done, but the recurrence has to be in a
1997 // perfectly reduced form, which can't be guaranteed.
1998 struct SCEVFindUnsafe {
1999 ScalarEvolution &SE;
2002 SCEVFindUnsafe(ScalarEvolution &se): SE(se), IsUnsafe(false) {}
2004 bool follow(const SCEV *S) {
2005 if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2006 const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
2007 if (!SC || SC->getValue()->isZero()) {
2012 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2013 const SCEV *Step = AR->getStepRecurrence(SE);
2014 if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
2021 bool isDone() const { return IsUnsafe; }
2026 bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE) {
2027 SCEVFindUnsafe Search(SE);
2028 visitAll(S, Search);
2029 return !Search.IsUnsafe;