1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
14 // If the trip count of a loop is computable, this pass also makes the following
16 // 1. The exit condition for the loop is canonicalized to compare the
17 // induction value against the exit value. This turns loops like:
18 // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19 // 2. Any use outside of the loop of an expression derived from the indvar
20 // is changed to compute the derived value outside of the loop, eliminating
21 // the dependence on the exit value of the induction variable. If the only
22 // purpose of the loop is to compute the exit value of some derived
23 // expression, this transformation will make the loop dead.
25 //===----------------------------------------------------------------------===//
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/GlobalsModRef.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/Analysis/LoopPass.h"
34 #include "llvm/Analysis/ScalarEvolutionExpander.h"
35 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
36 #include "llvm/Analysis/TargetLibraryInfo.h"
37 #include "llvm/Analysis/TargetTransformInfo.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/CFG.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/PatternMatch.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/Local.h"
53 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
56 #define DEBUG_TYPE "indvars"
58 STATISTIC(NumWidened , "Number of indvars widened");
59 STATISTIC(NumReplaced , "Number of exit values replaced");
60 STATISTIC(NumLFTR , "Number of loop exit tests replaced");
61 STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
62 STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
64 // Trip count verification can be enabled by default under NDEBUG if we
65 // implement a strong expression equivalence checker in SCEV. Until then, we
66 // use the verify-indvars flag, which may assert in some cases.
67 static cl::opt<bool> VerifyIndvars(
68 "verify-indvars", cl::Hidden,
69 cl::desc("Verify the ScalarEvolution result after running indvars"));
71 static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden,
72 cl::desc("Reduce live induction variables."));
74 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
76 static cl::opt<ReplaceExitVal> ReplaceExitValue(
77 "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
78 cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
79 cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
80 clEnumValN(OnlyCheapRepl, "cheap",
81 "only replace exit value when the cost is cheap"),
82 clEnumValN(AlwaysRepl, "always",
83 "always replace exit value whenever possible"),
89 class IndVarSimplify : public LoopPass {
93 TargetLibraryInfo *TLI;
94 const TargetTransformInfo *TTI;
96 SmallVector<WeakVH, 16> DeadInsts;
100 static char ID; // Pass identification, replacement for typeid
102 : LoopPass(ID), LI(nullptr), SE(nullptr), DT(nullptr), Changed(false) {
103 initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
106 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
108 void getAnalysisUsage(AnalysisUsage &AU) const override {
109 AU.addRequired<DominatorTreeWrapperPass>();
110 AU.addRequired<LoopInfoWrapperPass>();
111 AU.addRequired<ScalarEvolutionWrapperPass>();
112 AU.addRequiredID(LoopSimplifyID);
113 AU.addRequiredID(LCSSAID);
114 AU.addPreserved<GlobalsAAWrapperPass>();
115 AU.addPreserved<ScalarEvolutionWrapperPass>();
116 AU.addPreservedID(LoopSimplifyID);
117 AU.addPreservedID(LCSSAID);
118 AU.setPreservesCFG();
122 void releaseMemory() override {
126 bool isValidRewrite(Value *FromVal, Value *ToVal);
128 void handleFloatingPointIV(Loop *L, PHINode *PH);
129 void rewriteNonIntegerIVs(Loop *L);
131 void simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
133 bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
134 void rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
135 void rewriteFirstIterationLoopExitValues(Loop *L);
137 Value *linearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
138 PHINode *IndVar, SCEVExpander &Rewriter);
140 void sinkUnusedInvariants(Loop *L);
142 Value *expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L,
143 Instruction *InsertPt, Type *Ty);
147 char IndVarSimplify::ID = 0;
148 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
149 "Induction Variable Simplification", false, false)
150 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
151 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
152 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
153 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
154 INITIALIZE_PASS_DEPENDENCY(LCSSA)
155 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
156 "Induction Variable Simplification", false, false)
158 Pass *llvm::createIndVarSimplifyPass() {
159 return new IndVarSimplify();
162 /// Return true if the SCEV expansion generated by the rewriter can replace the
163 /// original value. SCEV guarantees that it produces the same value, but the way
164 /// it is produced may be illegal IR. Ideally, this function will only be
165 /// called for verification.
166 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
167 // If an SCEV expression subsumed multiple pointers, its expansion could
168 // reassociate the GEP changing the base pointer. This is illegal because the
169 // final address produced by a GEP chain must be inbounds relative to its
170 // underlying object. Otherwise basic alias analysis, among other things,
171 // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
172 // producing an expression involving multiple pointers. Until then, we must
175 // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
176 // because it understands lcssa phis while SCEV does not.
177 Value *FromPtr = FromVal;
178 Value *ToPtr = ToVal;
179 if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) {
180 FromPtr = GEP->getPointerOperand();
182 if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) {
183 ToPtr = GEP->getPointerOperand();
185 if (FromPtr != FromVal || ToPtr != ToVal) {
186 // Quickly check the common case
187 if (FromPtr == ToPtr)
190 // SCEV may have rewritten an expression that produces the GEP's pointer
191 // operand. That's ok as long as the pointer operand has the same base
192 // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
193 // base of a recurrence. This handles the case in which SCEV expansion
194 // converts a pointer type recurrence into a nonrecurrent pointer base
195 // indexed by an integer recurrence.
197 // If the GEP base pointer is a vector of pointers, abort.
198 if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
201 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
202 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
203 if (FromBase == ToBase)
206 DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
207 << *FromBase << " != " << *ToBase << "\n");
214 /// Determine the insertion point for this user. By default, insert immediately
215 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
216 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
217 /// common dominator for the incoming blocks.
218 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
220 PHINode *PHI = dyn_cast<PHINode>(User);
224 Instruction *InsertPt = nullptr;
225 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
226 if (PHI->getIncomingValue(i) != Def)
229 BasicBlock *InsertBB = PHI->getIncomingBlock(i);
231 InsertPt = InsertBB->getTerminator();
234 InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
235 InsertPt = InsertBB->getTerminator();
237 assert(InsertPt && "Missing phi operand");
238 assert((!isa<Instruction>(Def) ||
239 DT->dominates(cast<Instruction>(Def), InsertPt)) &&
240 "def does not dominate all uses");
244 //===----------------------------------------------------------------------===//
245 // rewriteNonIntegerIVs and helpers. Prefer integer IVs.
246 //===----------------------------------------------------------------------===//
248 /// Convert APF to an integer, if possible.
249 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
250 bool isExact = false;
251 // See if we can convert this to an int64_t
253 if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
254 &isExact) != APFloat::opOK || !isExact)
260 /// If the loop has floating induction variable then insert corresponding
261 /// integer induction variable if possible.
263 /// for(double i = 0; i < 10000; ++i)
265 /// is converted into
266 /// for(int i = 0; i < 10000; ++i)
269 void IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
270 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
271 unsigned BackEdge = IncomingEdge^1;
273 // Check incoming value.
274 auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
277 if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
280 // Check IV increment. Reject this PN if increment operation is not
281 // an add or increment value can not be represented by an integer.
282 auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
283 if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
285 // If this is not an add of the PHI with a constantfp, or if the constant fp
286 // is not an integer, bail out.
287 ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
289 if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
290 !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
293 // Check Incr uses. One user is PN and the other user is an exit condition
294 // used by the conditional terminator.
295 Value::user_iterator IncrUse = Incr->user_begin();
296 Instruction *U1 = cast<Instruction>(*IncrUse++);
297 if (IncrUse == Incr->user_end()) return;
298 Instruction *U2 = cast<Instruction>(*IncrUse++);
299 if (IncrUse != Incr->user_end()) return;
301 // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
302 // only used by a branch, we can't transform it.
303 FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
305 Compare = dyn_cast<FCmpInst>(U2);
306 if (!Compare || !Compare->hasOneUse() ||
307 !isa<BranchInst>(Compare->user_back()))
310 BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
312 // We need to verify that the branch actually controls the iteration count
313 // of the loop. If not, the new IV can overflow and no one will notice.
314 // The branch block must be in the loop and one of the successors must be out
316 assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
317 if (!L->contains(TheBr->getParent()) ||
318 (L->contains(TheBr->getSuccessor(0)) &&
319 L->contains(TheBr->getSuccessor(1))))
323 // If it isn't a comparison with an integer-as-fp (the exit value), we can't
325 ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
327 if (ExitValueVal == nullptr ||
328 !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
331 // Find new predicate for integer comparison.
332 CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
333 switch (Compare->getPredicate()) {
334 default: return; // Unknown comparison.
335 case CmpInst::FCMP_OEQ:
336 case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
337 case CmpInst::FCMP_ONE:
338 case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
339 case CmpInst::FCMP_OGT:
340 case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
341 case CmpInst::FCMP_OGE:
342 case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
343 case CmpInst::FCMP_OLT:
344 case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
345 case CmpInst::FCMP_OLE:
346 case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
349 // We convert the floating point induction variable to a signed i32 value if
350 // we can. This is only safe if the comparison will not overflow in a way
351 // that won't be trapped by the integer equivalent operations. Check for this
353 // TODO: We could use i64 if it is native and the range requires it.
355 // The start/stride/exit values must all fit in signed i32.
356 if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
359 // If not actually striding (add x, 0.0), avoid touching the code.
363 // Positive and negative strides have different safety conditions.
365 // If we have a positive stride, we require the init to be less than the
367 if (InitValue >= ExitValue)
370 uint32_t Range = uint32_t(ExitValue-InitValue);
371 // Check for infinite loop, either:
372 // while (i <= Exit) or until (i > Exit)
373 if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
374 if (++Range == 0) return; // Range overflows.
377 unsigned Leftover = Range % uint32_t(IncValue);
379 // If this is an equality comparison, we require that the strided value
380 // exactly land on the exit value, otherwise the IV condition will wrap
381 // around and do things the fp IV wouldn't.
382 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
386 // If the stride would wrap around the i32 before exiting, we can't
388 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
392 // If we have a negative stride, we require the init to be greater than the
394 if (InitValue <= ExitValue)
397 uint32_t Range = uint32_t(InitValue-ExitValue);
398 // Check for infinite loop, either:
399 // while (i >= Exit) or until (i < Exit)
400 if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
401 if (++Range == 0) return; // Range overflows.
404 unsigned Leftover = Range % uint32_t(-IncValue);
406 // If this is an equality comparison, we require that the strided value
407 // exactly land on the exit value, otherwise the IV condition will wrap
408 // around and do things the fp IV wouldn't.
409 if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
413 // If the stride would wrap around the i32 before exiting, we can't
415 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
419 IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
421 // Insert new integer induction variable.
422 PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
423 NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
424 PN->getIncomingBlock(IncomingEdge));
427 BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
428 Incr->getName()+".int", Incr);
429 NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
431 ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
432 ConstantInt::get(Int32Ty, ExitValue),
435 // In the following deletions, PN may become dead and may be deleted.
436 // Use a WeakVH to observe whether this happens.
439 // Delete the old floating point exit comparison. The branch starts using the
441 NewCompare->takeName(Compare);
442 Compare->replaceAllUsesWith(NewCompare);
443 RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
445 // Delete the old floating point increment.
446 Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
447 RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
449 // If the FP induction variable still has uses, this is because something else
450 // in the loop uses its value. In order to canonicalize the induction
451 // variable, we chose to eliminate the IV and rewrite it in terms of an
454 // We give preference to sitofp over uitofp because it is faster on most
457 Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
458 &*PN->getParent()->getFirstInsertionPt());
459 PN->replaceAllUsesWith(Conv);
460 RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
465 void IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
466 // First step. Check to see if there are any floating-point recurrences.
467 // If there are, change them into integer recurrences, permitting analysis by
468 // the SCEV routines.
470 BasicBlock *Header = L->getHeader();
472 SmallVector<WeakVH, 8> PHIs;
473 for (BasicBlock::iterator I = Header->begin();
474 PHINode *PN = dyn_cast<PHINode>(I); ++I)
477 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
478 if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
479 handleFloatingPointIV(L, PN);
481 // If the loop previously had floating-point IV, ScalarEvolution
482 // may not have been able to compute a trip count. Now that we've done some
483 // re-writing, the trip count may be computable.
489 // Collect information about PHI nodes which can be transformed in
490 // rewriteLoopExitValues.
493 unsigned Ith; // Ith incoming value.
494 Value *Val; // Exit value after expansion.
495 bool HighCost; // High Cost when expansion.
496 bool SafePhi; // LCSSASafePhiForRAUW.
498 RewritePhi(PHINode *P, unsigned I, Value *V, bool H, bool S)
499 : PN(P), Ith(I), Val(V), HighCost(H), SafePhi(S) {}
503 Value *IndVarSimplify::expandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S,
504 Loop *L, Instruction *InsertPt,
506 // Before expanding S into an expensive LLVM expression, see if we can use an
507 // already existing value as the expansion for S.
508 if (Value *ExistingValue = Rewriter.findExistingExpansion(S, InsertPt, L))
509 if (ExistingValue->getType() == ResultTy)
510 return ExistingValue;
512 // We didn't find anything, fall back to using SCEVExpander.
513 return Rewriter.expandCodeFor(S, ResultTy, InsertPt);
516 //===----------------------------------------------------------------------===//
517 // rewriteLoopExitValues - Optimize IV users outside the loop.
518 // As a side effect, reduces the amount of IV processing within the loop.
519 //===----------------------------------------------------------------------===//
521 /// Check to see if this loop has a computable loop-invariant execution count.
522 /// If so, this means that we can compute the final value of any expressions
523 /// that are recurrent in the loop, and substitute the exit values from the loop
524 /// into any instructions outside of the loop that use the final values of the
525 /// current expressions.
527 /// This is mostly redundant with the regular IndVarSimplify activities that
528 /// happen later, except that it's more powerful in some cases, because it's
529 /// able to brute-force evaluate arbitrary instructions as long as they have
530 /// constant operands at the beginning of the loop.
531 void IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
532 // Verify the input to the pass in already in LCSSA form.
533 assert(L->isLCSSAForm(*DT));
535 SmallVector<BasicBlock*, 8> ExitBlocks;
536 L->getUniqueExitBlocks(ExitBlocks);
538 SmallVector<RewritePhi, 8> RewritePhiSet;
539 // Find all values that are computed inside the loop, but used outside of it.
540 // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
541 // the exit blocks of the loop to find them.
542 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
543 BasicBlock *ExitBB = ExitBlocks[i];
545 // If there are no PHI nodes in this exit block, then no values defined
546 // inside the loop are used on this path, skip it.
547 PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
550 unsigned NumPreds = PN->getNumIncomingValues();
552 // We would like to be able to RAUW single-incoming value PHI nodes. We
553 // have to be certain this is safe even when this is an LCSSA PHI node.
554 // While the computed exit value is no longer varying in *this* loop, the
555 // exit block may be an exit block for an outer containing loop as well,
556 // the exit value may be varying in the outer loop, and thus it may still
557 // require an LCSSA PHI node. The safe case is when this is
558 // single-predecessor PHI node (LCSSA) and the exit block containing it is
559 // part of the enclosing loop, or this is the outer most loop of the nest.
560 // In either case the exit value could (at most) be varying in the same
561 // loop body as the phi node itself. Thus if it is in turn used outside of
562 // an enclosing loop it will only be via a separate LCSSA node.
563 bool LCSSASafePhiForRAUW =
565 (!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB));
567 // Iterate over all of the PHI nodes.
568 BasicBlock::iterator BBI = ExitBB->begin();
569 while ((PN = dyn_cast<PHINode>(BBI++))) {
571 continue; // dead use, don't replace it
573 // SCEV only supports integer expressions for now.
574 if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
577 // It's necessary to tell ScalarEvolution about this explicitly so that
578 // it can walk the def-use list and forget all SCEVs, as it may not be
579 // watching the PHI itself. Once the new exit value is in place, there
580 // may not be a def-use connection between the loop and every instruction
581 // which got a SCEVAddRecExpr for that loop.
584 // Iterate over all of the values in all the PHI nodes.
585 for (unsigned i = 0; i != NumPreds; ++i) {
586 // If the value being merged in is not integer or is not defined
587 // in the loop, skip it.
588 Value *InVal = PN->getIncomingValue(i);
589 if (!isa<Instruction>(InVal))
592 // If this pred is for a subloop, not L itself, skip it.
593 if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
594 continue; // The Block is in a subloop, skip it.
596 // Check that InVal is defined in the loop.
597 Instruction *Inst = cast<Instruction>(InVal);
598 if (!L->contains(Inst))
601 // Okay, this instruction has a user outside of the current loop
602 // and varies predictably *inside* the loop. Evaluate the value it
603 // contains when the loop exits, if possible.
604 const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
605 if (!SE->isLoopInvariant(ExitValue, L) ||
606 !isSafeToExpand(ExitValue, *SE))
609 // Computing the value outside of the loop brings no benefit if :
610 // - it is definitely used inside the loop in a way which can not be
612 // - no use outside of the loop can take advantage of hoisting the
613 // computation out of the loop
614 if (ExitValue->getSCEVType()>=scMulExpr) {
615 unsigned NumHardInternalUses = 0;
616 unsigned NumSoftExternalUses = 0;
617 unsigned NumUses = 0;
618 for (auto IB = Inst->user_begin(), IE = Inst->user_end();
619 IB != IE && NumUses <= 6; ++IB) {
620 Instruction *UseInstr = cast<Instruction>(*IB);
621 unsigned Opc = UseInstr->getOpcode();
623 if (L->contains(UseInstr)) {
624 if (Opc == Instruction::Call || Opc == Instruction::Ret)
625 NumHardInternalUses++;
627 if (Opc == Instruction::PHI) {
628 // Do not count the Phi as a use. LCSSA may have inserted
629 // plenty of trivial ones.
631 for (auto PB = UseInstr->user_begin(),
632 PE = UseInstr->user_end();
633 PB != PE && NumUses <= 6; ++PB, ++NumUses) {
634 unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
635 if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
636 NumSoftExternalUses++;
640 if (Opc != Instruction::Call && Opc != Instruction::Ret)
641 NumSoftExternalUses++;
644 if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
648 bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
650 expandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->getType());
652 DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
653 << " LoopVal = " << *Inst << "\n");
655 if (!isValidRewrite(Inst, ExitVal)) {
656 DeadInsts.push_back(ExitVal);
660 // Collect all the candidate PHINodes to be rewritten.
661 RewritePhiSet.push_back(
662 RewritePhi(PN, i, ExitVal, HighCost, LCSSASafePhiForRAUW));
667 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
670 for (const RewritePhi &Phi : RewritePhiSet) {
671 PHINode *PN = Phi.PN;
672 Value *ExitVal = Phi.Val;
674 // Only do the rewrite when the ExitValue can be expanded cheaply.
675 // If LoopCanBeDel is true, rewrite exit value aggressively.
676 if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
677 DeadInsts.push_back(ExitVal);
683 Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
684 PN->setIncomingValue(Phi.Ith, ExitVal);
686 // If this instruction is dead now, delete it. Don't do it now to avoid
687 // invalidating iterators.
688 if (isInstructionTriviallyDead(Inst, TLI))
689 DeadInsts.push_back(Inst);
691 // If we determined that this PHI is safe to replace even if an LCSSA
694 PN->replaceAllUsesWith(ExitVal);
695 PN->eraseFromParent();
699 // The insertion point instruction may have been deleted; clear it out
700 // so that the rewriter doesn't trip over it later.
701 Rewriter.clearInsertPoint();
704 //===---------------------------------------------------------------------===//
705 // rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
706 // they will exit at the first iteration.
707 //===---------------------------------------------------------------------===//
709 /// Check to see if this loop has loop invariant conditions which lead to loop
710 /// exits. If so, we know that if the exit path is taken, it is at the first
711 /// loop iteration. This lets us predict exit values of PHI nodes that live in
713 void IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
714 // Verify the input to the pass is already in LCSSA form.
715 assert(L->isLCSSAForm(*DT));
717 SmallVector<BasicBlock *, 8> ExitBlocks;
718 L->getUniqueExitBlocks(ExitBlocks);
720 for (auto *ExitBB : ExitBlocks) {
721 BasicBlock::iterator begin = ExitBB->begin();
722 // If there are no more PHI nodes in this exit block, then no more
723 // values defined inside the loop are used on this path.
724 while (auto *PN = dyn_cast<PHINode>(begin++)) {
725 for (unsigned IncomingValIdx = 0, e = PN->getNumIncomingValues();
726 IncomingValIdx != e; ++IncomingValIdx) {
727 auto *IncomingBB = PN->getIncomingBlock(IncomingValIdx);
728 if (!L->contains(IncomingBB))
731 // Get condition that leads to the exit path.
732 auto *TermInst = IncomingBB->getTerminator();
734 Value *Cond = nullptr;
735 if (auto *BI = dyn_cast<BranchInst>(TermInst)) {
736 // Must be a conditional branch, otherwise the block
737 // should not be in the loop.
738 Cond = BI->getCondition();
739 } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
740 Cond = SI->getCondition();
742 // All non-instructions are loop-invariant.
743 if (isa<Instruction>(Cond) && !L->isLoopInvariant(Cond))
747 dyn_cast<PHINode>(PN->getIncomingValue(IncomingValIdx));
749 // Only deal with PHIs.
753 // If ExitVal is a PHI on the loop header, then we know its
754 // value along this exit because the exit can only be taken
755 // on the first iteration.
756 auto *LoopPreheader = L->getLoopPreheader();
757 assert(LoopPreheader && "Invalid loop");
758 if (ExitVal->getBasicBlockIndex(LoopPreheader) != -1) {
759 assert(ExitVal->getParent() == L->getHeader() &&
760 "ExitVal must be in loop header");
761 PN->setIncomingValue(IncomingValIdx,
762 ExitVal->getIncomingValueForBlock(LoopPreheader));
769 /// Check whether it is possible to delete the loop after rewriting exit
770 /// value. If it is possible, ignore ReplaceExitValue and do rewriting
772 bool IndVarSimplify::canLoopBeDeleted(
773 Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
775 BasicBlock *Preheader = L->getLoopPreheader();
776 // If there is no preheader, the loop will not be deleted.
780 // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
781 // We obviate multiple ExitingBlocks case for simplicity.
782 // TODO: If we see testcase with multiple ExitingBlocks can be deleted
783 // after exit value rewriting, we can enhance the logic here.
784 SmallVector<BasicBlock *, 4> ExitingBlocks;
785 L->getExitingBlocks(ExitingBlocks);
786 SmallVector<BasicBlock *, 8> ExitBlocks;
787 L->getUniqueExitBlocks(ExitBlocks);
788 if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
791 BasicBlock *ExitBlock = ExitBlocks[0];
792 BasicBlock::iterator BI = ExitBlock->begin();
793 while (PHINode *P = dyn_cast<PHINode>(BI)) {
794 Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
796 // If the Incoming value of P is found in RewritePhiSet, we know it
797 // could be rewritten to use a loop invariant value in transformation
798 // phase later. Skip it in the loop invariant check below.
800 for (const RewritePhi &Phi : RewritePhiSet) {
801 unsigned i = Phi.Ith;
802 if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
809 if (!found && (I = dyn_cast<Instruction>(Incoming)))
810 if (!L->hasLoopInvariantOperands(I))
816 for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
818 for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE;
820 if (BI->mayHaveSideEffects())
828 //===----------------------------------------------------------------------===//
829 // IV Widening - Extend the width of an IV to cover its widest uses.
830 //===----------------------------------------------------------------------===//
833 // Collect information about induction variables that are used by sign/zero
834 // extend operations. This information is recorded by CollectExtend and provides
835 // the input to WidenIV.
837 PHINode *NarrowIV = nullptr;
838 Type *WidestNativeType = nullptr; // Widest integer type created [sz]ext
839 bool IsSigned = false; // Was a sext user seen before a zext?
843 /// Update information about the induction variable that is extended by this
844 /// sign or zero extend operation. This is used to determine the final width of
845 /// the IV before actually widening it.
846 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
847 const TargetTransformInfo *TTI) {
848 bool IsSigned = Cast->getOpcode() == Instruction::SExt;
849 if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
852 Type *Ty = Cast->getType();
853 uint64_t Width = SE->getTypeSizeInBits(Ty);
854 if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
857 // Cast is either an sext or zext up to this point.
858 // We should not widen an indvar if arithmetics on the wider indvar are more
859 // expensive than those on the narrower indvar. We check only the cost of ADD
860 // because at least an ADD is required to increment the induction variable. We
861 // could compute more comprehensively the cost of all instructions on the
862 // induction variable when necessary.
864 TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
865 TTI->getArithmeticInstrCost(Instruction::Add,
866 Cast->getOperand(0)->getType())) {
870 if (!WI.WidestNativeType) {
871 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
872 WI.IsSigned = IsSigned;
876 // We extend the IV to satisfy the sign of its first user, arbitrarily.
877 if (WI.IsSigned != IsSigned)
880 if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
881 WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
886 /// Record a link in the Narrow IV def-use chain along with the WideIV that
887 /// computes the same value as the Narrow IV def. This avoids caching Use*
889 struct NarrowIVDefUse {
890 Instruction *NarrowDef = nullptr;
891 Instruction *NarrowUse = nullptr;
892 Instruction *WideDef = nullptr;
894 // True if the narrow def is never negative. Tracking this information lets
895 // us use a sign extension instead of a zero extension or vice versa, when
896 // profitable and legal.
897 bool NeverNegative = false;
899 NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
901 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
902 NeverNegative(NeverNegative) {}
905 /// The goal of this transform is to remove sign and zero extends without
906 /// creating any new induction variables. To do this, it creates a new phi of
907 /// the wider type and redirects all users, either removing extends or inserting
908 /// truncs whenever we stop propagating the type.
924 Instruction *WideInc;
925 const SCEV *WideIncExpr;
926 SmallVectorImpl<WeakVH> &DeadInsts;
928 SmallPtrSet<Instruction*,16> Widened;
929 SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
932 WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
933 ScalarEvolution *SEv, DominatorTree *DTree,
934 SmallVectorImpl<WeakVH> &DI) :
935 OrigPhi(WI.NarrowIV),
936 WideType(WI.WidestNativeType),
937 IsSigned(WI.IsSigned),
939 L(LI->getLoopFor(OrigPhi->getParent())),
944 WideIncExpr(nullptr),
946 assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
949 PHINode *createWideIV(SCEVExpander &Rewriter);
952 Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
955 Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
956 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
957 const SCEVAddRecExpr *WideAR);
958 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
960 const SCEVAddRecExpr *getWideRecurrence(Instruction *NarrowUse);
962 const SCEVAddRecExpr* getExtendedOperandRecurrence(NarrowIVDefUse DU);
964 const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
965 unsigned OpCode) const;
967 Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
969 bool widenLoopCompare(NarrowIVDefUse DU);
971 void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
973 } // anonymous namespace
975 /// Perform a quick domtree based check for loop invariance assuming that V is
976 /// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this
978 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
979 Instruction *Inst = dyn_cast<Instruction>(V);
983 return DT->properlyDominates(Inst->getParent(), L->getHeader());
986 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
987 bool IsSigned, Instruction *Use) {
988 // Set the debug location and conservative insertion point.
989 IRBuilder<> Builder(Use);
990 // Hoist the insertion point into loop preheaders as far as possible.
991 for (const Loop *L = LI->getLoopFor(Use->getParent());
992 L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
993 L = L->getParentLoop())
994 Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
996 return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
997 Builder.CreateZExt(NarrowOper, WideType);
1000 /// Instantiate a wide operation to replace a narrow operation. This only needs
1001 /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1002 /// 0 for any operation we decide not to clone.
1003 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1004 const SCEVAddRecExpr *WideAR) {
1005 unsigned Opcode = DU.NarrowUse->getOpcode();
1009 case Instruction::Add:
1010 case Instruction::Mul:
1011 case Instruction::UDiv:
1012 case Instruction::Sub:
1013 return cloneArithmeticIVUser(DU, WideAR);
1015 case Instruction::And:
1016 case Instruction::Or:
1017 case Instruction::Xor:
1018 case Instruction::Shl:
1019 case Instruction::LShr:
1020 case Instruction::AShr:
1021 return cloneBitwiseIVUser(DU);
1025 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1026 Instruction *NarrowUse = DU.NarrowUse;
1027 Instruction *NarrowDef = DU.NarrowDef;
1028 Instruction *WideDef = DU.WideDef;
1030 DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1032 // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1033 // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1034 // invariant and will be folded or hoisted. If it actually comes from a
1035 // widened IV, it should be removed during a future call to widenIVUse.
1036 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1038 : createExtendInst(NarrowUse->getOperand(0), WideType,
1039 IsSigned, NarrowUse);
1040 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1042 : createExtendInst(NarrowUse->getOperand(1), WideType,
1043 IsSigned, NarrowUse);
1045 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1046 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1047 NarrowBO->getName());
1048 IRBuilder<> Builder(NarrowUse);
1049 Builder.Insert(WideBO);
1050 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
1051 if (OBO->hasNoUnsignedWrap())
1052 WideBO->setHasNoUnsignedWrap();
1053 if (OBO->hasNoSignedWrap())
1054 WideBO->setHasNoSignedWrap();
1059 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1060 const SCEVAddRecExpr *WideAR) {
1061 Instruction *NarrowUse = DU.NarrowUse;
1062 Instruction *NarrowDef = DU.NarrowDef;
1063 Instruction *WideDef = DU.WideDef;
1065 DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1067 unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1069 // We're trying to find X such that
1071 // Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1073 // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1074 // and check using SCEV if any of them are correct.
1076 // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1077 // correct solution to X.
1078 auto GuessNonIVOperand = [&](bool SignExt) {
1079 const SCEV *WideLHS;
1080 const SCEV *WideRHS;
1082 auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1084 return SE->getSignExtendExpr(S, Ty);
1085 return SE->getZeroExtendExpr(S, Ty);
1089 WideLHS = SE->getSCEV(WideDef);
1090 const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1091 WideRHS = GetExtend(NarrowRHS, WideType);
1093 const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1094 WideLHS = GetExtend(NarrowLHS, WideType);
1095 WideRHS = SE->getSCEV(WideDef);
1098 // WideUse is "WideDef `op.wide` X" as described in the comment.
1099 const SCEV *WideUse = nullptr;
1101 switch (NarrowUse->getOpcode()) {
1103 llvm_unreachable("No other possibility!");
1105 case Instruction::Add:
1106 WideUse = SE->getAddExpr(WideLHS, WideRHS);
1109 case Instruction::Mul:
1110 WideUse = SE->getMulExpr(WideLHS, WideRHS);
1113 case Instruction::UDiv:
1114 WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1117 case Instruction::Sub:
1118 WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1122 return WideUse == WideAR;
1125 bool SignExtend = IsSigned;
1126 if (!GuessNonIVOperand(SignExtend)) {
1127 SignExtend = !SignExtend;
1128 if (!GuessNonIVOperand(SignExtend))
1132 Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1134 : createExtendInst(NarrowUse->getOperand(0), WideType,
1135 SignExtend, NarrowUse);
1136 Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1138 : createExtendInst(NarrowUse->getOperand(1), WideType,
1139 SignExtend, NarrowUse);
1141 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1142 auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1143 NarrowBO->getName());
1145 IRBuilder<> Builder(NarrowUse);
1146 Builder.Insert(WideBO);
1147 if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
1148 if (OBO->hasNoUnsignedWrap())
1149 WideBO->setHasNoUnsignedWrap();
1150 if (OBO->hasNoSignedWrap())
1151 WideBO->setHasNoSignedWrap();
1156 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1157 unsigned OpCode) const {
1158 if (OpCode == Instruction::Add)
1159 return SE->getAddExpr(LHS, RHS);
1160 if (OpCode == Instruction::Sub)
1161 return SE->getMinusSCEV(LHS, RHS);
1162 if (OpCode == Instruction::Mul)
1163 return SE->getMulExpr(LHS, RHS);
1165 llvm_unreachable("Unsupported opcode.");
1168 /// No-wrap operations can transfer sign extension of their result to their
1169 /// operands. Generate the SCEV value for the widened operation without
1170 /// actually modifying the IR yet. If the expression after extending the
1171 /// operands is an AddRec for this loop, return it.
1172 const SCEVAddRecExpr* WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1174 // Handle the common case of add<nsw/nuw>
1175 const unsigned OpCode = DU.NarrowUse->getOpcode();
1176 // Only Add/Sub/Mul instructions supported yet.
1177 if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1178 OpCode != Instruction::Mul)
1181 // One operand (NarrowDef) has already been extended to WideDef. Now determine
1182 // if extending the other will lead to a recurrence.
1183 const unsigned ExtendOperIdx =
1184 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1185 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1187 const SCEV *ExtendOperExpr = nullptr;
1188 const OverflowingBinaryOperator *OBO =
1189 cast<OverflowingBinaryOperator>(DU.NarrowUse);
1190 if (IsSigned && OBO->hasNoSignedWrap())
1191 ExtendOperExpr = SE->getSignExtendExpr(
1192 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1193 else if(!IsSigned && OBO->hasNoUnsignedWrap())
1194 ExtendOperExpr = SE->getZeroExtendExpr(
1195 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1199 // When creating this SCEV expr, don't apply the current operations NSW or NUW
1200 // flags. This instruction may be guarded by control flow that the no-wrap
1201 // behavior depends on. Non-control-equivalent instructions can be mapped to
1202 // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1203 // semantics to those operations.
1204 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1205 const SCEV *rhs = ExtendOperExpr;
1207 // Let's swap operands to the initial order for the case of non-commutative
1208 // operations, like SUB. See PR21014.
1209 if (ExtendOperIdx == 0)
1210 std::swap(lhs, rhs);
1211 const SCEVAddRecExpr *AddRec =
1212 dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1214 if (!AddRec || AddRec->getLoop() != L)
1219 /// Is this instruction potentially interesting for further simplification after
1220 /// widening it's type? In other words, can the extend be safely hoisted out of
1221 /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1222 /// so, return the sign or zero extended recurrence. Otherwise return NULL.
1223 const SCEVAddRecExpr *WidenIV::getWideRecurrence(Instruction *NarrowUse) {
1224 if (!SE->isSCEVable(NarrowUse->getType()))
1227 const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
1228 if (SE->getTypeSizeInBits(NarrowExpr->getType())
1229 >= SE->getTypeSizeInBits(WideType)) {
1230 // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1231 // index. So don't follow this use.
1235 const SCEV *WideExpr = IsSigned ?
1236 SE->getSignExtendExpr(NarrowExpr, WideType) :
1237 SE->getZeroExtendExpr(NarrowExpr, WideType);
1238 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1239 if (!AddRec || AddRec->getLoop() != L)
1244 /// This IV user cannot be widen. Replace this use of the original narrow IV
1245 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
1246 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) {
1247 DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
1248 << " for user " << *DU.NarrowUse << "\n");
1249 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
1250 Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1251 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1254 /// If the narrow use is a compare instruction, then widen the compare
1255 // (and possibly the other operand). The extend operation is hoisted into the
1256 // loop preheader as far as possible.
1257 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1258 ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1262 // We can legally widen the comparison in the following two cases:
1264 // - The signedness of the IV extension and comparison match
1266 // - The narrow IV is always positive (and thus its sign extension is equal
1267 // to its zero extension). For instance, let's say we're zero extending
1268 // %narrow for the following use
1270 // icmp slt i32 %narrow, %val ... (A)
1272 // and %narrow is always positive. Then
1274 // (A) == icmp slt i32 sext(%narrow), sext(%val)
1275 // == icmp slt i32 zext(%narrow), sext(%val)
1277 if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1280 Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1281 unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1282 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1283 assert (CastWidth <= IVWidth && "Unexpected width while widening compare.");
1285 // Widen the compare instruction.
1286 IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
1287 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1289 // Widen the other operand of the compare, if necessary.
1290 if (CastWidth < IVWidth) {
1291 Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1292 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1297 /// Determine whether an individual user of the narrow IV can be widened. If so,
1298 /// return the wide clone of the user.
1299 Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1301 // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1302 if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1303 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1304 // For LCSSA phis, sink the truncate outside the loop.
1305 // After SimplifyCFG most loop exit targets have a single predecessor.
1306 // Otherwise fall back to a truncate within the loop.
1307 if (UsePhi->getNumOperands() != 1)
1308 truncateIVUse(DU, DT);
1311 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1313 WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1314 IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1315 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1316 UsePhi->replaceAllUsesWith(Trunc);
1317 DeadInsts.emplace_back(UsePhi);
1318 DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
1319 << " to " << *WidePhi << "\n");
1324 // Our raison d'etre! Eliminate sign and zero extension.
1325 if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
1326 Value *NewDef = DU.WideDef;
1327 if (DU.NarrowUse->getType() != WideType) {
1328 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1329 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1330 if (CastWidth < IVWidth) {
1331 // The cast isn't as wide as the IV, so insert a Trunc.
1332 IRBuilder<> Builder(DU.NarrowUse);
1333 NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1336 // A wider extend was hidden behind a narrower one. This may induce
1337 // another round of IV widening in which the intermediate IV becomes
1338 // dead. It should be very rare.
1339 DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1340 << " not wide enough to subsume " << *DU.NarrowUse << "\n");
1341 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1342 NewDef = DU.NarrowUse;
1345 if (NewDef != DU.NarrowUse) {
1346 DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1347 << " replaced by " << *DU.WideDef << "\n");
1349 DU.NarrowUse->replaceAllUsesWith(NewDef);
1350 DeadInsts.emplace_back(DU.NarrowUse);
1352 // Now that the extend is gone, we want to expose it's uses for potential
1353 // further simplification. We don't need to directly inform SimplifyIVUsers
1354 // of the new users, because their parent IV will be processed later as a
1355 // new loop phi. If we preserved IVUsers analysis, we would also want to
1356 // push the uses of WideDef here.
1358 // No further widening is needed. The deceased [sz]ext had done it for us.
1362 // Does this user itself evaluate to a recurrence after widening?
1363 const SCEVAddRecExpr *WideAddRec = getWideRecurrence(DU.NarrowUse);
1365 WideAddRec = getExtendedOperandRecurrence(DU);
1368 // If use is a loop condition, try to promote the condition instead of
1369 // truncating the IV first.
1370 if (widenLoopCompare(DU))
1373 // This user does not evaluate to a recurence after widening, so don't
1374 // follow it. Instead insert a Trunc to kill off the original use,
1375 // eventually isolating the original narrow IV so it can be removed.
1376 truncateIVUse(DU, DT);
1379 // Assume block terminators cannot evaluate to a recurrence. We can't to
1380 // insert a Trunc after a terminator if there happens to be a critical edge.
1381 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1382 "SCEV is not expected to evaluate a block terminator");
1384 // Reuse the IV increment that SCEVExpander created as long as it dominates
1386 Instruction *WideUse = nullptr;
1387 if (WideAddRec == WideIncExpr
1388 && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1391 WideUse = cloneIVUser(DU, WideAddRec);
1395 // Evaluation of WideAddRec ensured that the narrow expression could be
1396 // extended outside the loop without overflow. This suggests that the wide use
1397 // evaluates to the same expression as the extended narrow use, but doesn't
1398 // absolutely guarantee it. Hence the following failsafe check. In rare cases
1399 // where it fails, we simply throw away the newly created wide use.
1400 if (WideAddRec != SE->getSCEV(WideUse)) {
1401 DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
1402 << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
1403 DeadInsts.emplace_back(WideUse);
1407 // Returning WideUse pushes it on the worklist.
1411 /// Add eligible users of NarrowDef to NarrowIVUsers.
1413 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1414 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1415 bool NeverNegative =
1416 SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1417 SE->getConstant(NarrowSCEV->getType(), 0));
1418 for (User *U : NarrowDef->users()) {
1419 Instruction *NarrowUser = cast<Instruction>(U);
1421 // Handle data flow merges and bizarre phi cycles.
1422 if (!Widened.insert(NarrowUser).second)
1425 NarrowIVUsers.push_back(
1426 NarrowIVDefUse(NarrowDef, NarrowUser, WideDef, NeverNegative));
1430 /// Process a single induction variable. First use the SCEVExpander to create a
1431 /// wide induction variable that evaluates to the same recurrence as the
1432 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1433 /// def-use chain. After widenIVUse has processed all interesting IV users, the
1434 /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1436 /// It would be simpler to delete uses as they are processed, but we must avoid
1437 /// invalidating SCEV expressions.
1439 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1440 // Is this phi an induction variable?
1441 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1445 // Widen the induction variable expression.
1446 const SCEV *WideIVExpr = IsSigned ?
1447 SE->getSignExtendExpr(AddRec, WideType) :
1448 SE->getZeroExtendExpr(AddRec, WideType);
1450 assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1451 "Expect the new IV expression to preserve its type");
1453 // Can the IV be extended outside the loop without overflow?
1454 AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1455 if (!AddRec || AddRec->getLoop() != L)
1458 // An AddRec must have loop-invariant operands. Since this AddRec is
1459 // materialized by a loop header phi, the expression cannot have any post-loop
1460 // operands, so they must dominate the loop header.
1461 assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1462 SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
1463 && "Loop header phi recurrence inputs do not dominate the loop");
1465 // The rewriter provides a value for the desired IV expression. This may
1466 // either find an existing phi or materialize a new one. Either way, we
1467 // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1468 // of the phi-SCC dominates the loop entry.
1469 Instruction *InsertPt = &L->getHeader()->front();
1470 WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1472 // Remembering the WideIV increment generated by SCEVExpander allows
1473 // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1474 // employ a general reuse mechanism because the call above is the only call to
1475 // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1476 if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1478 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1479 WideIncExpr = SE->getSCEV(WideInc);
1482 DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1485 // Traverse the def-use chain using a worklist starting at the original IV.
1486 assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1488 Widened.insert(OrigPhi);
1489 pushNarrowIVUsers(OrigPhi, WidePhi);
1491 while (!NarrowIVUsers.empty()) {
1492 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1494 // Process a def-use edge. This may replace the use, so don't hold a
1495 // use_iterator across it.
1496 Instruction *WideUse = widenIVUse(DU, Rewriter);
1498 // Follow all def-use edges from the previous narrow use.
1500 pushNarrowIVUsers(DU.NarrowUse, WideUse);
1502 // widenIVUse may have removed the def-use edge.
1503 if (DU.NarrowDef->use_empty())
1504 DeadInsts.emplace_back(DU.NarrowDef);
1509 //===----------------------------------------------------------------------===//
1510 // Live IV Reduction - Minimize IVs live across the loop.
1511 //===----------------------------------------------------------------------===//
1514 //===----------------------------------------------------------------------===//
1515 // Simplification of IV users based on SCEV evaluation.
1516 //===----------------------------------------------------------------------===//
1519 class IndVarSimplifyVisitor : public IVVisitor {
1520 ScalarEvolution *SE;
1521 const TargetTransformInfo *TTI;
1527 IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
1528 const TargetTransformInfo *TTI,
1529 const DominatorTree *DTree)
1530 : SE(SCEV), TTI(TTI), IVPhi(IV) {
1532 WI.NarrowIV = IVPhi;
1534 setSplitOverflowIntrinsics();
1537 // Implement the interface used by simplifyUsersOfIV.
1538 void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
1542 /// Iteratively perform simplification on a worklist of IV users. Each
1543 /// successive simplification may push more users which may themselves be
1544 /// candidates for simplification.
1546 /// Sign/Zero extend elimination is interleaved with IV simplification.
1548 void IndVarSimplify::simplifyAndExtend(Loop *L,
1549 SCEVExpander &Rewriter,
1550 LPPassManager &LPM) {
1551 SmallVector<WideIVInfo, 8> WideIVs;
1553 SmallVector<PHINode*, 8> LoopPhis;
1554 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1555 LoopPhis.push_back(cast<PHINode>(I));
1557 // Each round of simplification iterates through the SimplifyIVUsers worklist
1558 // for all current phis, then determines whether any IVs can be
1559 // widened. Widening adds new phis to LoopPhis, inducing another round of
1560 // simplification on the wide IVs.
1561 while (!LoopPhis.empty()) {
1562 // Evaluate as many IV expressions as possible before widening any IVs. This
1563 // forces SCEV to set no-wrap flags before evaluating sign/zero
1564 // extension. The first time SCEV attempts to normalize sign/zero extension,
1565 // the result becomes final. So for the most predictable results, we delay
1566 // evaluation of sign/zero extend evaluation until needed, and avoid running
1567 // other SCEV based analysis prior to simplifyAndExtend.
1569 PHINode *CurrIV = LoopPhis.pop_back_val();
1571 // Information about sign/zero extensions of CurrIV.
1572 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1574 Changed |= simplifyUsersOfIV(CurrIV, SE, DT, &LPM, DeadInsts, &Visitor);
1576 if (Visitor.WI.WidestNativeType) {
1577 WideIVs.push_back(Visitor.WI);
1579 } while(!LoopPhis.empty());
1581 for (; !WideIVs.empty(); WideIVs.pop_back()) {
1582 WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
1583 if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1585 LoopPhis.push_back(WidePhi);
1591 //===----------------------------------------------------------------------===//
1592 // linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1593 //===----------------------------------------------------------------------===//
1595 /// Return true if this loop's backedge taken count expression can be safely and
1596 /// cheaply expanded into an instruction sequence that can be used by
1597 /// linearFunctionTestReplace.
1599 /// TODO: This fails for pointer-type loop counters with greater than one byte
1600 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
1601 /// we could skip this check in the case that the LFTR loop counter (chosen by
1602 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
1603 /// the loop test to an inequality test by checking the target data's alignment
1604 /// of element types (given that the initial pointer value originates from or is
1605 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1606 /// However, we don't yet have a strong motivation for converting loop tests
1607 /// into inequality tests.
1608 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
1609 SCEVExpander &Rewriter) {
1610 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1611 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1612 BackedgeTakenCount->isZero())
1615 if (!L->getExitingBlock())
1618 // Can't rewrite non-branch yet.
1619 if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
1622 if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
1628 /// Return the loop header phi IFF IncV adds a loop invariant value to the phi.
1629 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1630 Instruction *IncI = dyn_cast<Instruction>(IncV);
1634 switch (IncI->getOpcode()) {
1635 case Instruction::Add:
1636 case Instruction::Sub:
1638 case Instruction::GetElementPtr:
1639 // An IV counter must preserve its type.
1640 if (IncI->getNumOperands() == 2)
1646 PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1647 if (Phi && Phi->getParent() == L->getHeader()) {
1648 if (isLoopInvariant(IncI->getOperand(1), L, DT))
1652 if (IncI->getOpcode() == Instruction::GetElementPtr)
1655 // Allow add/sub to be commuted.
1656 Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1657 if (Phi && Phi->getParent() == L->getHeader()) {
1658 if (isLoopInvariant(IncI->getOperand(0), L, DT))
1664 /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
1665 static ICmpInst *getLoopTest(Loop *L) {
1666 assert(L->getExitingBlock() && "expected loop exit");
1668 BasicBlock *LatchBlock = L->getLoopLatch();
1669 // Don't bother with LFTR if the loop is not properly simplified.
1673 BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1674 assert(BI && "expected exit branch");
1676 return dyn_cast<ICmpInst>(BI->getCondition());
1679 /// linearFunctionTestReplace policy. Return true unless we can show that the
1680 /// current exit test is already sufficiently canonical.
1681 static bool needsLFTR(Loop *L, DominatorTree *DT) {
1682 // Do LFTR to simplify the exit condition to an ICMP.
1683 ICmpInst *Cond = getLoopTest(L);
1687 // Do LFTR to simplify the exit ICMP to EQ/NE
1688 ICmpInst::Predicate Pred = Cond->getPredicate();
1689 if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1692 // Look for a loop invariant RHS
1693 Value *LHS = Cond->getOperand(0);
1694 Value *RHS = Cond->getOperand(1);
1695 if (!isLoopInvariant(RHS, L, DT)) {
1696 if (!isLoopInvariant(LHS, L, DT))
1698 std::swap(LHS, RHS);
1700 // Look for a simple IV counter LHS
1701 PHINode *Phi = dyn_cast<PHINode>(LHS);
1703 Phi = getLoopPhiForCounter(LHS, L, DT);
1708 // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
1709 int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
1713 // Do LFTR if the exit condition's IV is *not* a simple counter.
1714 Value *IncV = Phi->getIncomingValue(Idx);
1715 return Phi != getLoopPhiForCounter(IncV, L, DT);
1718 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
1719 /// down to checking that all operands are constant and listing instructions
1720 /// that may hide undef.
1721 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
1723 if (isa<Constant>(V))
1724 return !isa<UndefValue>(V);
1729 // Conservatively handle non-constant non-instructions. For example, Arguments
1731 Instruction *I = dyn_cast<Instruction>(V);
1735 // Load and return values may be undef.
1736 if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
1739 // Optimistically handle other instructions.
1740 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
1741 if (!Visited.insert(*OI).second)
1743 if (!hasConcreteDefImpl(*OI, Visited, Depth+1))
1749 /// Return true if the given value is concrete. We must prove that undef can
1752 /// TODO: If we decide that this is a good approach to checking for undef, we
1753 /// may factor it into a common location.
1754 static bool hasConcreteDef(Value *V) {
1755 SmallPtrSet<Value*, 8> Visited;
1757 return hasConcreteDefImpl(V, Visited, 0);
1760 /// Return true if this IV has any uses other than the (soon to be rewritten)
1762 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1763 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1764 Value *IncV = Phi->getIncomingValue(LatchIdx);
1766 for (User *U : Phi->users())
1767 if (U != Cond && U != IncV) return false;
1769 for (User *U : IncV->users())
1770 if (U != Cond && U != Phi) return false;
1774 /// Find an affine IV in canonical form.
1776 /// BECount may be an i8* pointer type. The pointer difference is already
1777 /// valid count without scaling the address stride, so it remains a pointer
1778 /// expression as far as SCEV is concerned.
1780 /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
1782 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
1784 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
1785 /// This is difficult in general for SCEV because of potential overflow. But we
1786 /// could at least handle constant BECounts.
1787 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
1788 ScalarEvolution *SE, DominatorTree *DT) {
1789 uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
1792 cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
1794 // Loop over all of the PHI nodes, looking for a simple counter.
1795 PHINode *BestPhi = nullptr;
1796 const SCEV *BestInit = nullptr;
1797 BasicBlock *LatchBlock = L->getLoopLatch();
1798 assert(LatchBlock && "needsLFTR should guarantee a loop latch");
1800 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1801 PHINode *Phi = cast<PHINode>(I);
1802 if (!SE->isSCEVable(Phi->getType()))
1805 // Avoid comparing an integer IV against a pointer Limit.
1806 if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
1809 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
1810 if (!AR || AR->getLoop() != L || !AR->isAffine())
1813 // AR may be a pointer type, while BECount is an integer type.
1814 // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
1815 // AR may not be a narrower type, or we may never exit.
1816 uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
1817 if (PhiWidth < BCWidth ||
1818 !L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth))
1821 const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
1822 if (!Step || !Step->isOne())
1825 int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1826 Value *IncV = Phi->getIncomingValue(LatchIdx);
1827 if (getLoopPhiForCounter(IncV, L, DT) != Phi)
1830 // Avoid reusing a potentially undef value to compute other values that may
1831 // have originally had a concrete definition.
1832 if (!hasConcreteDef(Phi)) {
1833 // We explicitly allow unknown phis as long as they are already used by
1834 // the loop test. In this case we assume that performing LFTR could not
1835 // increase the number of undef users.
1836 if (ICmpInst *Cond = getLoopTest(L)) {
1837 if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT)
1838 && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
1843 const SCEV *Init = AR->getStart();
1845 if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
1846 // Don't force a live loop counter if another IV can be used.
1847 if (AlmostDeadIV(Phi, LatchBlock, Cond))
1850 // Prefer to count-from-zero. This is a more "canonical" counter form. It
1851 // also prefers integer to pointer IVs.
1852 if (BestInit->isZero() != Init->isZero()) {
1853 if (BestInit->isZero())
1856 // If two IVs both count from zero or both count from nonzero then the
1857 // narrower is likely a dead phi that has been widened. Use the wider phi
1858 // to allow the other to be eliminated.
1859 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
1868 /// Help linearFunctionTestReplace by generating a value that holds the RHS of
1869 /// the new loop test.
1870 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
1871 SCEVExpander &Rewriter, ScalarEvolution *SE) {
1872 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
1873 assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
1874 const SCEV *IVInit = AR->getStart();
1876 // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
1877 // finds a valid pointer IV. Sign extend BECount in order to materialize a
1878 // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
1879 // the existing GEPs whenever possible.
1880 if (IndVar->getType()->isPointerTy()
1881 && !IVCount->getType()->isPointerTy()) {
1883 // IVOffset will be the new GEP offset that is interpreted by GEP as a
1884 // signed value. IVCount on the other hand represents the loop trip count,
1885 // which is an unsigned value. FindLoopCounter only allows induction
1886 // variables that have a positive unit stride of one. This means we don't
1887 // have to handle the case of negative offsets (yet) and just need to zero
1889 Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
1890 const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
1892 // Expand the code for the iteration count.
1893 assert(SE->isLoopInvariant(IVOffset, L) &&
1894 "Computed iteration count is not loop invariant!");
1895 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1896 Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
1898 Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
1899 assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
1900 // We could handle pointer IVs other than i8*, but we need to compensate for
1901 // gep index scaling. See canExpandBackedgeTakenCount comments.
1902 assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
1903 cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
1904 && "unit stride pointer IV must be i8*");
1906 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
1907 return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
1910 // In any other case, convert both IVInit and IVCount to integers before
1911 // comparing. This may result in SCEV expension of pointers, but in practice
1912 // SCEV will fold the pointer arithmetic away as such:
1913 // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
1915 // Valid Cases: (1) both integers is most common; (2) both may be pointers
1916 // for simple memset-style loops.
1918 // IVInit integer and IVCount pointer would only occur if a canonical IV
1919 // were generated on top of case #2, which is not expected.
1921 const SCEV *IVLimit = nullptr;
1922 // For unit stride, IVCount = Start + BECount with 2's complement overflow.
1923 // For non-zero Start, compute IVCount here.
1924 if (AR->getStart()->isZero())
1927 assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
1928 const SCEV *IVInit = AR->getStart();
1930 // For integer IVs, truncate the IV before computing IVInit + BECount.
1931 if (SE->getTypeSizeInBits(IVInit->getType())
1932 > SE->getTypeSizeInBits(IVCount->getType()))
1933 IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
1935 IVLimit = SE->getAddExpr(IVInit, IVCount);
1937 // Expand the code for the iteration count.
1938 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1939 IRBuilder<> Builder(BI);
1940 assert(SE->isLoopInvariant(IVLimit, L) &&
1941 "Computed iteration count is not loop invariant!");
1942 // Ensure that we generate the same type as IndVar, or a smaller integer
1943 // type. In the presence of null pointer values, we have an integer type
1944 // SCEV expression (IVInit) for a pointer type IV value (IndVar).
1945 Type *LimitTy = IVCount->getType()->isPointerTy() ?
1946 IndVar->getType() : IVCount->getType();
1947 return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
1951 /// This method rewrites the exit condition of the loop to be a canonical !=
1952 /// comparison against the incremented loop induction variable. This pass is
1953 /// able to rewrite the exit tests of any loop where the SCEV analysis can
1954 /// determine a loop-invariant trip count of the loop, which is actually a much
1955 /// broader range than just linear tests.
1956 Value *IndVarSimplify::
1957 linearFunctionTestReplace(Loop *L,
1958 const SCEV *BackedgeTakenCount,
1960 SCEVExpander &Rewriter) {
1961 assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
1963 // Initialize CmpIndVar and IVCount to their preincremented values.
1964 Value *CmpIndVar = IndVar;
1965 const SCEV *IVCount = BackedgeTakenCount;
1967 // If the exiting block is the same as the backedge block, we prefer to
1968 // compare against the post-incremented value, otherwise we must compare
1969 // against the preincremented value.
1970 if (L->getExitingBlock() == L->getLoopLatch()) {
1971 // Add one to the "backedge-taken" count to get the trip count.
1972 // This addition may overflow, which is valid as long as the comparison is
1973 // truncated to BackedgeTakenCount->getType().
1974 IVCount = SE->getAddExpr(BackedgeTakenCount,
1975 SE->getOne(BackedgeTakenCount->getType()));
1976 // The BackedgeTaken expression contains the number of times that the
1977 // backedge branches to the loop header. This is one less than the
1978 // number of times the loop executes, so use the incremented indvar.
1979 CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
1982 Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
1983 assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
1984 && "genLoopLimit missed a cast");
1986 // Insert a new icmp_ne or icmp_eq instruction before the branch.
1987 BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
1988 ICmpInst::Predicate P;
1989 if (L->contains(BI->getSuccessor(0)))
1990 P = ICmpInst::ICMP_NE;
1992 P = ICmpInst::ICMP_EQ;
1994 DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
1995 << " LHS:" << *CmpIndVar << '\n'
1997 << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
1998 << " RHS:\t" << *ExitCnt << "\n"
1999 << " IVCount:\t" << *IVCount << "\n");
2001 IRBuilder<> Builder(BI);
2003 // LFTR can ignore IV overflow and truncate to the width of
2004 // BECount. This avoids materializing the add(zext(add)) expression.
2005 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
2006 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
2007 if (CmpIndVarSize > ExitCntSize) {
2008 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2009 const SCEV *ARStart = AR->getStart();
2010 const SCEV *ARStep = AR->getStepRecurrence(*SE);
2011 // For constant IVCount, avoid truncation.
2012 if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
2013 const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue();
2014 APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue();
2015 // Note that the post-inc value of BackedgeTakenCount may have overflowed
2016 // above such that IVCount is now zero.
2017 if (IVCount != BackedgeTakenCount && Count == 0) {
2018 Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
2022 Count = Count.zext(CmpIndVarSize);
2024 if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2025 NewLimit = Start - Count;
2027 NewLimit = Start + Count;
2028 ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
2030 DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n");
2032 CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
2036 Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
2037 Value *OrigCond = BI->getCondition();
2038 // It's tempting to use replaceAllUsesWith here to fully replace the old
2039 // comparison, but that's not immediately safe, since users of the old
2040 // comparison may not be dominated by the new comparison. Instead, just
2041 // update the branch to use the new comparison; in the common case this
2042 // will make old comparison dead.
2043 BI->setCondition(Cond);
2044 DeadInsts.push_back(OrigCond);
2051 //===----------------------------------------------------------------------===//
2052 // sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
2053 //===----------------------------------------------------------------------===//
2055 /// If there's a single exit block, sink any loop-invariant values that
2056 /// were defined in the preheader but not used inside the loop into the
2057 /// exit block to reduce register pressure in the loop.
2058 void IndVarSimplify::sinkUnusedInvariants(Loop *L) {
2059 BasicBlock *ExitBlock = L->getExitBlock();
2060 if (!ExitBlock) return;
2062 BasicBlock *Preheader = L->getLoopPreheader();
2063 if (!Preheader) return;
2065 Instruction *InsertPt = &*ExitBlock->getFirstInsertionPt();
2066 BasicBlock::iterator I(Preheader->getTerminator());
2067 while (I != Preheader->begin()) {
2069 // New instructions were inserted at the end of the preheader.
2070 if (isa<PHINode>(I))
2073 // Don't move instructions which might have side effects, since the side
2074 // effects need to complete before instructions inside the loop. Also don't
2075 // move instructions which might read memory, since the loop may modify
2076 // memory. Note that it's okay if the instruction might have undefined
2077 // behavior: LoopSimplify guarantees that the preheader dominates the exit
2079 if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2082 // Skip debug info intrinsics.
2083 if (isa<DbgInfoIntrinsic>(I))
2086 // Skip eh pad instructions.
2090 // Don't sink alloca: we never want to sink static alloca's out of the
2091 // entry block, and correctly sinking dynamic alloca's requires
2092 // checks for stacksave/stackrestore intrinsics.
2093 // FIXME: Refactor this check somehow?
2094 if (isa<AllocaInst>(I))
2097 // Determine if there is a use in or before the loop (direct or
2099 bool UsedInLoop = false;
2100 for (Use &U : I->uses()) {
2101 Instruction *User = cast<Instruction>(U.getUser());
2102 BasicBlock *UseBB = User->getParent();
2103 if (PHINode *P = dyn_cast<PHINode>(User)) {
2105 PHINode::getIncomingValueNumForOperand(U.getOperandNo());
2106 UseBB = P->getIncomingBlock(i);
2108 if (UseBB == Preheader || L->contains(UseBB)) {
2114 // If there is, the def must remain in the preheader.
2118 // Otherwise, sink it to the exit block.
2119 Instruction *ToMove = &*I;
2122 if (I != Preheader->begin()) {
2123 // Skip debug info intrinsics.
2126 } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2128 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2134 ToMove->moveBefore(InsertPt);
2140 //===----------------------------------------------------------------------===//
2141 // IndVarSimplify driver. Manage several subpasses of IV simplification.
2142 //===----------------------------------------------------------------------===//
2144 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
2145 if (skipOptnoneFunction(L))
2148 // If LoopSimplify form is not available, stay out of trouble. Some notes:
2149 // - LSR currently only supports LoopSimplify-form loops. Indvars'
2150 // canonicalization can be a pessimization without LSR to "clean up"
2152 // - We depend on having a preheader; in particular,
2153 // Loop::getCanonicalInductionVariable only supports loops with preheaders,
2154 // and we're in trouble if we can't find the induction variable even when
2155 // we've manually inserted one.
2156 if (!L->isLoopSimplifyForm())
2159 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2160 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2161 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2162 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2163 TLI = TLIP ? &TLIP->getTLI() : nullptr;
2164 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2165 TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
2166 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2171 // If there are any floating-point recurrences, attempt to
2172 // transform them to use integer recurrences.
2173 rewriteNonIntegerIVs(L);
2175 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2177 // Create a rewriter object which we'll use to transform the code with.
2178 SCEVExpander Rewriter(*SE, DL, "indvars");
2180 Rewriter.setDebugType(DEBUG_TYPE);
2183 // Eliminate redundant IV users.
2185 // Simplification works best when run before other consumers of SCEV. We
2186 // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2187 // other expressions involving loop IVs have been evaluated. This helps SCEV
2188 // set no-wrap flags before normalizing sign/zero extension.
2189 Rewriter.disableCanonicalMode();
2190 simplifyAndExtend(L, Rewriter, LPM);
2192 // Check to see if this loop has a computable loop-invariant execution count.
2193 // If so, this means that we can compute the final value of any expressions
2194 // that are recurrent in the loop, and substitute the exit values from the
2195 // loop into any instructions outside of the loop that use the final values of
2196 // the current expressions.
2198 if (ReplaceExitValue != NeverRepl &&
2199 !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2200 rewriteLoopExitValues(L, Rewriter);
2202 // Eliminate redundant IV cycles.
2203 NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
2205 // If we have a trip count expression, rewrite the loop's exit condition
2206 // using it. We can currently only handle loops with a single exit.
2207 if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) {
2208 PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
2210 // Check preconditions for proper SCEVExpander operation. SCEV does not
2211 // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2212 // pass that uses the SCEVExpander must do it. This does not work well for
2213 // loop passes because SCEVExpander makes assumptions about all loops,
2214 // while LoopPassManager only forces the current loop to be simplified.
2216 // FIXME: SCEV expansion has no way to bail out, so the caller must
2217 // explicitly check any assumptions made by SCEV. Brittle.
2218 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2219 if (!AR || AR->getLoop()->getLoopPreheader())
2220 (void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2224 // Clear the rewriter cache, because values that are in the rewriter's cache
2225 // can be deleted in the loop below, causing the AssertingVH in the cache to
2229 // Now that we're done iterating through lists, clean up any instructions
2230 // which are now dead.
2231 while (!DeadInsts.empty())
2232 if (Instruction *Inst =
2233 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2234 RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
2236 // The Rewriter may not be used from this point on.
2238 // Loop-invariant instructions in the preheader that aren't used in the
2239 // loop may be sunk below the loop to reduce register pressure.
2240 sinkUnusedInvariants(L);
2242 // rewriteFirstIterationLoopExitValues does not rely on the computation of
2243 // trip count and therefore can further simplify exit values in addition to
2244 // rewriteLoopExitValues.
2245 rewriteFirstIterationLoopExitValues(L);
2247 // Clean up dead instructions.
2248 Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
2249 // Check a post-condition.
2250 assert(L->isLCSSAForm(*DT) &&
2251 "Indvars did not leave the loop in lcssa form!");
2253 // Verify that LFTR, and any other change have not interfered with SCEV's
2254 // ability to compute trip count.
2256 if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2258 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2259 if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2260 SE->getTypeSizeInBits(NewBECount->getType()))
2261 NewBECount = SE->getTruncateOrNoop(NewBECount,
2262 BackedgeTakenCount->getType());
2264 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2265 NewBECount->getType());
2266 assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");