Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp
35269 views
//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This transformation analyzes and transforms the induction variables (and9// computations derived from them) into simpler forms suitable for subsequent10// analysis and transformation.11//12// If the trip count of a loop is computable, this pass also makes the following13// changes:14// 1. The exit condition for the loop is canonicalized to compare the15// induction value against the exit value. This turns loops like:16// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'17// 2. Any use outside of the loop of an expression derived from the indvar18// is changed to compute the derived value outside of the loop, eliminating19// the dependence on the exit value of the induction variable. If the only20// purpose of the loop is to compute the exit value of some derived21// expression, this transformation will make the loop dead.22//23//===----------------------------------------------------------------------===//2425#include "llvm/Transforms/Scalar/IndVarSimplify.h"26#include "llvm/ADT/APFloat.h"27#include "llvm/ADT/ArrayRef.h"28#include "llvm/ADT/STLExtras.h"29#include "llvm/ADT/SmallPtrSet.h"30#include "llvm/ADT/SmallSet.h"31#include "llvm/ADT/SmallVector.h"32#include "llvm/ADT/Statistic.h"33#include "llvm/ADT/iterator_range.h"34#include "llvm/Analysis/LoopInfo.h"35#include "llvm/Analysis/LoopPass.h"36#include "llvm/Analysis/MemorySSA.h"37#include "llvm/Analysis/MemorySSAUpdater.h"38#include "llvm/Analysis/ScalarEvolution.h"39#include "llvm/Analysis/ScalarEvolutionExpressions.h"40#include "llvm/Analysis/TargetLibraryInfo.h"41#include "llvm/Analysis/TargetTransformInfo.h"42#include "llvm/Analysis/ValueTracking.h"43#include "llvm/IR/BasicBlock.h"44#include "llvm/IR/Constant.h"45#include "llvm/IR/ConstantRange.h"46#include "llvm/IR/Constants.h"47#include "llvm/IR/DataLayout.h"48#include "llvm/IR/DerivedTypes.h"49#include "llvm/IR/Dominators.h"50#include "llvm/IR/Function.h"51#include "llvm/IR/IRBuilder.h"52#include "llvm/IR/InstrTypes.h"53#include "llvm/IR/Instruction.h"54#include "llvm/IR/Instructions.h"55#include "llvm/IR/IntrinsicInst.h"56#include "llvm/IR/Intrinsics.h"57#include "llvm/IR/Module.h"58#include "llvm/IR/Operator.h"59#include "llvm/IR/PassManager.h"60#include "llvm/IR/PatternMatch.h"61#include "llvm/IR/Type.h"62#include "llvm/IR/Use.h"63#include "llvm/IR/User.h"64#include "llvm/IR/Value.h"65#include "llvm/IR/ValueHandle.h"66#include "llvm/Support/Casting.h"67#include "llvm/Support/CommandLine.h"68#include "llvm/Support/Compiler.h"69#include "llvm/Support/Debug.h"70#include "llvm/Support/MathExtras.h"71#include "llvm/Support/raw_ostream.h"72#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"73#include "llvm/Transforms/Utils/BasicBlockUtils.h"74#include "llvm/Transforms/Utils/Local.h"75#include "llvm/Transforms/Utils/LoopUtils.h"76#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"77#include "llvm/Transforms/Utils/SimplifyIndVar.h"78#include <cassert>79#include <cstdint>80#include <utility>8182using namespace llvm;83using namespace PatternMatch;8485#define DEBUG_TYPE "indvars"8687STATISTIC(NumWidened , "Number of indvars widened");88STATISTIC(NumReplaced , "Number of exit values replaced");89STATISTIC(NumLFTR , "Number of loop exit tests replaced");90STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");91STATISTIC(NumElimIV , "Number of congruent IVs eliminated");9293static cl::opt<ReplaceExitVal> ReplaceExitValue(94"replexitval", cl::Hidden, cl::init(OnlyCheapRepl),95cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),96cl::values(97clEnumValN(NeverRepl, "never", "never replace exit value"),98clEnumValN(OnlyCheapRepl, "cheap",99"only replace exit value when the cost is cheap"),100clEnumValN(101UnusedIndVarInLoop, "unusedindvarinloop",102"only replace exit value when it is an unused "103"induction variable in the loop and has cheap replacement cost"),104clEnumValN(NoHardUse, "noharduse",105"only replace exit values when loop def likely dead"),106clEnumValN(AlwaysRepl, "always",107"always replace exit value whenever possible")));108109static cl::opt<bool> UsePostIncrementRanges(110"indvars-post-increment-ranges", cl::Hidden,111cl::desc("Use post increment control-dependent ranges in IndVarSimplify"),112cl::init(true));113114static cl::opt<bool>115DisableLFTR("disable-lftr", cl::Hidden, cl::init(false),116cl::desc("Disable Linear Function Test Replace optimization"));117118static cl::opt<bool>119LoopPredication("indvars-predicate-loops", cl::Hidden, cl::init(true),120cl::desc("Predicate conditions in read only loops"));121122static cl::opt<bool>123AllowIVWidening("indvars-widen-indvars", cl::Hidden, cl::init(true),124cl::desc("Allow widening of indvars to eliminate s/zext"));125126namespace {127128class IndVarSimplify {129LoopInfo *LI;130ScalarEvolution *SE;131DominatorTree *DT;132const DataLayout &DL;133TargetLibraryInfo *TLI;134const TargetTransformInfo *TTI;135std::unique_ptr<MemorySSAUpdater> MSSAU;136137SmallVector<WeakTrackingVH, 16> DeadInsts;138bool WidenIndVars;139140bool RunUnswitching = false;141142bool handleFloatingPointIV(Loop *L, PHINode *PH);143bool rewriteNonIntegerIVs(Loop *L);144145bool simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);146/// Try to improve our exit conditions by converting condition from signed147/// to unsigned or rotating computation out of the loop.148/// (See inline comment about why this is duplicated from simplifyAndExtend)149bool canonicalizeExitCondition(Loop *L);150/// Try to eliminate loop exits based on analyzeable exit counts151bool optimizeLoopExits(Loop *L, SCEVExpander &Rewriter);152/// Try to form loop invariant tests for loop exits by changing how many153/// iterations of the loop run when that is unobservable.154bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);155156bool rewriteFirstIterationLoopExitValues(Loop *L);157158bool linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,159const SCEV *ExitCount,160PHINode *IndVar, SCEVExpander &Rewriter);161162bool sinkUnusedInvariants(Loop *L);163164public:165IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,166const DataLayout &DL, TargetLibraryInfo *TLI,167TargetTransformInfo *TTI, MemorySSA *MSSA, bool WidenIndVars)168: LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI),169WidenIndVars(WidenIndVars) {170if (MSSA)171MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);172}173174bool run(Loop *L);175176bool runUnswitching() const { return RunUnswitching; }177};178179} // end anonymous namespace180181//===----------------------------------------------------------------------===//182// rewriteNonIntegerIVs and helpers. Prefer integer IVs.183//===----------------------------------------------------------------------===//184185/// Convert APF to an integer, if possible.186static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {187bool isExact = false;188// See if we can convert this to an int64_t189uint64_t UIntVal;190if (APF.convertToInteger(MutableArrayRef(UIntVal), 64, true,191APFloat::rmTowardZero, &isExact) != APFloat::opOK ||192!isExact)193return false;194IntVal = UIntVal;195return true;196}197198/// If the loop has floating induction variable then insert corresponding199/// integer induction variable if possible.200/// For example,201/// for(double i = 0; i < 10000; ++i)202/// bar(i)203/// is converted into204/// for(int i = 0; i < 10000; ++i)205/// bar((double)i);206bool IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {207unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));208unsigned BackEdge = IncomingEdge^1;209210// Check incoming value.211auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));212213int64_t InitValue;214if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))215return false;216217// Check IV increment. Reject this PN if increment operation is not218// an add or increment value can not be represented by an integer.219auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));220if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return false;221222// If this is not an add of the PHI with a constantfp, or if the constant fp223// is not an integer, bail out.224ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));225int64_t IncValue;226if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||227!ConvertToSInt(IncValueVal->getValueAPF(), IncValue))228return false;229230// Check Incr uses. One user is PN and the other user is an exit condition231// used by the conditional terminator.232Value::user_iterator IncrUse = Incr->user_begin();233Instruction *U1 = cast<Instruction>(*IncrUse++);234if (IncrUse == Incr->user_end()) return false;235Instruction *U2 = cast<Instruction>(*IncrUse++);236if (IncrUse != Incr->user_end()) return false;237238// Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't239// only used by a branch, we can't transform it.240FCmpInst *Compare = dyn_cast<FCmpInst>(U1);241if (!Compare)242Compare = dyn_cast<FCmpInst>(U2);243if (!Compare || !Compare->hasOneUse() ||244!isa<BranchInst>(Compare->user_back()))245return false;246247BranchInst *TheBr = cast<BranchInst>(Compare->user_back());248249// We need to verify that the branch actually controls the iteration count250// of the loop. If not, the new IV can overflow and no one will notice.251// The branch block must be in the loop and one of the successors must be out252// of the loop.253assert(TheBr->isConditional() && "Can't use fcmp if not conditional");254if (!L->contains(TheBr->getParent()) ||255(L->contains(TheBr->getSuccessor(0)) &&256L->contains(TheBr->getSuccessor(1))))257return false;258259// If it isn't a comparison with an integer-as-fp (the exit value), we can't260// transform it.261ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));262int64_t ExitValue;263if (ExitValueVal == nullptr ||264!ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))265return false;266267// Find new predicate for integer comparison.268CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;269switch (Compare->getPredicate()) {270default: return false; // Unknown comparison.271case CmpInst::FCMP_OEQ:272case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;273case CmpInst::FCMP_ONE:274case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;275case CmpInst::FCMP_OGT:276case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;277case CmpInst::FCMP_OGE:278case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;279case CmpInst::FCMP_OLT:280case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;281case CmpInst::FCMP_OLE:282case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;283}284285// We convert the floating point induction variable to a signed i32 value if286// we can. This is only safe if the comparison will not overflow in a way287// that won't be trapped by the integer equivalent operations. Check for this288// now.289// TODO: We could use i64 if it is native and the range requires it.290291// The start/stride/exit values must all fit in signed i32.292if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))293return false;294295// If not actually striding (add x, 0.0), avoid touching the code.296if (IncValue == 0)297return false;298299// Positive and negative strides have different safety conditions.300if (IncValue > 0) {301// If we have a positive stride, we require the init to be less than the302// exit value.303if (InitValue >= ExitValue)304return false;305306uint32_t Range = uint32_t(ExitValue-InitValue);307// Check for infinite loop, either:308// while (i <= Exit) or until (i > Exit)309if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {310if (++Range == 0) return false; // Range overflows.311}312313unsigned Leftover = Range % uint32_t(IncValue);314315// If this is an equality comparison, we require that the strided value316// exactly land on the exit value, otherwise the IV condition will wrap317// around and do things the fp IV wouldn't.318if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&319Leftover != 0)320return false;321322// If the stride would wrap around the i32 before exiting, we can't323// transform the IV.324if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)325return false;326} else {327// If we have a negative stride, we require the init to be greater than the328// exit value.329if (InitValue <= ExitValue)330return false;331332uint32_t Range = uint32_t(InitValue-ExitValue);333// Check for infinite loop, either:334// while (i >= Exit) or until (i < Exit)335if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {336if (++Range == 0) return false; // Range overflows.337}338339unsigned Leftover = Range % uint32_t(-IncValue);340341// If this is an equality comparison, we require that the strided value342// exactly land on the exit value, otherwise the IV condition will wrap343// around and do things the fp IV wouldn't.344if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&345Leftover != 0)346return false;347348// If the stride would wrap around the i32 before exiting, we can't349// transform the IV.350if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)351return false;352}353354IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());355356// Insert new integer induction variable.357PHINode *NewPHI =358PHINode::Create(Int32Ty, 2, PN->getName() + ".int", PN->getIterator());359NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),360PN->getIncomingBlock(IncomingEdge));361NewPHI->setDebugLoc(PN->getDebugLoc());362363Instruction *NewAdd =364BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),365Incr->getName() + ".int", Incr->getIterator());366NewAdd->setDebugLoc(Incr->getDebugLoc());367NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));368369ICmpInst *NewCompare =370new ICmpInst(TheBr->getIterator(), NewPred, NewAdd,371ConstantInt::get(Int32Ty, ExitValue), Compare->getName());372NewCompare->setDebugLoc(Compare->getDebugLoc());373374// In the following deletions, PN may become dead and may be deleted.375// Use a WeakTrackingVH to observe whether this happens.376WeakTrackingVH WeakPH = PN;377378// Delete the old floating point exit comparison. The branch starts using the379// new comparison.380NewCompare->takeName(Compare);381Compare->replaceAllUsesWith(NewCompare);382RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI, MSSAU.get());383384// Delete the old floating point increment.385Incr->replaceAllUsesWith(PoisonValue::get(Incr->getType()));386RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI, MSSAU.get());387388// If the FP induction variable still has uses, this is because something else389// in the loop uses its value. In order to canonicalize the induction390// variable, we chose to eliminate the IV and rewrite it in terms of an391// int->fp cast.392//393// We give preference to sitofp over uitofp because it is faster on most394// platforms.395if (WeakPH) {396Instruction *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",397PN->getParent()->getFirstInsertionPt());398Conv->setDebugLoc(PN->getDebugLoc());399PN->replaceAllUsesWith(Conv);400RecursivelyDeleteTriviallyDeadInstructions(PN, TLI, MSSAU.get());401}402return true;403}404405bool IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {406// First step. Check to see if there are any floating-point recurrences.407// If there are, change them into integer recurrences, permitting analysis by408// the SCEV routines.409BasicBlock *Header = L->getHeader();410411SmallVector<WeakTrackingVH, 8> PHIs;412for (PHINode &PN : Header->phis())413PHIs.push_back(&PN);414415bool Changed = false;416for (WeakTrackingVH &PHI : PHIs)417if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHI))418Changed |= handleFloatingPointIV(L, PN);419420// If the loop previously had floating-point IV, ScalarEvolution421// may not have been able to compute a trip count. Now that we've done some422// re-writing, the trip count may be computable.423if (Changed)424SE->forgetLoop(L);425return Changed;426}427428//===---------------------------------------------------------------------===//429// rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know430// they will exit at the first iteration.431//===---------------------------------------------------------------------===//432433/// Check to see if this loop has loop invariant conditions which lead to loop434/// exits. If so, we know that if the exit path is taken, it is at the first435/// loop iteration. This lets us predict exit values of PHI nodes that live in436/// loop header.437bool IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {438// Verify the input to the pass is already in LCSSA form.439assert(L->isLCSSAForm(*DT));440441SmallVector<BasicBlock *, 8> ExitBlocks;442L->getUniqueExitBlocks(ExitBlocks);443444bool MadeAnyChanges = false;445for (auto *ExitBB : ExitBlocks) {446// If there are no more PHI nodes in this exit block, then no more447// values defined inside the loop are used on this path.448for (PHINode &PN : ExitBB->phis()) {449for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();450IncomingValIdx != E; ++IncomingValIdx) {451auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);452453// Can we prove that the exit must run on the first iteration if it454// runs at all? (i.e. early exits are fine for our purposes, but455// traces which lead to this exit being taken on the 2nd iteration456// aren't.) Note that this is about whether the exit branch is457// executed, not about whether it is taken.458if (!L->getLoopLatch() ||459!DT->dominates(IncomingBB, L->getLoopLatch()))460continue;461462// Get condition that leads to the exit path.463auto *TermInst = IncomingBB->getTerminator();464465Value *Cond = nullptr;466if (auto *BI = dyn_cast<BranchInst>(TermInst)) {467// Must be a conditional branch, otherwise the block468// should not be in the loop.469Cond = BI->getCondition();470} else if (auto *SI = dyn_cast<SwitchInst>(TermInst))471Cond = SI->getCondition();472else473continue;474475if (!L->isLoopInvariant(Cond))476continue;477478auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));479480// Only deal with PHIs in the loop header.481if (!ExitVal || ExitVal->getParent() != L->getHeader())482continue;483484// If ExitVal is a PHI on the loop header, then we know its485// value along this exit because the exit can only be taken486// on the first iteration.487auto *LoopPreheader = L->getLoopPreheader();488assert(LoopPreheader && "Invalid loop");489int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);490if (PreheaderIdx != -1) {491assert(ExitVal->getParent() == L->getHeader() &&492"ExitVal must be in loop header");493MadeAnyChanges = true;494PN.setIncomingValue(IncomingValIdx,495ExitVal->getIncomingValue(PreheaderIdx));496SE->forgetValue(&PN);497}498}499}500}501return MadeAnyChanges;502}503504//===----------------------------------------------------------------------===//505// IV Widening - Extend the width of an IV to cover its widest uses.506//===----------------------------------------------------------------------===//507508/// Update information about the induction variable that is extended by this509/// sign or zero extend operation. This is used to determine the final width of510/// the IV before actually widening it.511static void visitIVCast(CastInst *Cast, WideIVInfo &WI,512ScalarEvolution *SE,513const TargetTransformInfo *TTI) {514bool IsSigned = Cast->getOpcode() == Instruction::SExt;515if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)516return;517518Type *Ty = Cast->getType();519uint64_t Width = SE->getTypeSizeInBits(Ty);520if (!Cast->getDataLayout().isLegalInteger(Width))521return;522523// Check that `Cast` actually extends the induction variable (we rely on this524// later). This takes care of cases where `Cast` is extending a truncation of525// the narrow induction variable, and thus can end up being narrower than the526// "narrow" induction variable.527uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());528if (NarrowIVWidth >= Width)529return;530531// Cast is either an sext or zext up to this point.532// We should not widen an indvar if arithmetics on the wider indvar are more533// expensive than those on the narrower indvar. We check only the cost of ADD534// because at least an ADD is required to increment the induction variable. We535// could compute more comprehensively the cost of all instructions on the536// induction variable when necessary.537if (TTI &&538TTI->getArithmeticInstrCost(Instruction::Add, Ty) >539TTI->getArithmeticInstrCost(Instruction::Add,540Cast->getOperand(0)->getType())) {541return;542}543544if (!WI.WidestNativeType ||545Width > SE->getTypeSizeInBits(WI.WidestNativeType)) {546WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);547WI.IsSigned = IsSigned;548return;549}550551// We extend the IV to satisfy the sign of its user(s), or 'signed'552// if there are multiple users with both sign- and zero extensions,553// in order not to introduce nondeterministic behaviour based on the554// unspecified order of a PHI nodes' users-iterator.555WI.IsSigned |= IsSigned;556}557558//===----------------------------------------------------------------------===//559// Live IV Reduction - Minimize IVs live across the loop.560//===----------------------------------------------------------------------===//561562//===----------------------------------------------------------------------===//563// Simplification of IV users based on SCEV evaluation.564//===----------------------------------------------------------------------===//565566namespace {567568class IndVarSimplifyVisitor : public IVVisitor {569ScalarEvolution *SE;570const TargetTransformInfo *TTI;571PHINode *IVPhi;572573public:574WideIVInfo WI;575576IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,577const TargetTransformInfo *TTI,578const DominatorTree *DTree)579: SE(SCEV), TTI(TTI), IVPhi(IV) {580DT = DTree;581WI.NarrowIV = IVPhi;582}583584// Implement the interface used by simplifyUsersOfIV.585void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }586};587588} // end anonymous namespace589590/// Iteratively perform simplification on a worklist of IV users. Each591/// successive simplification may push more users which may themselves be592/// candidates for simplification.593///594/// Sign/Zero extend elimination is interleaved with IV simplification.595bool IndVarSimplify::simplifyAndExtend(Loop *L,596SCEVExpander &Rewriter,597LoopInfo *LI) {598SmallVector<WideIVInfo, 8> WideIVs;599600auto *GuardDecl = L->getBlocks()[0]->getModule()->getFunction(601Intrinsic::getName(Intrinsic::experimental_guard));602bool HasGuards = GuardDecl && !GuardDecl->use_empty();603604SmallVector<PHINode *, 8> LoopPhis;605for (PHINode &PN : L->getHeader()->phis())606LoopPhis.push_back(&PN);607608// Each round of simplification iterates through the SimplifyIVUsers worklist609// for all current phis, then determines whether any IVs can be610// widened. Widening adds new phis to LoopPhis, inducing another round of611// simplification on the wide IVs.612bool Changed = false;613while (!LoopPhis.empty()) {614// Evaluate as many IV expressions as possible before widening any IVs. This615// forces SCEV to set no-wrap flags before evaluating sign/zero616// extension. The first time SCEV attempts to normalize sign/zero extension,617// the result becomes final. So for the most predictable results, we delay618// evaluation of sign/zero extend evaluation until needed, and avoid running619// other SCEV based analysis prior to simplifyAndExtend.620do {621PHINode *CurrIV = LoopPhis.pop_back_val();622623// Information about sign/zero extensions of CurrIV.624IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);625626const auto &[C, U] = simplifyUsersOfIV(CurrIV, SE, DT, LI, TTI, DeadInsts,627Rewriter, &Visitor);628629Changed |= C;630RunUnswitching |= U;631if (Visitor.WI.WidestNativeType) {632WideIVs.push_back(Visitor.WI);633}634} while(!LoopPhis.empty());635636// Continue if we disallowed widening.637if (!WidenIndVars)638continue;639640for (; !WideIVs.empty(); WideIVs.pop_back()) {641unsigned ElimExt;642unsigned Widened;643if (PHINode *WidePhi = createWideIV(WideIVs.back(), LI, SE, Rewriter,644DT, DeadInsts, ElimExt, Widened,645HasGuards, UsePostIncrementRanges)) {646NumElimExt += ElimExt;647NumWidened += Widened;648Changed = true;649LoopPhis.push_back(WidePhi);650}651}652}653return Changed;654}655656//===----------------------------------------------------------------------===//657// linearFunctionTestReplace and its kin. Rewrite the loop exit condition.658//===----------------------------------------------------------------------===//659660/// Given an Value which is hoped to be part of an add recurance in the given661/// loop, return the associated Phi node if so. Otherwise, return null. Note662/// that this is less general than SCEVs AddRec checking.663static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L) {664Instruction *IncI = dyn_cast<Instruction>(IncV);665if (!IncI)666return nullptr;667668switch (IncI->getOpcode()) {669case Instruction::Add:670case Instruction::Sub:671break;672case Instruction::GetElementPtr:673// An IV counter must preserve its type.674if (IncI->getNumOperands() == 2)675break;676[[fallthrough]];677default:678return nullptr;679}680681PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));682if (Phi && Phi->getParent() == L->getHeader()) {683if (L->isLoopInvariant(IncI->getOperand(1)))684return Phi;685return nullptr;686}687if (IncI->getOpcode() == Instruction::GetElementPtr)688return nullptr;689690// Allow add/sub to be commuted.691Phi = dyn_cast<PHINode>(IncI->getOperand(1));692if (Phi && Phi->getParent() == L->getHeader()) {693if (L->isLoopInvariant(IncI->getOperand(0)))694return Phi;695}696return nullptr;697}698699/// Whether the current loop exit test is based on this value. Currently this700/// is limited to a direct use in the loop condition.701static bool isLoopExitTestBasedOn(Value *V, BasicBlock *ExitingBB) {702BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());703ICmpInst *ICmp = dyn_cast<ICmpInst>(BI->getCondition());704// TODO: Allow non-icmp loop test.705if (!ICmp)706return false;707708// TODO: Allow indirect use.709return ICmp->getOperand(0) == V || ICmp->getOperand(1) == V;710}711712/// linearFunctionTestReplace policy. Return true unless we can show that the713/// current exit test is already sufficiently canonical.714static bool needsLFTR(Loop *L, BasicBlock *ExitingBB) {715assert(L->getLoopLatch() && "Must be in simplified form");716717// Avoid converting a constant or loop invariant test back to a runtime718// test. This is critical for when SCEV's cached ExitCount is less precise719// than the current IR (such as after we've proven a particular exit is720// actually dead and thus the BE count never reaches our ExitCount.)721BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());722if (L->isLoopInvariant(BI->getCondition()))723return false;724725// Do LFTR to simplify the exit condition to an ICMP.726ICmpInst *Cond = dyn_cast<ICmpInst>(BI->getCondition());727if (!Cond)728return true;729730// Do LFTR to simplify the exit ICMP to EQ/NE731ICmpInst::Predicate Pred = Cond->getPredicate();732if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)733return true;734735// Look for a loop invariant RHS736Value *LHS = Cond->getOperand(0);737Value *RHS = Cond->getOperand(1);738if (!L->isLoopInvariant(RHS)) {739if (!L->isLoopInvariant(LHS))740return true;741std::swap(LHS, RHS);742}743// Look for a simple IV counter LHS744PHINode *Phi = dyn_cast<PHINode>(LHS);745if (!Phi)746Phi = getLoopPhiForCounter(LHS, L);747748if (!Phi)749return true;750751// Do LFTR if PHI node is defined in the loop, but is *not* a counter.752int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());753if (Idx < 0)754return true;755756// Do LFTR if the exit condition's IV is *not* a simple counter.757Value *IncV = Phi->getIncomingValue(Idx);758return Phi != getLoopPhiForCounter(IncV, L);759}760761/// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils762/// down to checking that all operands are constant and listing instructions763/// that may hide undef.764static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,765unsigned Depth) {766if (isa<Constant>(V))767return !isa<UndefValue>(V);768769if (Depth >= 6)770return false;771772// Conservatively handle non-constant non-instructions. For example, Arguments773// may be undef.774Instruction *I = dyn_cast<Instruction>(V);775if (!I)776return false;777778// Load and return values may be undef.779if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))780return false;781782// Optimistically handle other instructions.783for (Value *Op : I->operands()) {784if (!Visited.insert(Op).second)785continue;786if (!hasConcreteDefImpl(Op, Visited, Depth+1))787return false;788}789return true;790}791792/// Return true if the given value is concrete. We must prove that undef can793/// never reach it.794///795/// TODO: If we decide that this is a good approach to checking for undef, we796/// may factor it into a common location.797static bool hasConcreteDef(Value *V) {798SmallPtrSet<Value*, 8> Visited;799Visited.insert(V);800return hasConcreteDefImpl(V, Visited, 0);801}802803/// Return true if the given phi is a "counter" in L. A counter is an804/// add recurance (of integer or pointer type) with an arbitrary start, and a805/// step of 1. Note that L must have exactly one latch.806static bool isLoopCounter(PHINode* Phi, Loop *L,807ScalarEvolution *SE) {808assert(Phi->getParent() == L->getHeader());809assert(L->getLoopLatch());810811if (!SE->isSCEVable(Phi->getType()))812return false;813814const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));815if (!AR || AR->getLoop() != L || !AR->isAffine())816return false;817818const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));819if (!Step || !Step->isOne())820return false;821822int LatchIdx = Phi->getBasicBlockIndex(L->getLoopLatch());823Value *IncV = Phi->getIncomingValue(LatchIdx);824return (getLoopPhiForCounter(IncV, L) == Phi &&825isa<SCEVAddRecExpr>(SE->getSCEV(IncV)));826}827828/// Search the loop header for a loop counter (anadd rec w/step of one)829/// suitable for use by LFTR. If multiple counters are available, select the830/// "best" one based profitable heuristics.831///832/// BECount may be an i8* pointer type. The pointer difference is already833/// valid count without scaling the address stride, so it remains a pointer834/// expression as far as SCEV is concerned.835static PHINode *FindLoopCounter(Loop *L, BasicBlock *ExitingBB,836const SCEV *BECount,837ScalarEvolution *SE, DominatorTree *DT) {838uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());839840Value *Cond = cast<BranchInst>(ExitingBB->getTerminator())->getCondition();841842// Loop over all of the PHI nodes, looking for a simple counter.843PHINode *BestPhi = nullptr;844const SCEV *BestInit = nullptr;845BasicBlock *LatchBlock = L->getLoopLatch();846assert(LatchBlock && "Must be in simplified form");847const DataLayout &DL = L->getHeader()->getDataLayout();848849for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {850PHINode *Phi = cast<PHINode>(I);851if (!isLoopCounter(Phi, L, SE))852continue;853854const auto *AR = cast<SCEVAddRecExpr>(SE->getSCEV(Phi));855856// AR may be a pointer type, while BECount is an integer type.857// AR may be wider than BECount. With eq/ne tests overflow is immaterial.858// AR may not be a narrower type, or we may never exit.859uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());860if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))861continue;862863// Avoid reusing a potentially undef value to compute other values that may864// have originally had a concrete definition.865if (!hasConcreteDef(Phi)) {866// We explicitly allow unknown phis as long as they are already used by867// the loop exit test. This is legal since performing LFTR could not868// increase the number of undef users.869Value *IncPhi = Phi->getIncomingValueForBlock(LatchBlock);870if (!isLoopExitTestBasedOn(Phi, ExitingBB) &&871!isLoopExitTestBasedOn(IncPhi, ExitingBB))872continue;873}874875// Avoid introducing undefined behavior due to poison which didn't exist in876// the original program. (Annoyingly, the rules for poison and undef877// propagation are distinct, so this does NOT cover the undef case above.)878// We have to ensure that we don't introduce UB by introducing a use on an879// iteration where said IV produces poison. Our strategy here differs for880// pointers and integer IVs. For integers, we strip and reinfer as needed,881// see code in linearFunctionTestReplace. For pointers, we restrict882// transforms as there is no good way to reinfer inbounds once lost.883if (!Phi->getType()->isIntegerTy() &&884!mustExecuteUBIfPoisonOnPathTo(Phi, ExitingBB->getTerminator(), DT))885continue;886887const SCEV *Init = AR->getStart();888889if (BestPhi && !isAlmostDeadIV(BestPhi, LatchBlock, Cond)) {890// Don't force a live loop counter if another IV can be used.891if (isAlmostDeadIV(Phi, LatchBlock, Cond))892continue;893894// Prefer to count-from-zero. This is a more "canonical" counter form. It895// also prefers integer to pointer IVs.896if (BestInit->isZero() != Init->isZero()) {897if (BestInit->isZero())898continue;899}900// If two IVs both count from zero or both count from nonzero then the901// narrower is likely a dead phi that has been widened. Use the wider phi902// to allow the other to be eliminated.903else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))904continue;905}906BestPhi = Phi;907BestInit = Init;908}909return BestPhi;910}911912/// Insert an IR expression which computes the value held by the IV IndVar913/// (which must be an loop counter w/unit stride) after the backedge of loop L914/// is taken ExitCount times.915static Value *genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB,916const SCEV *ExitCount, bool UsePostInc, Loop *L,917SCEVExpander &Rewriter, ScalarEvolution *SE) {918assert(isLoopCounter(IndVar, L, SE));919assert(ExitCount->getType()->isIntegerTy() && "exit count must be integer");920const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));921assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");922923// For integer IVs, truncate the IV before computing the limit unless we924// know apriori that the limit must be a constant when evaluated in the925// bitwidth of the IV. We prefer (potentially) keeping a truncate of the926// IV in the loop over a (potentially) expensive expansion of the widened927// exit count add(zext(add)) expression.928if (IndVar->getType()->isIntegerTy() &&929SE->getTypeSizeInBits(AR->getType()) >930SE->getTypeSizeInBits(ExitCount->getType())) {931const SCEV *IVInit = AR->getStart();932if (!isa<SCEVConstant>(IVInit) || !isa<SCEVConstant>(ExitCount))933AR = cast<SCEVAddRecExpr>(SE->getTruncateExpr(AR, ExitCount->getType()));934}935936const SCEVAddRecExpr *ARBase = UsePostInc ? AR->getPostIncExpr(*SE) : AR;937const SCEV *IVLimit = ARBase->evaluateAtIteration(ExitCount, *SE);938assert(SE->isLoopInvariant(IVLimit, L) &&939"Computed iteration count is not loop invariant!");940return Rewriter.expandCodeFor(IVLimit, ARBase->getType(),941ExitingBB->getTerminator());942}943944/// This method rewrites the exit condition of the loop to be a canonical !=945/// comparison against the incremented loop induction variable. This pass is946/// able to rewrite the exit tests of any loop where the SCEV analysis can947/// determine a loop-invariant trip count of the loop, which is actually a much948/// broader range than just linear tests.949bool IndVarSimplify::950linearFunctionTestReplace(Loop *L, BasicBlock *ExitingBB,951const SCEV *ExitCount,952PHINode *IndVar, SCEVExpander &Rewriter) {953assert(L->getLoopLatch() && "Loop no longer in simplified form?");954assert(isLoopCounter(IndVar, L, SE));955Instruction * const IncVar =956cast<Instruction>(IndVar->getIncomingValueForBlock(L->getLoopLatch()));957958// Initialize CmpIndVar to the preincremented IV.959Value *CmpIndVar = IndVar;960bool UsePostInc = false;961962// If the exiting block is the same as the backedge block, we prefer to963// compare against the post-incremented value, otherwise we must compare964// against the preincremented value.965if (ExitingBB == L->getLoopLatch()) {966// For pointer IVs, we chose to not strip inbounds which requires us not967// to add a potentially UB introducing use. We need to either a) show968// the loop test we're modifying is already in post-inc form, or b) show969// that adding a use must not introduce UB.970bool SafeToPostInc =971IndVar->getType()->isIntegerTy() ||972isLoopExitTestBasedOn(IncVar, ExitingBB) ||973mustExecuteUBIfPoisonOnPathTo(IncVar, ExitingBB->getTerminator(), DT);974if (SafeToPostInc) {975UsePostInc = true;976CmpIndVar = IncVar;977}978}979980// It may be necessary to drop nowrap flags on the incrementing instruction981// if either LFTR moves from a pre-inc check to a post-inc check (in which982// case the increment might have previously been poison on the last iteration983// only) or if LFTR switches to a different IV that was previously dynamically984// dead (and as such may be arbitrarily poison). We remove any nowrap flags985// that SCEV didn't infer for the post-inc addrec (even if we use a pre-inc986// check), because the pre-inc addrec flags may be adopted from the original987// instruction, while SCEV has to explicitly prove the post-inc nowrap flags.988// TODO: This handling is inaccurate for one case: If we switch to a989// dynamically dead IV that wraps on the first loop iteration only, which is990// not covered by the post-inc addrec. (If the new IV was not dynamically991// dead, it could not be poison on the first iteration in the first place.)992if (auto *BO = dyn_cast<BinaryOperator>(IncVar)) {993const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IncVar));994if (BO->hasNoUnsignedWrap())995BO->setHasNoUnsignedWrap(AR->hasNoUnsignedWrap());996if (BO->hasNoSignedWrap())997BO->setHasNoSignedWrap(AR->hasNoSignedWrap());998}9991000Value *ExitCnt = genLoopLimit(1001IndVar, ExitingBB, ExitCount, UsePostInc, L, Rewriter, SE);1002assert(ExitCnt->getType()->isPointerTy() ==1003IndVar->getType()->isPointerTy() &&1004"genLoopLimit missed a cast");10051006// Insert a new icmp_ne or icmp_eq instruction before the branch.1007BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());1008ICmpInst::Predicate P;1009if (L->contains(BI->getSuccessor(0)))1010P = ICmpInst::ICMP_NE;1011else1012P = ICmpInst::ICMP_EQ;10131014IRBuilder<> Builder(BI);10151016// The new loop exit condition should reuse the debug location of the1017// original loop exit condition.1018if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))1019Builder.SetCurrentDebugLocation(Cond->getDebugLoc());10201021// For integer IVs, if we evaluated the limit in the narrower bitwidth to1022// avoid the expensive expansion of the limit expression in the wider type,1023// emit a truncate to narrow the IV to the ExitCount type. This is safe1024// since we know (from the exit count bitwidth), that we can't self-wrap in1025// the narrower type.1026unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());1027unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());1028if (CmpIndVarSize > ExitCntSize) {1029assert(!CmpIndVar->getType()->isPointerTy() &&1030!ExitCnt->getType()->isPointerTy());10311032// Before resorting to actually inserting the truncate, use the same1033// reasoning as from SimplifyIndvar::eliminateTrunc to see if we can extend1034// the other side of the comparison instead. We still evaluate the limit1035// in the narrower bitwidth, we just prefer a zext/sext outside the loop to1036// a truncate within in.1037bool Extended = false;1038const SCEV *IV = SE->getSCEV(CmpIndVar);1039const SCEV *TruncatedIV = SE->getTruncateExpr(IV, ExitCnt->getType());1040const SCEV *ZExtTrunc =1041SE->getZeroExtendExpr(TruncatedIV, CmpIndVar->getType());10421043if (ZExtTrunc == IV) {1044Extended = true;1045ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),1046"wide.trip.count");1047} else {1048const SCEV *SExtTrunc =1049SE->getSignExtendExpr(TruncatedIV, CmpIndVar->getType());1050if (SExtTrunc == IV) {1051Extended = true;1052ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),1053"wide.trip.count");1054}1055}10561057if (Extended) {1058bool Discard;1059L->makeLoopInvariant(ExitCnt, Discard);1060} else1061CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),1062"lftr.wideiv");1063}1064LLVM_DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"1065<< " LHS:" << *CmpIndVar << '\n'1066<< " op:\t" << (P == ICmpInst::ICMP_NE ? "!=" : "==")1067<< "\n"1068<< " RHS:\t" << *ExitCnt << "\n"1069<< "ExitCount:\t" << *ExitCount << "\n"1070<< " was: " << *BI->getCondition() << "\n");10711072Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");1073Value *OrigCond = BI->getCondition();1074// It's tempting to use replaceAllUsesWith here to fully replace the old1075// comparison, but that's not immediately safe, since users of the old1076// comparison may not be dominated by the new comparison. Instead, just1077// update the branch to use the new comparison; in the common case this1078// will make old comparison dead.1079BI->setCondition(Cond);1080DeadInsts.emplace_back(OrigCond);10811082++NumLFTR;1083return true;1084}10851086//===----------------------------------------------------------------------===//1087// sinkUnusedInvariants. A late subpass to cleanup loop preheaders.1088//===----------------------------------------------------------------------===//10891090/// If there's a single exit block, sink any loop-invariant values that1091/// were defined in the preheader but not used inside the loop into the1092/// exit block to reduce register pressure in the loop.1093bool IndVarSimplify::sinkUnusedInvariants(Loop *L) {1094BasicBlock *ExitBlock = L->getExitBlock();1095if (!ExitBlock) return false;10961097BasicBlock *Preheader = L->getLoopPreheader();1098if (!Preheader) return false;10991100bool MadeAnyChanges = false;1101BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt();1102BasicBlock::iterator I(Preheader->getTerminator());1103while (I != Preheader->begin()) {1104--I;1105// New instructions were inserted at the end of the preheader.1106if (isa<PHINode>(I))1107break;11081109// Don't move instructions which might have side effects, since the side1110// effects need to complete before instructions inside the loop. Also don't1111// move instructions which might read memory, since the loop may modify1112// memory. Note that it's okay if the instruction might have undefined1113// behavior: LoopSimplify guarantees that the preheader dominates the exit1114// block.1115if (I->mayHaveSideEffects() || I->mayReadFromMemory())1116continue;11171118// Skip debug info intrinsics.1119if (isa<DbgInfoIntrinsic>(I))1120continue;11211122// Skip eh pad instructions.1123if (I->isEHPad())1124continue;11251126// Don't sink alloca: we never want to sink static alloca's out of the1127// entry block, and correctly sinking dynamic alloca's requires1128// checks for stacksave/stackrestore intrinsics.1129// FIXME: Refactor this check somehow?1130if (isa<AllocaInst>(I))1131continue;11321133// Determine if there is a use in or before the loop (direct or1134// otherwise).1135bool UsedInLoop = false;1136for (Use &U : I->uses()) {1137Instruction *User = cast<Instruction>(U.getUser());1138BasicBlock *UseBB = User->getParent();1139if (PHINode *P = dyn_cast<PHINode>(User)) {1140unsigned i =1141PHINode::getIncomingValueNumForOperand(U.getOperandNo());1142UseBB = P->getIncomingBlock(i);1143}1144if (UseBB == Preheader || L->contains(UseBB)) {1145UsedInLoop = true;1146break;1147}1148}11491150// If there is, the def must remain in the preheader.1151if (UsedInLoop)1152continue;11531154// Otherwise, sink it to the exit block.1155Instruction *ToMove = &*I;1156bool Done = false;11571158if (I != Preheader->begin()) {1159// Skip debug info intrinsics.1160do {1161--I;1162} while (I->isDebugOrPseudoInst() && I != Preheader->begin());11631164if (I->isDebugOrPseudoInst() && I == Preheader->begin())1165Done = true;1166} else {1167Done = true;1168}11691170MadeAnyChanges = true;1171ToMove->moveBefore(*ExitBlock, InsertPt);1172SE->forgetValue(ToMove);1173if (Done) break;1174InsertPt = ToMove->getIterator();1175}11761177return MadeAnyChanges;1178}11791180static void replaceExitCond(BranchInst *BI, Value *NewCond,1181SmallVectorImpl<WeakTrackingVH> &DeadInsts) {1182auto *OldCond = BI->getCondition();1183LLVM_DEBUG(dbgs() << "Replacing condition of loop-exiting branch " << *BI1184<< " with " << *NewCond << "\n");1185BI->setCondition(NewCond);1186if (OldCond->use_empty())1187DeadInsts.emplace_back(OldCond);1188}11891190static Constant *createFoldedExitCond(const Loop *L, BasicBlock *ExitingBB,1191bool IsTaken) {1192BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());1193bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));1194auto *OldCond = BI->getCondition();1195return ConstantInt::get(OldCond->getType(),1196IsTaken ? ExitIfTrue : !ExitIfTrue);1197}11981199static void foldExit(const Loop *L, BasicBlock *ExitingBB, bool IsTaken,1200SmallVectorImpl<WeakTrackingVH> &DeadInsts) {1201BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());1202auto *NewCond = createFoldedExitCond(L, ExitingBB, IsTaken);1203replaceExitCond(BI, NewCond, DeadInsts);1204}12051206static void replaceLoopPHINodesWithPreheaderValues(1207LoopInfo *LI, Loop *L, SmallVectorImpl<WeakTrackingVH> &DeadInsts,1208ScalarEvolution &SE) {1209assert(L->isLoopSimplifyForm() && "Should only do it in simplify form!");1210auto *LoopPreheader = L->getLoopPreheader();1211auto *LoopHeader = L->getHeader();1212SmallVector<Instruction *> Worklist;1213for (auto &PN : LoopHeader->phis()) {1214auto *PreheaderIncoming = PN.getIncomingValueForBlock(LoopPreheader);1215for (User *U : PN.users())1216Worklist.push_back(cast<Instruction>(U));1217SE.forgetValue(&PN);1218PN.replaceAllUsesWith(PreheaderIncoming);1219DeadInsts.emplace_back(&PN);1220}12211222// Replacing with the preheader value will often allow IV users to simplify1223// (especially if the preheader value is a constant).1224SmallPtrSet<Instruction *, 16> Visited;1225while (!Worklist.empty()) {1226auto *I = cast<Instruction>(Worklist.pop_back_val());1227if (!Visited.insert(I).second)1228continue;12291230// Don't simplify instructions outside the loop.1231if (!L->contains(I))1232continue;12331234Value *Res = simplifyInstruction(I, I->getDataLayout());1235if (Res && LI->replacementPreservesLCSSAForm(I, Res)) {1236for (User *U : I->users())1237Worklist.push_back(cast<Instruction>(U));1238I->replaceAllUsesWith(Res);1239DeadInsts.emplace_back(I);1240}1241}1242}12431244static Value *1245createInvariantCond(const Loop *L, BasicBlock *ExitingBB,1246const ScalarEvolution::LoopInvariantPredicate &LIP,1247SCEVExpander &Rewriter) {1248ICmpInst::Predicate InvariantPred = LIP.Pred;1249BasicBlock *Preheader = L->getLoopPreheader();1250assert(Preheader && "Preheader doesn't exist");1251Rewriter.setInsertPoint(Preheader->getTerminator());1252auto *LHSV = Rewriter.expandCodeFor(LIP.LHS);1253auto *RHSV = Rewriter.expandCodeFor(LIP.RHS);1254bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));1255if (ExitIfTrue)1256InvariantPred = ICmpInst::getInversePredicate(InvariantPred);1257IRBuilder<> Builder(Preheader->getTerminator());1258BranchInst *BI = cast<BranchInst>(ExitingBB->getTerminator());1259return Builder.CreateICmp(InvariantPred, LHSV, RHSV,1260BI->getCondition()->getName());1261}12621263static std::optional<Value *>1264createReplacement(ICmpInst *ICmp, const Loop *L, BasicBlock *ExitingBB,1265const SCEV *MaxIter, bool Inverted, bool SkipLastIter,1266ScalarEvolution *SE, SCEVExpander &Rewriter) {1267ICmpInst::Predicate Pred = ICmp->getPredicate();1268Value *LHS = ICmp->getOperand(0);1269Value *RHS = ICmp->getOperand(1);12701271// 'LHS pred RHS' should now mean that we stay in loop.1272auto *BI = cast<BranchInst>(ExitingBB->getTerminator());1273if (Inverted)1274Pred = CmpInst::getInversePredicate(Pred);12751276const SCEV *LHSS = SE->getSCEVAtScope(LHS, L);1277const SCEV *RHSS = SE->getSCEVAtScope(RHS, L);1278// Can we prove it to be trivially true or false?1279if (auto EV = SE->evaluatePredicateAt(Pred, LHSS, RHSS, BI))1280return createFoldedExitCond(L, ExitingBB, /*IsTaken*/ !*EV);12811282auto *ARTy = LHSS->getType();1283auto *MaxIterTy = MaxIter->getType();1284// If possible, adjust types.1285if (SE->getTypeSizeInBits(ARTy) > SE->getTypeSizeInBits(MaxIterTy))1286MaxIter = SE->getZeroExtendExpr(MaxIter, ARTy);1287else if (SE->getTypeSizeInBits(ARTy) < SE->getTypeSizeInBits(MaxIterTy)) {1288const SCEV *MinusOne = SE->getMinusOne(ARTy);1289auto *MaxAllowedIter = SE->getZeroExtendExpr(MinusOne, MaxIterTy);1290if (SE->isKnownPredicateAt(ICmpInst::ICMP_ULE, MaxIter, MaxAllowedIter, BI))1291MaxIter = SE->getTruncateExpr(MaxIter, ARTy);1292}12931294if (SkipLastIter) {1295// Semantically skip last iter is "subtract 1, do not bother about unsigned1296// wrap". getLoopInvariantExitCondDuringFirstIterations knows how to deal1297// with umin in a smart way, but umin(a, b) - 1 will likely not simplify.1298// So we manually construct umin(a - 1, b - 1).1299SmallVector<const SCEV *, 4> Elements;1300if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter)) {1301for (auto *Op : UMin->operands())1302Elements.push_back(SE->getMinusSCEV(Op, SE->getOne(Op->getType())));1303MaxIter = SE->getUMinFromMismatchedTypes(Elements);1304} else1305MaxIter = SE->getMinusSCEV(MaxIter, SE->getOne(MaxIter->getType()));1306}13071308// Check if there is a loop-invariant predicate equivalent to our check.1309auto LIP = SE->getLoopInvariantExitCondDuringFirstIterations(Pred, LHSS, RHSS,1310L, BI, MaxIter);1311if (!LIP)1312return std::nullopt;13131314// Can we prove it to be trivially true?1315if (SE->isKnownPredicateAt(LIP->Pred, LIP->LHS, LIP->RHS, BI))1316return createFoldedExitCond(L, ExitingBB, /*IsTaken*/ false);1317else1318return createInvariantCond(L, ExitingBB, *LIP, Rewriter);1319}13201321static bool optimizeLoopExitWithUnknownExitCount(1322const Loop *L, BranchInst *BI, BasicBlock *ExitingBB, const SCEV *MaxIter,1323bool SkipLastIter, ScalarEvolution *SE, SCEVExpander &Rewriter,1324SmallVectorImpl<WeakTrackingVH> &DeadInsts) {1325assert(1326(L->contains(BI->getSuccessor(0)) != L->contains(BI->getSuccessor(1))) &&1327"Not a loop exit!");13281329// For branch that stays in loop by TRUE condition, go through AND. For branch1330// that stays in loop by FALSE condition, go through OR. Both gives the1331// similar logic: "stay in loop iff all conditions are true(false)".1332bool Inverted = L->contains(BI->getSuccessor(1));1333SmallVector<ICmpInst *, 4> LeafConditions;1334SmallVector<Value *, 4> Worklist;1335SmallPtrSet<Value *, 4> Visited;1336Value *OldCond = BI->getCondition();1337Visited.insert(OldCond);1338Worklist.push_back(OldCond);13391340auto GoThrough = [&](Value *V) {1341Value *LHS = nullptr, *RHS = nullptr;1342if (Inverted) {1343if (!match(V, m_LogicalOr(m_Value(LHS), m_Value(RHS))))1344return false;1345} else {1346if (!match(V, m_LogicalAnd(m_Value(LHS), m_Value(RHS))))1347return false;1348}1349if (Visited.insert(LHS).second)1350Worklist.push_back(LHS);1351if (Visited.insert(RHS).second)1352Worklist.push_back(RHS);1353return true;1354};13551356do {1357Value *Curr = Worklist.pop_back_val();1358// Go through AND/OR conditions. Collect leaf ICMPs. We only care about1359// those with one use, to avoid instruction duplication.1360if (Curr->hasOneUse())1361if (!GoThrough(Curr))1362if (auto *ICmp = dyn_cast<ICmpInst>(Curr))1363LeafConditions.push_back(ICmp);1364} while (!Worklist.empty());13651366// If the current basic block has the same exit count as the whole loop, and1367// it consists of multiple icmp's, try to collect all icmp's that give exact1368// same exit count. For all other icmp's, we could use one less iteration,1369// because their value on the last iteration doesn't really matter.1370SmallPtrSet<ICmpInst *, 4> ICmpsFailingOnLastIter;1371if (!SkipLastIter && LeafConditions.size() > 1 &&1372SE->getExitCount(L, ExitingBB,1373ScalarEvolution::ExitCountKind::SymbolicMaximum) ==1374MaxIter)1375for (auto *ICmp : LeafConditions) {1376auto EL = SE->computeExitLimitFromCond(L, ICmp, Inverted,1377/*ControlsExit*/ false);1378auto *ExitMax = EL.SymbolicMaxNotTaken;1379if (isa<SCEVCouldNotCompute>(ExitMax))1380continue;1381// They could be of different types (specifically this happens after1382// IV widening).1383auto *WiderType =1384SE->getWiderType(ExitMax->getType(), MaxIter->getType());1385auto *WideExitMax = SE->getNoopOrZeroExtend(ExitMax, WiderType);1386auto *WideMaxIter = SE->getNoopOrZeroExtend(MaxIter, WiderType);1387if (WideExitMax == WideMaxIter)1388ICmpsFailingOnLastIter.insert(ICmp);1389}13901391bool Changed = false;1392for (auto *OldCond : LeafConditions) {1393// Skip last iteration for this icmp under one of two conditions:1394// - We do it for all conditions;1395// - There is another ICmp that would fail on last iter, so this one doesn't1396// really matter.1397bool OptimisticSkipLastIter = SkipLastIter;1398if (!OptimisticSkipLastIter) {1399if (ICmpsFailingOnLastIter.size() > 1)1400OptimisticSkipLastIter = true;1401else if (ICmpsFailingOnLastIter.size() == 1)1402OptimisticSkipLastIter = !ICmpsFailingOnLastIter.count(OldCond);1403}1404if (auto Replaced =1405createReplacement(OldCond, L, ExitingBB, MaxIter, Inverted,1406OptimisticSkipLastIter, SE, Rewriter)) {1407Changed = true;1408auto *NewCond = *Replaced;1409if (auto *NCI = dyn_cast<Instruction>(NewCond)) {1410NCI->setName(OldCond->getName() + ".first_iter");1411}1412LLVM_DEBUG(dbgs() << "Unknown exit count: Replacing " << *OldCond1413<< " with " << *NewCond << "\n");1414assert(OldCond->hasOneUse() && "Must be!");1415OldCond->replaceAllUsesWith(NewCond);1416DeadInsts.push_back(OldCond);1417// Make sure we no longer consider this condition as failing on last1418// iteration.1419ICmpsFailingOnLastIter.erase(OldCond);1420}1421}1422return Changed;1423}14241425bool IndVarSimplify::canonicalizeExitCondition(Loop *L) {1426// Note: This is duplicating a particular part on SimplifyIndVars reasoning.1427// We need to duplicate it because given icmp zext(small-iv), C, IVUsers1428// never reaches the icmp since the zext doesn't fold to an AddRec unless1429// it already has flags. The alternative to this would be to extending the1430// set of "interesting" IV users to include the icmp, but doing that1431// regresses results in practice by querying SCEVs before trip counts which1432// rely on them which results in SCEV caching sub-optimal answers. The1433// concern about caching sub-optimal results is why we only query SCEVs of1434// the loop invariant RHS here.1435SmallVector<BasicBlock*, 16> ExitingBlocks;1436L->getExitingBlocks(ExitingBlocks);1437bool Changed = false;1438for (auto *ExitingBB : ExitingBlocks) {1439auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());1440if (!BI)1441continue;1442assert(BI->isConditional() && "exit branch must be conditional");14431444auto *ICmp = dyn_cast<ICmpInst>(BI->getCondition());1445if (!ICmp || !ICmp->hasOneUse())1446continue;14471448auto *LHS = ICmp->getOperand(0);1449auto *RHS = ICmp->getOperand(1);1450// For the range reasoning, avoid computing SCEVs in the loop to avoid1451// poisoning cache with sub-optimal results. For the must-execute case,1452// this is a neccessary precondition for correctness.1453if (!L->isLoopInvariant(RHS)) {1454if (!L->isLoopInvariant(LHS))1455continue;1456// Same logic applies for the inverse case1457std::swap(LHS, RHS);1458}14591460// Match (icmp signed-cond zext, RHS)1461Value *LHSOp = nullptr;1462if (!match(LHS, m_ZExt(m_Value(LHSOp))) || !ICmp->isSigned())1463continue;14641465const DataLayout &DL = ExitingBB->getDataLayout();1466const unsigned InnerBitWidth = DL.getTypeSizeInBits(LHSOp->getType());1467const unsigned OuterBitWidth = DL.getTypeSizeInBits(RHS->getType());1468auto FullCR = ConstantRange::getFull(InnerBitWidth);1469FullCR = FullCR.zeroExtend(OuterBitWidth);1470auto RHSCR = SE->getUnsignedRange(SE->applyLoopGuards(SE->getSCEV(RHS), L));1471if (FullCR.contains(RHSCR)) {1472// We have now matched icmp signed-cond zext(X), zext(Y'), and can thus1473// replace the signed condition with the unsigned version.1474ICmp->setPredicate(ICmp->getUnsignedPredicate());1475Changed = true;1476// Note: No SCEV invalidation needed. We've changed the predicate, but1477// have not changed exit counts, or the values produced by the compare.1478continue;1479}1480}14811482// Now that we've canonicalized the condition to match the extend,1483// see if we can rotate the extend out of the loop.1484for (auto *ExitingBB : ExitingBlocks) {1485auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());1486if (!BI)1487continue;1488assert(BI->isConditional() && "exit branch must be conditional");14891490auto *ICmp = dyn_cast<ICmpInst>(BI->getCondition());1491if (!ICmp || !ICmp->hasOneUse() || !ICmp->isUnsigned())1492continue;14931494bool Swapped = false;1495auto *LHS = ICmp->getOperand(0);1496auto *RHS = ICmp->getOperand(1);1497if (L->isLoopInvariant(LHS) == L->isLoopInvariant(RHS))1498// Nothing to rotate1499continue;1500if (L->isLoopInvariant(LHS)) {1501// Same logic applies for the inverse case until we actually pick1502// which operand of the compare to update.1503Swapped = true;1504std::swap(LHS, RHS);1505}1506assert(!L->isLoopInvariant(LHS) && L->isLoopInvariant(RHS));15071508// Match (icmp unsigned-cond zext, RHS)1509// TODO: Extend to handle corresponding sext/signed-cmp case1510// TODO: Extend to other invertible functions1511Value *LHSOp = nullptr;1512if (!match(LHS, m_ZExt(m_Value(LHSOp))))1513continue;15141515// In general, we only rotate if we can do so without increasing the number1516// of instructions. The exception is when we have an zext(add-rec). The1517// reason for allowing this exception is that we know we need to get rid1518// of the zext for SCEV to be able to compute a trip count for said loops;1519// we consider the new trip count valuable enough to increase instruction1520// count by one.1521if (!LHS->hasOneUse() && !isa<SCEVAddRecExpr>(SE->getSCEV(LHSOp)))1522continue;15231524// Given a icmp unsigned-cond zext(Op) where zext(trunc(RHS)) == RHS1525// replace with an icmp of the form icmp unsigned-cond Op, trunc(RHS)1526// when zext is loop varying and RHS is loop invariant. This converts1527// loop varying work to loop-invariant work.1528auto doRotateTransform = [&]() {1529assert(ICmp->isUnsigned() && "must have proven unsigned already");1530auto *NewRHS = CastInst::Create(1531Instruction::Trunc, RHS, LHSOp->getType(), "",1532L->getLoopPreheader()->getTerminator()->getIterator());1533ICmp->setOperand(Swapped ? 1 : 0, LHSOp);1534ICmp->setOperand(Swapped ? 0 : 1, NewRHS);1535if (LHS->use_empty())1536DeadInsts.push_back(LHS);1537};153815391540const DataLayout &DL = ExitingBB->getDataLayout();1541const unsigned InnerBitWidth = DL.getTypeSizeInBits(LHSOp->getType());1542const unsigned OuterBitWidth = DL.getTypeSizeInBits(RHS->getType());1543auto FullCR = ConstantRange::getFull(InnerBitWidth);1544FullCR = FullCR.zeroExtend(OuterBitWidth);1545auto RHSCR = SE->getUnsignedRange(SE->applyLoopGuards(SE->getSCEV(RHS), L));1546if (FullCR.contains(RHSCR)) {1547doRotateTransform();1548Changed = true;1549// Note, we are leaving SCEV in an unfortunately imprecise case here1550// as rotation tends to reveal information about trip counts not1551// previously visible.1552continue;1553}1554}15551556return Changed;1557}15581559bool IndVarSimplify::optimizeLoopExits(Loop *L, SCEVExpander &Rewriter) {1560SmallVector<BasicBlock*, 16> ExitingBlocks;1561L->getExitingBlocks(ExitingBlocks);15621563// Remove all exits which aren't both rewriteable and execute on every1564// iteration.1565llvm::erase_if(ExitingBlocks, [&](BasicBlock *ExitingBB) {1566// If our exitting block exits multiple loops, we can only rewrite the1567// innermost one. Otherwise, we're changing how many times the innermost1568// loop runs before it exits.1569if (LI->getLoopFor(ExitingBB) != L)1570return true;15711572// Can't rewrite non-branch yet.1573BranchInst *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());1574if (!BI)1575return true;15761577// Likewise, the loop latch must be dominated by the exiting BB.1578if (!DT->dominates(ExitingBB, L->getLoopLatch()))1579return true;15801581if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {1582// If already constant, nothing to do. However, if this is an1583// unconditional exit, we can still replace header phis with their1584// preheader value.1585if (!L->contains(BI->getSuccessor(CI->isNullValue())))1586replaceLoopPHINodesWithPreheaderValues(LI, L, DeadInsts, *SE);1587return true;1588}15891590return false;1591});15921593if (ExitingBlocks.empty())1594return false;15951596// Get a symbolic upper bound on the loop backedge taken count.1597const SCEV *MaxBECount = SE->getSymbolicMaxBackedgeTakenCount(L);1598if (isa<SCEVCouldNotCompute>(MaxBECount))1599return false;16001601// Visit our exit blocks in order of dominance. We know from the fact that1602// all exits must dominate the latch, so there is a total dominance order1603// between them.1604llvm::sort(ExitingBlocks, [&](BasicBlock *A, BasicBlock *B) {1605// std::sort sorts in ascending order, so we want the inverse of1606// the normal dominance relation.1607if (A == B) return false;1608if (DT->properlyDominates(A, B))1609return true;1610else {1611assert(DT->properlyDominates(B, A) &&1612"expected total dominance order!");1613return false;1614}1615});1616#ifdef ASSERT1617for (unsigned i = 1; i < ExitingBlocks.size(); i++) {1618assert(DT->dominates(ExitingBlocks[i-1], ExitingBlocks[i]));1619}1620#endif16211622bool Changed = false;1623bool SkipLastIter = false;1624const SCEV *CurrMaxExit = SE->getCouldNotCompute();1625auto UpdateSkipLastIter = [&](const SCEV *MaxExitCount) {1626if (SkipLastIter || isa<SCEVCouldNotCompute>(MaxExitCount))1627return;1628if (isa<SCEVCouldNotCompute>(CurrMaxExit))1629CurrMaxExit = MaxExitCount;1630else1631CurrMaxExit = SE->getUMinFromMismatchedTypes(CurrMaxExit, MaxExitCount);1632// If the loop has more than 1 iteration, all further checks will be1633// executed 1 iteration less.1634if (CurrMaxExit == MaxBECount)1635SkipLastIter = true;1636};1637SmallSet<const SCEV *, 8> DominatingExactExitCounts;1638for (BasicBlock *ExitingBB : ExitingBlocks) {1639const SCEV *ExactExitCount = SE->getExitCount(L, ExitingBB);1640const SCEV *MaxExitCount = SE->getExitCount(1641L, ExitingBB, ScalarEvolution::ExitCountKind::SymbolicMaximum);1642if (isa<SCEVCouldNotCompute>(ExactExitCount)) {1643// Okay, we do not know the exit count here. Can we at least prove that it1644// will remain the same within iteration space?1645auto *BI = cast<BranchInst>(ExitingBB->getTerminator());1646auto OptimizeCond = [&](bool SkipLastIter) {1647return optimizeLoopExitWithUnknownExitCount(L, BI, ExitingBB,1648MaxBECount, SkipLastIter,1649SE, Rewriter, DeadInsts);1650};16511652// TODO: We might have proved that we can skip the last iteration for1653// this check. In this case, we only want to check the condition on the1654// pre-last iteration (MaxBECount - 1). However, there is a nasty1655// corner case:1656//1657// for (i = len; i != 0; i--) { ... check (i ult X) ... }1658//1659// If we could not prove that len != 0, then we also could not prove that1660// (len - 1) is not a UINT_MAX. If we simply query (len - 1), then1661// OptimizeCond will likely not prove anything for it, even if it could1662// prove the same fact for len.1663//1664// As a temporary solution, we query both last and pre-last iterations in1665// hope that we will be able to prove triviality for at least one of1666// them. We can stop querying MaxBECount for this case once SCEV1667// understands that (MaxBECount - 1) will not overflow here.1668if (OptimizeCond(false))1669Changed = true;1670else if (SkipLastIter && OptimizeCond(true))1671Changed = true;1672UpdateSkipLastIter(MaxExitCount);1673continue;1674}16751676UpdateSkipLastIter(ExactExitCount);16771678// If we know we'd exit on the first iteration, rewrite the exit to1679// reflect this. This does not imply the loop must exit through this1680// exit; there may be an earlier one taken on the first iteration.1681// We know that the backedge can't be taken, so we replace all1682// the header PHIs with values coming from the preheader.1683if (ExactExitCount->isZero()) {1684foldExit(L, ExitingBB, true, DeadInsts);1685replaceLoopPHINodesWithPreheaderValues(LI, L, DeadInsts, *SE);1686Changed = true;1687continue;1688}16891690assert(ExactExitCount->getType()->isIntegerTy() &&1691MaxBECount->getType()->isIntegerTy() &&1692"Exit counts must be integers");16931694Type *WiderType =1695SE->getWiderType(MaxBECount->getType(), ExactExitCount->getType());1696ExactExitCount = SE->getNoopOrZeroExtend(ExactExitCount, WiderType);1697MaxBECount = SE->getNoopOrZeroExtend(MaxBECount, WiderType);1698assert(MaxBECount->getType() == ExactExitCount->getType());16991700// Can we prove that some other exit must be taken strictly before this1701// one?1702if (SE->isLoopEntryGuardedByCond(L, CmpInst::ICMP_ULT, MaxBECount,1703ExactExitCount)) {1704foldExit(L, ExitingBB, false, DeadInsts);1705Changed = true;1706continue;1707}17081709// As we run, keep track of which exit counts we've encountered. If we1710// find a duplicate, we've found an exit which would have exited on the1711// exiting iteration, but (from the visit order) strictly follows another1712// which does the same and is thus dead.1713if (!DominatingExactExitCounts.insert(ExactExitCount).second) {1714foldExit(L, ExitingBB, false, DeadInsts);1715Changed = true;1716continue;1717}17181719// TODO: There might be another oppurtunity to leverage SCEV's reasoning1720// here. If we kept track of the min of dominanting exits so far, we could1721// discharge exits with EC >= MDEC. This is less powerful than the existing1722// transform (since later exits aren't considered), but potentially more1723// powerful for any case where SCEV can prove a >=u b, but neither a == b1724// or a >u b. Such a case is not currently known.1725}1726return Changed;1727}17281729bool IndVarSimplify::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {1730SmallVector<BasicBlock*, 16> ExitingBlocks;1731L->getExitingBlocks(ExitingBlocks);17321733// Finally, see if we can rewrite our exit conditions into a loop invariant1734// form. If we have a read-only loop, and we can tell that we must exit down1735// a path which does not need any of the values computed within the loop, we1736// can rewrite the loop to exit on the first iteration. Note that this1737// doesn't either a) tell us the loop exits on the first iteration (unless1738// *all* exits are predicateable) or b) tell us *which* exit might be taken.1739// This transformation looks a lot like a restricted form of dead loop1740// elimination, but restricted to read-only loops and without neccesssarily1741// needing to kill the loop entirely.1742if (!LoopPredication)1743return false;17441745// Note: ExactBTC is the exact backedge taken count *iff* the loop exits1746// through *explicit* control flow. We have to eliminate the possibility of1747// implicit exits (see below) before we know it's truly exact.1748const SCEV *ExactBTC = SE->getBackedgeTakenCount(L);1749if (isa<SCEVCouldNotCompute>(ExactBTC) || !Rewriter.isSafeToExpand(ExactBTC))1750return false;17511752assert(SE->isLoopInvariant(ExactBTC, L) && "BTC must be loop invariant");1753assert(ExactBTC->getType()->isIntegerTy() && "BTC must be integer");17541755auto BadExit = [&](BasicBlock *ExitingBB) {1756// If our exiting block exits multiple loops, we can only rewrite the1757// innermost one. Otherwise, we're changing how many times the innermost1758// loop runs before it exits.1759if (LI->getLoopFor(ExitingBB) != L)1760return true;17611762// Can't rewrite non-branch yet.1763BranchInst *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());1764if (!BI)1765return true;17661767// If already constant, nothing to do.1768if (isa<Constant>(BI->getCondition()))1769return true;17701771// If the exit block has phis, we need to be able to compute the values1772// within the loop which contains them. This assumes trivially lcssa phis1773// have already been removed; TODO: generalize1774BasicBlock *ExitBlock =1775BI->getSuccessor(L->contains(BI->getSuccessor(0)) ? 1 : 0);1776if (!ExitBlock->phis().empty())1777return true;17781779const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);1780if (isa<SCEVCouldNotCompute>(ExitCount) ||1781!Rewriter.isSafeToExpand(ExitCount))1782return true;17831784assert(SE->isLoopInvariant(ExitCount, L) &&1785"Exit count must be loop invariant");1786assert(ExitCount->getType()->isIntegerTy() && "Exit count must be integer");1787return false;1788};17891790// If we have any exits which can't be predicated themselves, than we can't1791// predicate any exit which isn't guaranteed to execute before it. Consider1792// two exits (a) and (b) which would both exit on the same iteration. If we1793// can predicate (b), but not (a), and (a) preceeds (b) along some path, then1794// we could convert a loop from exiting through (a) to one exiting through1795// (b). Note that this problem exists only for exits with the same exit1796// count, and we could be more aggressive when exit counts are known inequal.1797llvm::sort(ExitingBlocks,1798[&](BasicBlock *A, BasicBlock *B) {1799// std::sort sorts in ascending order, so we want the inverse of1800// the normal dominance relation, plus a tie breaker for blocks1801// unordered by dominance.1802if (DT->properlyDominates(A, B)) return true;1803if (DT->properlyDominates(B, A)) return false;1804return A->getName() < B->getName();1805});1806// Check to see if our exit blocks are a total order (i.e. a linear chain of1807// exits before the backedge). If they aren't, reasoning about reachability1808// is complicated and we choose not to for now.1809for (unsigned i = 1; i < ExitingBlocks.size(); i++)1810if (!DT->dominates(ExitingBlocks[i-1], ExitingBlocks[i]))1811return false;18121813// Given our sorted total order, we know that exit[j] must be evaluated1814// after all exit[i] such j > i.1815for (unsigned i = 0, e = ExitingBlocks.size(); i < e; i++)1816if (BadExit(ExitingBlocks[i])) {1817ExitingBlocks.resize(i);1818break;1819}18201821if (ExitingBlocks.empty())1822return false;18231824// We rely on not being able to reach an exiting block on a later iteration1825// then it's statically compute exit count. The implementaton of1826// getExitCount currently has this invariant, but assert it here so that1827// breakage is obvious if this ever changes..1828assert(llvm::all_of(ExitingBlocks, [&](BasicBlock *ExitingBB) {1829return DT->dominates(ExitingBB, L->getLoopLatch());1830}));18311832// At this point, ExitingBlocks consists of only those blocks which are1833// predicatable. Given that, we know we have at least one exit we can1834// predicate if the loop is doesn't have side effects and doesn't have any1835// implicit exits (because then our exact BTC isn't actually exact).1836// @Reviewers - As structured, this is O(I^2) for loop nests. Any1837// suggestions on how to improve this? I can obviously bail out for outer1838// loops, but that seems less than ideal. MemorySSA can find memory writes,1839// is that enough for *all* side effects?1840for (BasicBlock *BB : L->blocks())1841for (auto &I : *BB)1842// TODO:isGuaranteedToTransfer1843if (I.mayHaveSideEffects())1844return false;18451846bool Changed = false;1847// Finally, do the actual predication for all predicatable blocks. A couple1848// of notes here:1849// 1) We don't bother to constant fold dominated exits with identical exit1850// counts; that's simply a form of CSE/equality propagation and we leave1851// it for dedicated passes.1852// 2) We insert the comparison at the branch. Hoisting introduces additional1853// legality constraints and we leave that to dedicated logic. We want to1854// predicate even if we can't insert a loop invariant expression as1855// peeling or unrolling will likely reduce the cost of the otherwise loop1856// varying check.1857Rewriter.setInsertPoint(L->getLoopPreheader()->getTerminator());1858IRBuilder<> B(L->getLoopPreheader()->getTerminator());1859Value *ExactBTCV = nullptr; // Lazily generated if needed.1860for (BasicBlock *ExitingBB : ExitingBlocks) {1861const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);18621863auto *BI = cast<BranchInst>(ExitingBB->getTerminator());1864Value *NewCond;1865if (ExitCount == ExactBTC) {1866NewCond = L->contains(BI->getSuccessor(0)) ?1867B.getFalse() : B.getTrue();1868} else {1869Value *ECV = Rewriter.expandCodeFor(ExitCount);1870if (!ExactBTCV)1871ExactBTCV = Rewriter.expandCodeFor(ExactBTC);1872Value *RHS = ExactBTCV;1873if (ECV->getType() != RHS->getType()) {1874Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());1875ECV = B.CreateZExt(ECV, WiderTy);1876RHS = B.CreateZExt(RHS, WiderTy);1877}1878auto Pred = L->contains(BI->getSuccessor(0)) ?1879ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;1880NewCond = B.CreateICmp(Pred, ECV, RHS);1881}1882Value *OldCond = BI->getCondition();1883BI->setCondition(NewCond);1884if (OldCond->use_empty())1885DeadInsts.emplace_back(OldCond);1886Changed = true;1887RunUnswitching = true;1888}18891890return Changed;1891}18921893//===----------------------------------------------------------------------===//1894// IndVarSimplify driver. Manage several subpasses of IV simplification.1895//===----------------------------------------------------------------------===//18961897bool IndVarSimplify::run(Loop *L) {1898// We need (and expect!) the incoming loop to be in LCSSA.1899assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&1900"LCSSA required to run indvars!");19011902// If LoopSimplify form is not available, stay out of trouble. Some notes:1903// - LSR currently only supports LoopSimplify-form loops. Indvars'1904// canonicalization can be a pessimization without LSR to "clean up"1905// afterwards.1906// - We depend on having a preheader; in particular,1907// Loop::getCanonicalInductionVariable only supports loops with preheaders,1908// and we're in trouble if we can't find the induction variable even when1909// we've manually inserted one.1910// - LFTR relies on having a single backedge.1911if (!L->isLoopSimplifyForm())1912return false;19131914bool Changed = false;1915// If there are any floating-point recurrences, attempt to1916// transform them to use integer recurrences.1917Changed |= rewriteNonIntegerIVs(L);19181919// Create a rewriter object which we'll use to transform the code with.1920SCEVExpander Rewriter(*SE, DL, "indvars");1921#ifndef NDEBUG1922Rewriter.setDebugType(DEBUG_TYPE);1923#endif19241925// Eliminate redundant IV users.1926//1927// Simplification works best when run before other consumers of SCEV. We1928// attempt to avoid evaluating SCEVs for sign/zero extend operations until1929// other expressions involving loop IVs have been evaluated. This helps SCEV1930// set no-wrap flags before normalizing sign/zero extension.1931Rewriter.disableCanonicalMode();1932Changed |= simplifyAndExtend(L, Rewriter, LI);19331934// Check to see if we can compute the final value of any expressions1935// that are recurrent in the loop, and substitute the exit values from the1936// loop into any instructions outside of the loop that use the final values1937// of the current expressions.1938if (ReplaceExitValue != NeverRepl) {1939if (int Rewrites = rewriteLoopExitValues(L, LI, TLI, SE, TTI, Rewriter, DT,1940ReplaceExitValue, DeadInsts)) {1941NumReplaced += Rewrites;1942Changed = true;1943}1944}19451946// Eliminate redundant IV cycles.1947NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts, TTI);19481949// Try to convert exit conditions to unsigned and rotate computation1950// out of the loop. Note: Handles invalidation internally if needed.1951Changed |= canonicalizeExitCondition(L);19521953// Try to eliminate loop exits based on analyzeable exit counts1954if (optimizeLoopExits(L, Rewriter)) {1955Changed = true;1956// Given we've changed exit counts, notify SCEV1957// Some nested loops may share same folded exit basic block,1958// thus we need to notify top most loop.1959SE->forgetTopmostLoop(L);1960}19611962// Try to form loop invariant tests for loop exits by changing how many1963// iterations of the loop run when that is unobservable.1964if (predicateLoopExits(L, Rewriter)) {1965Changed = true;1966// Given we've changed exit counts, notify SCEV1967SE->forgetLoop(L);1968}19691970// If we have a trip count expression, rewrite the loop's exit condition1971// using it.1972if (!DisableLFTR) {1973BasicBlock *PreHeader = L->getLoopPreheader();19741975SmallVector<BasicBlock*, 16> ExitingBlocks;1976L->getExitingBlocks(ExitingBlocks);1977for (BasicBlock *ExitingBB : ExitingBlocks) {1978// Can't rewrite non-branch yet.1979if (!isa<BranchInst>(ExitingBB->getTerminator()))1980continue;19811982// If our exitting block exits multiple loops, we can only rewrite the1983// innermost one. Otherwise, we're changing how many times the innermost1984// loop runs before it exits.1985if (LI->getLoopFor(ExitingBB) != L)1986continue;19871988if (!needsLFTR(L, ExitingBB))1989continue;19901991const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);1992if (isa<SCEVCouldNotCompute>(ExitCount))1993continue;19941995// This was handled above, but as we form SCEVs, we can sometimes refine1996// existing ones; this allows exit counts to be folded to zero which1997// weren't when optimizeLoopExits saw them. Arguably, we should iterate1998// until stable to handle cases like this better.1999if (ExitCount->isZero())2000continue;20012002PHINode *IndVar = FindLoopCounter(L, ExitingBB, ExitCount, SE, DT);2003if (!IndVar)2004continue;20052006// Avoid high cost expansions. Note: This heuristic is questionable in2007// that our definition of "high cost" is not exactly principled.2008if (Rewriter.isHighCostExpansion(ExitCount, L, SCEVCheapExpansionBudget,2009TTI, PreHeader->getTerminator()))2010continue;20112012if (!Rewriter.isSafeToExpand(ExitCount))2013continue;20142015Changed |= linearFunctionTestReplace(L, ExitingBB,2016ExitCount, IndVar,2017Rewriter);2018}2019}2020// Clear the rewriter cache, because values that are in the rewriter's cache2021// can be deleted in the loop below, causing the AssertingVH in the cache to2022// trigger.2023Rewriter.clear();20242025// Now that we're done iterating through lists, clean up any instructions2026// which are now dead.2027while (!DeadInsts.empty()) {2028Value *V = DeadInsts.pop_back_val();20292030if (PHINode *PHI = dyn_cast_or_null<PHINode>(V))2031Changed |= RecursivelyDeleteDeadPHINode(PHI, TLI, MSSAU.get());2032else if (Instruction *Inst = dyn_cast_or_null<Instruction>(V))2033Changed |=2034RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI, MSSAU.get());2035}20362037// The Rewriter may not be used from this point on.20382039// Loop-invariant instructions in the preheader that aren't used in the2040// loop may be sunk below the loop to reduce register pressure.2041Changed |= sinkUnusedInvariants(L);20422043// rewriteFirstIterationLoopExitValues does not rely on the computation of2044// trip count and therefore can further simplify exit values in addition to2045// rewriteLoopExitValues.2046Changed |= rewriteFirstIterationLoopExitValues(L);20472048// Clean up dead instructions.2049Changed |= DeleteDeadPHIs(L->getHeader(), TLI, MSSAU.get());20502051// Check a post-condition.2052assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&2053"Indvars did not preserve LCSSA!");2054if (VerifyMemorySSA && MSSAU)2055MSSAU->getMemorySSA()->verifyMemorySSA();20562057return Changed;2058}20592060PreservedAnalyses IndVarSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,2061LoopStandardAnalysisResults &AR,2062LPMUpdater &) {2063Function *F = L.getHeader()->getParent();2064const DataLayout &DL = F->getDataLayout();20652066IndVarSimplify IVS(&AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI, AR.MSSA,2067WidenIndVars && AllowIVWidening);2068if (!IVS.run(&L))2069return PreservedAnalyses::all();20702071auto PA = getLoopPassPreservedAnalyses();2072PA.preserveSet<CFGAnalyses>();2073if (IVS.runUnswitching()) {2074AM.getResult<ShouldRunExtraSimpleLoopUnswitch>(L, AR);2075PA.preserve<ShouldRunExtraSimpleLoopUnswitch>();2076}20772078if (AR.MSSA)2079PA.preserve<MemorySSAAnalysis>();2080return PA;2081}208220832084