1e8d8bef9SDimitry Andric //===- LoopFlatten.cpp - Loop flattening pass------------------------------===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric // 9e8d8bef9SDimitry Andric // This pass flattens pairs nested loops into a single loop. 10e8d8bef9SDimitry Andric // 11e8d8bef9SDimitry Andric // The intention is to optimise loop nests like this, which together access an 12e8d8bef9SDimitry Andric // array linearly: 1304eeddc0SDimitry Andric // 14e8d8bef9SDimitry Andric // for (int i = 0; i < N; ++i) 15e8d8bef9SDimitry Andric // for (int j = 0; j < M; ++j) 16e8d8bef9SDimitry Andric // f(A[i*M+j]); 1704eeddc0SDimitry Andric // 18e8d8bef9SDimitry Andric // into one loop: 1904eeddc0SDimitry Andric // 20e8d8bef9SDimitry Andric // for (int i = 0; i < (N*M); ++i) 21e8d8bef9SDimitry Andric // f(A[i]); 22e8d8bef9SDimitry Andric // 23e8d8bef9SDimitry Andric // It can also flatten loops where the induction variables are not used in the 24e8d8bef9SDimitry Andric // loop. This is only worth doing if the induction variables are only used in an 25e8d8bef9SDimitry Andric // expression like i*M+j. If they had any other uses, we would have to insert a 26e8d8bef9SDimitry Andric // div/mod to reconstruct the original values, so this wouldn't be profitable. 27e8d8bef9SDimitry Andric // 2804eeddc0SDimitry Andric // We also need to prove that N*M will not overflow. The preferred solution is 2904eeddc0SDimitry Andric // to widen the IV, which avoids overflow checks, so that is tried first. If 3004eeddc0SDimitry Andric // the IV cannot be widened, then we try to determine that this new tripcount 3104eeddc0SDimitry Andric // expression won't overflow. 3204eeddc0SDimitry Andric // 3304eeddc0SDimitry Andric // Q: Does LoopFlatten use SCEV? 3404eeddc0SDimitry Andric // Short answer: Yes and no. 3504eeddc0SDimitry Andric // 3604eeddc0SDimitry Andric // Long answer: 3704eeddc0SDimitry Andric // For this transformation to be valid, we require all uses of the induction 3804eeddc0SDimitry Andric // variables to be linear expressions of the form i*M+j. The different Loop 3904eeddc0SDimitry Andric // APIs are used to get some loop components like the induction variable, 4004eeddc0SDimitry Andric // compare statement, etc. In addition, we do some pattern matching to find the 4104eeddc0SDimitry Andric // linear expressions and other loop components like the loop increment. The 4204eeddc0SDimitry Andric // latter are examples of expressions that do use the induction variable, but 4304eeddc0SDimitry Andric // are safe to ignore when we check all uses to be of the form i*M+j. We keep 4404eeddc0SDimitry Andric // track of all of this in bookkeeping struct FlattenInfo. 4504eeddc0SDimitry Andric // We assume the loops to be canonical, i.e. starting at 0 and increment with 4604eeddc0SDimitry Andric // 1. This makes RHS of the compare the loop tripcount (with the right 4704eeddc0SDimitry Andric // predicate). We use SCEV to then sanity check that this tripcount matches 4804eeddc0SDimitry Andric // with the tripcount as computed by SCEV. 49e8d8bef9SDimitry Andric // 50e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 51e8d8bef9SDimitry Andric 52e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/LoopFlatten.h" 53349cc55cSDimitry Andric 54349cc55cSDimitry Andric #include "llvm/ADT/Statistic.h" 55e8d8bef9SDimitry Andric #include "llvm/Analysis/AssumptionCache.h" 56e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 5781ad6265SDimitry Andric #include "llvm/Analysis/LoopNestAnalysis.h" 5804eeddc0SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h" 59e8d8bef9SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h" 60e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 61e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 62e8d8bef9SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 63e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 64e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 65e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h" 66e8d8bef9SDimitry Andric #include "llvm/IR/Module.h" 67e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 68e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h" 69e8d8bef9SDimitry Andric #include "llvm/Pass.h" 70e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 71e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 72e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar.h" 7381ad6265SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h" 74e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 75e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 76e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 77e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h" 78*bdd1243dSDimitry Andric #include <optional> 79e8d8bef9SDimitry Andric 80e8d8bef9SDimitry Andric using namespace llvm; 81e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 82e8d8bef9SDimitry Andric 83349cc55cSDimitry Andric #define DEBUG_TYPE "loop-flatten" 84349cc55cSDimitry Andric 85349cc55cSDimitry Andric STATISTIC(NumFlattened, "Number of loops flattened"); 86349cc55cSDimitry Andric 87e8d8bef9SDimitry Andric static cl::opt<unsigned> RepeatedInstructionThreshold( 88e8d8bef9SDimitry Andric "loop-flatten-cost-threshold", cl::Hidden, cl::init(2), 89e8d8bef9SDimitry Andric cl::desc("Limit on the cost of instructions that can be repeated due to " 90e8d8bef9SDimitry Andric "loop flattening")); 91e8d8bef9SDimitry Andric 92e8d8bef9SDimitry Andric static cl::opt<bool> 93e8d8bef9SDimitry Andric AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, 94e8d8bef9SDimitry Andric cl::init(false), 95e8d8bef9SDimitry Andric cl::desc("Assume that the product of the two iteration " 96fe6060f1SDimitry Andric "trip counts will never overflow")); 97e8d8bef9SDimitry Andric 98e8d8bef9SDimitry Andric static cl::opt<bool> 9904eeddc0SDimitry Andric WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true), 100e8d8bef9SDimitry Andric cl::desc("Widen the loop induction variables, if possible, so " 101e8d8bef9SDimitry Andric "overflow checks won't reject flattening")); 102e8d8bef9SDimitry Andric 103*bdd1243dSDimitry Andric namespace { 10404eeddc0SDimitry Andric // We require all uses of both induction variables to match this pattern: 10504eeddc0SDimitry Andric // 10604eeddc0SDimitry Andric // (OuterPHI * InnerTripCount) + InnerPHI 10704eeddc0SDimitry Andric // 10804eeddc0SDimitry Andric // I.e., it needs to be a linear expression of the induction variables and the 10904eeddc0SDimitry Andric // inner loop trip count. We keep track of all different expressions on which 11004eeddc0SDimitry Andric // checks will be performed in this bookkeeping struct. 11104eeddc0SDimitry Andric // 112e8d8bef9SDimitry Andric struct FlattenInfo { 11304eeddc0SDimitry Andric Loop *OuterLoop = nullptr; // The loop pair to be flattened. 114e8d8bef9SDimitry Andric Loop *InnerLoop = nullptr; 11504eeddc0SDimitry Andric 11604eeddc0SDimitry Andric PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop 11704eeddc0SDimitry Andric PHINode *OuterInductionPHI = nullptr; // induction variables, which are 11804eeddc0SDimitry Andric // expected to start at zero and 11904eeddc0SDimitry Andric // increment by one on each loop. 12004eeddc0SDimitry Andric 12104eeddc0SDimitry Andric Value *InnerTripCount = nullptr; // The product of these two tripcounts 12204eeddc0SDimitry Andric Value *OuterTripCount = nullptr; // will be the new flattened loop 12304eeddc0SDimitry Andric // tripcount. Also used to recognise a 12404eeddc0SDimitry Andric // linear expression that will be replaced. 12504eeddc0SDimitry Andric 12604eeddc0SDimitry Andric SmallPtrSet<Value *, 4> LinearIVUses; // Contains the linear expressions 12704eeddc0SDimitry Andric // of the form i*M+j that will be 12804eeddc0SDimitry Andric // replaced. 12904eeddc0SDimitry Andric 13004eeddc0SDimitry Andric BinaryOperator *InnerIncrement = nullptr; // Uses of induction variables in 13104eeddc0SDimitry Andric BinaryOperator *OuterIncrement = nullptr; // loop control statements that 13204eeddc0SDimitry Andric BranchInst *InnerBranch = nullptr; // are safe to ignore. 13304eeddc0SDimitry Andric 13404eeddc0SDimitry Andric BranchInst *OuterBranch = nullptr; // The instruction that needs to be 13504eeddc0SDimitry Andric // updated with new tripcount. 13604eeddc0SDimitry Andric 137e8d8bef9SDimitry Andric SmallPtrSet<PHINode *, 4> InnerPHIsToTransform; 138e8d8bef9SDimitry Andric 13904eeddc0SDimitry Andric bool Widened = false; // Whether this holds the flatten info before or after 14004eeddc0SDimitry Andric // widening. 141e8d8bef9SDimitry Andric 14204eeddc0SDimitry Andric PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction 14304eeddc0SDimitry Andric PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV 144*bdd1243dSDimitry Andric // has been applied. Used to skip 14504eeddc0SDimitry Andric // checks on phi nodes. 146349cc55cSDimitry Andric 147e8d8bef9SDimitry Andric FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){}; 148349cc55cSDimitry Andric 149349cc55cSDimitry Andric bool isNarrowInductionPhi(PHINode *Phi) { 150349cc55cSDimitry Andric // This can't be the narrow phi if we haven't widened the IV first. 151349cc55cSDimitry Andric if (!Widened) 152349cc55cSDimitry Andric return false; 153349cc55cSDimitry Andric return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi; 154349cc55cSDimitry Andric } 15504eeddc0SDimitry Andric bool isInnerLoopIncrement(User *U) { 15604eeddc0SDimitry Andric return InnerIncrement == U; 15704eeddc0SDimitry Andric } 15804eeddc0SDimitry Andric bool isOuterLoopIncrement(User *U) { 15904eeddc0SDimitry Andric return OuterIncrement == U; 16004eeddc0SDimitry Andric } 16104eeddc0SDimitry Andric bool isInnerLoopTest(User *U) { 16204eeddc0SDimitry Andric return InnerBranch->getCondition() == U; 16304eeddc0SDimitry Andric } 16404eeddc0SDimitry Andric 16504eeddc0SDimitry Andric bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) { 16604eeddc0SDimitry Andric for (User *U : OuterInductionPHI->users()) { 16704eeddc0SDimitry Andric if (isOuterLoopIncrement(U)) 16804eeddc0SDimitry Andric continue; 16904eeddc0SDimitry Andric 17004eeddc0SDimitry Andric auto IsValidOuterPHIUses = [&] (User *U) -> bool { 17104eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump()); 17204eeddc0SDimitry Andric if (!ValidOuterPHIUses.count(U)) { 17304eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 17404eeddc0SDimitry Andric return false; 17504eeddc0SDimitry Andric } 17604eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 17704eeddc0SDimitry Andric return true; 17804eeddc0SDimitry Andric }; 17904eeddc0SDimitry Andric 18004eeddc0SDimitry Andric if (auto *V = dyn_cast<TruncInst>(U)) { 18104eeddc0SDimitry Andric for (auto *K : V->users()) { 18204eeddc0SDimitry Andric if (!IsValidOuterPHIUses(K)) 18304eeddc0SDimitry Andric return false; 18404eeddc0SDimitry Andric } 18504eeddc0SDimitry Andric continue; 18604eeddc0SDimitry Andric } 18704eeddc0SDimitry Andric 18804eeddc0SDimitry Andric if (!IsValidOuterPHIUses(U)) 18904eeddc0SDimitry Andric return false; 19004eeddc0SDimitry Andric } 19104eeddc0SDimitry Andric return true; 19204eeddc0SDimitry Andric } 19304eeddc0SDimitry Andric 19404eeddc0SDimitry Andric bool matchLinearIVUser(User *U, Value *InnerTripCount, 19504eeddc0SDimitry Andric SmallPtrSet<Value *, 4> &ValidOuterPHIUses) { 196*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Checking linear i*M+j expression for: "; U->dump()); 19704eeddc0SDimitry Andric Value *MatchedMul = nullptr; 19804eeddc0SDimitry Andric Value *MatchedItCount = nullptr; 19904eeddc0SDimitry Andric 20004eeddc0SDimitry Andric bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI), 20104eeddc0SDimitry Andric m_Value(MatchedMul))) && 20204eeddc0SDimitry Andric match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI), 20304eeddc0SDimitry Andric m_Value(MatchedItCount))); 20404eeddc0SDimitry Andric 20504eeddc0SDimitry Andric // Matches the same pattern as above, except it also looks for truncs 20604eeddc0SDimitry Andric // on the phi, which can be the result of widening the induction variables. 20704eeddc0SDimitry Andric bool IsAddTrunc = 20804eeddc0SDimitry Andric match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)), 20904eeddc0SDimitry Andric m_Value(MatchedMul))) && 21004eeddc0SDimitry Andric match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)), 21104eeddc0SDimitry Andric m_Value(MatchedItCount))); 21204eeddc0SDimitry Andric 21304eeddc0SDimitry Andric if (!MatchedItCount) 21404eeddc0SDimitry Andric return false; 21504eeddc0SDimitry Andric 216*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Matched multiplication: "; MatchedMul->dump()); 217*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Matched iteration count: "; MatchedItCount->dump()); 218*bdd1243dSDimitry Andric 219*bdd1243dSDimitry Andric // The mul should not have any other uses. Widening may leave trivially dead 220*bdd1243dSDimitry Andric // uses, which can be ignored. 221*bdd1243dSDimitry Andric if (count_if(MatchedMul->users(), [](User *U) { 222*bdd1243dSDimitry Andric return !isInstructionTriviallyDead(cast<Instruction>(U)); 223*bdd1243dSDimitry Andric }) > 1) { 224*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Multiply has more than one use\n"); 225*bdd1243dSDimitry Andric return false; 226*bdd1243dSDimitry Andric } 227*bdd1243dSDimitry Andric 22881ad6265SDimitry Andric // Look through extends if the IV has been widened. Don't look through 22981ad6265SDimitry Andric // extends if we already looked through a trunc. 23081ad6265SDimitry Andric if (Widened && IsAdd && 23104eeddc0SDimitry Andric (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) { 23204eeddc0SDimitry Andric assert(MatchedItCount->getType() == InnerInductionPHI->getType() && 23304eeddc0SDimitry Andric "Unexpected type mismatch in types after widening"); 23404eeddc0SDimitry Andric MatchedItCount = isa<SExtInst>(MatchedItCount) 23504eeddc0SDimitry Andric ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0) 23604eeddc0SDimitry Andric : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0); 23704eeddc0SDimitry Andric } 23804eeddc0SDimitry Andric 239*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Looking for inner trip count: "; 240*bdd1243dSDimitry Andric InnerTripCount->dump()); 241*bdd1243dSDimitry Andric 24204eeddc0SDimitry Andric if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) { 243*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Found. This sse is optimisable\n"); 24404eeddc0SDimitry Andric ValidOuterPHIUses.insert(MatchedMul); 24504eeddc0SDimitry Andric LinearIVUses.insert(U); 24604eeddc0SDimitry Andric return true; 24704eeddc0SDimitry Andric } 24804eeddc0SDimitry Andric 24904eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 25004eeddc0SDimitry Andric return false; 25104eeddc0SDimitry Andric } 25204eeddc0SDimitry Andric 25304eeddc0SDimitry Andric bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) { 25404eeddc0SDimitry Andric Value *SExtInnerTripCount = InnerTripCount; 25504eeddc0SDimitry Andric if (Widened && 25604eeddc0SDimitry Andric (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount))) 25704eeddc0SDimitry Andric SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0); 25804eeddc0SDimitry Andric 25904eeddc0SDimitry Andric for (User *U : InnerInductionPHI->users()) { 260*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Checking User: "; U->dump()); 261*bdd1243dSDimitry Andric if (isInnerLoopIncrement(U)) { 262*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Use is inner loop increment, continuing\n"); 26304eeddc0SDimitry Andric continue; 264*bdd1243dSDimitry Andric } 26504eeddc0SDimitry Andric 26604eeddc0SDimitry Andric // After widening the IVs, a trunc instruction might have been introduced, 26704eeddc0SDimitry Andric // so look through truncs. 26804eeddc0SDimitry Andric if (isa<TruncInst>(U)) { 26904eeddc0SDimitry Andric if (!U->hasOneUse()) 27004eeddc0SDimitry Andric return false; 27104eeddc0SDimitry Andric U = *U->user_begin(); 27204eeddc0SDimitry Andric } 27304eeddc0SDimitry Andric 27404eeddc0SDimitry Andric // If the use is in the compare (which is also the condition of the inner 27504eeddc0SDimitry Andric // branch) then the compare has been altered by another transformation e.g 27604eeddc0SDimitry Andric // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is 27704eeddc0SDimitry Andric // a constant. Ignore this use as the compare gets removed later anyway. 278*bdd1243dSDimitry Andric if (isInnerLoopTest(U)) { 279*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Use is the inner loop test, continuing\n"); 28004eeddc0SDimitry Andric continue; 281*bdd1243dSDimitry Andric } 28204eeddc0SDimitry Andric 283*bdd1243dSDimitry Andric if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses)) { 284*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Not a linear IV user\n"); 28504eeddc0SDimitry Andric return false; 28604eeddc0SDimitry Andric } 287*bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Linear IV users found!\n"); 288*bdd1243dSDimitry Andric } 28904eeddc0SDimitry Andric return true; 29004eeddc0SDimitry Andric } 291e8d8bef9SDimitry Andric }; 292*bdd1243dSDimitry Andric } // namespace 293e8d8bef9SDimitry Andric 294349cc55cSDimitry Andric static bool 295349cc55cSDimitry Andric setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment, 296349cc55cSDimitry Andric SmallPtrSetImpl<Instruction *> &IterationInstructions) { 297349cc55cSDimitry Andric TripCount = TC; 298349cc55cSDimitry Andric IterationInstructions.insert(Increment); 299349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump()); 300349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump()); 301349cc55cSDimitry Andric LLVM_DEBUG(dbgs() << "Successfully found all loop components\n"); 302349cc55cSDimitry Andric return true; 303349cc55cSDimitry Andric } 304349cc55cSDimitry Andric 30504eeddc0SDimitry Andric // Given the RHS of the loop latch compare instruction, verify with SCEV 30604eeddc0SDimitry Andric // that this is indeed the loop tripcount. 30704eeddc0SDimitry Andric // TODO: This used to be a straightforward check but has grown to be quite 30804eeddc0SDimitry Andric // complicated now. It is therefore worth revisiting what the additional 30904eeddc0SDimitry Andric // benefits are of this (compared to relying on canonical loops and pattern 31004eeddc0SDimitry Andric // matching). 31104eeddc0SDimitry Andric static bool verifyTripCount(Value *RHS, Loop *L, 31204eeddc0SDimitry Andric SmallPtrSetImpl<Instruction *> &IterationInstructions, 31304eeddc0SDimitry Andric PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, 31404eeddc0SDimitry Andric BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) { 31504eeddc0SDimitry Andric const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L); 31604eeddc0SDimitry Andric if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 31704eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n"); 31804eeddc0SDimitry Andric return false; 31904eeddc0SDimitry Andric } 32004eeddc0SDimitry Andric 32104eeddc0SDimitry Andric // The Extend=false flag is used for getTripCountFromExitCount as we want 32204eeddc0SDimitry Andric // to verify and match it with the pattern matched tripcount. Please note 32304eeddc0SDimitry Andric // that overflow checks are performed in checkOverflow, but are first tried 32404eeddc0SDimitry Andric // to avoid by widening the IV. 32504eeddc0SDimitry Andric const SCEV *SCEVTripCount = 32604eeddc0SDimitry Andric SE->getTripCountFromExitCount(BackedgeTakenCount, /*Extend=*/false); 32704eeddc0SDimitry Andric 32804eeddc0SDimitry Andric const SCEV *SCEVRHS = SE->getSCEV(RHS); 32904eeddc0SDimitry Andric if (SCEVRHS == SCEVTripCount) 33004eeddc0SDimitry Andric return setLoopComponents(RHS, TripCount, Increment, IterationInstructions); 33104eeddc0SDimitry Andric ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS); 33204eeddc0SDimitry Andric if (ConstantRHS) { 33304eeddc0SDimitry Andric const SCEV *BackedgeTCExt = nullptr; 33404eeddc0SDimitry Andric if (IsWidened) { 33504eeddc0SDimitry Andric const SCEV *SCEVTripCountExt; 33604eeddc0SDimitry Andric // Find the extended backedge taken count and extended trip count using 33704eeddc0SDimitry Andric // SCEV. One of these should now match the RHS of the compare. 33804eeddc0SDimitry Andric BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType()); 33904eeddc0SDimitry Andric SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt, false); 34004eeddc0SDimitry Andric if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) { 34104eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid trip count\n"); 34204eeddc0SDimitry Andric return false; 34304eeddc0SDimitry Andric } 34404eeddc0SDimitry Andric } 34504eeddc0SDimitry Andric // If the RHS of the compare is equal to the backedge taken count we need 34604eeddc0SDimitry Andric // to add one to get the trip count. 34704eeddc0SDimitry Andric if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) { 34804eeddc0SDimitry Andric ConstantInt *One = ConstantInt::get(ConstantRHS->getType(), 1); 34904eeddc0SDimitry Andric Value *NewRHS = ConstantInt::get( 35004eeddc0SDimitry Andric ConstantRHS->getContext(), ConstantRHS->getValue() + One->getValue()); 35104eeddc0SDimitry Andric return setLoopComponents(NewRHS, TripCount, Increment, 35204eeddc0SDimitry Andric IterationInstructions); 35304eeddc0SDimitry Andric } 35404eeddc0SDimitry Andric return setLoopComponents(RHS, TripCount, Increment, IterationInstructions); 35504eeddc0SDimitry Andric } 35604eeddc0SDimitry Andric // If the RHS isn't a constant then check that the reason it doesn't match 35704eeddc0SDimitry Andric // the SCEV trip count is because the RHS is a ZExt or SExt instruction 35804eeddc0SDimitry Andric // (and take the trip count to be the RHS). 35904eeddc0SDimitry Andric if (!IsWidened) { 36004eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid trip count\n"); 36104eeddc0SDimitry Andric return false; 36204eeddc0SDimitry Andric } 36304eeddc0SDimitry Andric auto *TripCountInst = dyn_cast<Instruction>(RHS); 36404eeddc0SDimitry Andric if (!TripCountInst) { 36504eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid trip count\n"); 36604eeddc0SDimitry Andric return false; 36704eeddc0SDimitry Andric } 36804eeddc0SDimitry Andric if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) || 36904eeddc0SDimitry Andric SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) { 37004eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n"); 37104eeddc0SDimitry Andric return false; 37204eeddc0SDimitry Andric } 37304eeddc0SDimitry Andric return setLoopComponents(RHS, TripCount, Increment, IterationInstructions); 37404eeddc0SDimitry Andric } 37504eeddc0SDimitry Andric 376fe6060f1SDimitry Andric // Finds the induction variable, increment and trip count for a simple loop that 377fe6060f1SDimitry Andric // we can flatten. 378e8d8bef9SDimitry Andric static bool findLoopComponents( 379e8d8bef9SDimitry Andric Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions, 380fe6060f1SDimitry Andric PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, 381fe6060f1SDimitry Andric BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) { 382e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n"); 383e8d8bef9SDimitry Andric 384e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) { 385e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Loop is not in normal form\n"); 386e8d8bef9SDimitry Andric return false; 387e8d8bef9SDimitry Andric } 388e8d8bef9SDimitry Andric 389fe6060f1SDimitry Andric // Currently, to simplify the implementation, the Loop induction variable must 390fe6060f1SDimitry Andric // start at zero and increment with a step size of one. 391fe6060f1SDimitry Andric if (!L->isCanonical(*SE)) { 392fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Loop is not canonical\n"); 393fe6060f1SDimitry Andric return false; 394fe6060f1SDimitry Andric } 395fe6060f1SDimitry Andric 396e8d8bef9SDimitry Andric // There must be exactly one exiting block, and it must be the same at the 397e8d8bef9SDimitry Andric // latch. 398e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 399e8d8bef9SDimitry Andric if (L->getExitingBlock() != Latch) { 400e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n"); 401e8d8bef9SDimitry Andric return false; 402e8d8bef9SDimitry Andric } 403e8d8bef9SDimitry Andric 404e8d8bef9SDimitry Andric // Find the induction PHI. If there is no induction PHI, we can't do the 405e8d8bef9SDimitry Andric // transformation. TODO: could other variables trigger this? Do we have to 406e8d8bef9SDimitry Andric // search for the best one? 407fe6060f1SDimitry Andric InductionPHI = L->getInductionVariable(*SE); 408e8d8bef9SDimitry Andric if (!InductionPHI) { 409e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find induction PHI\n"); 410e8d8bef9SDimitry Andric return false; 411e8d8bef9SDimitry Andric } 412fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump()); 413e8d8bef9SDimitry Andric 414fe6060f1SDimitry Andric bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0)); 415e8d8bef9SDimitry Andric auto IsValidPredicate = [&](ICmpInst::Predicate Pred) { 416e8d8bef9SDimitry Andric if (ContinueOnTrue) 417e8d8bef9SDimitry Andric return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT; 418e8d8bef9SDimitry Andric else 419e8d8bef9SDimitry Andric return Pred == CmpInst::ICMP_EQ; 420e8d8bef9SDimitry Andric }; 421e8d8bef9SDimitry Andric 422fe6060f1SDimitry Andric // Find Compare and make sure it is valid. getLatchCmpInst checks that the 423fe6060f1SDimitry Andric // back branch of the latch is conditional. 424fe6060f1SDimitry Andric ICmpInst *Compare = L->getLatchCmpInst(); 425e8d8bef9SDimitry Andric if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) || 426e8d8bef9SDimitry Andric Compare->hasNUsesOrMore(2)) { 427e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid comparison\n"); 428e8d8bef9SDimitry Andric return false; 429e8d8bef9SDimitry Andric } 430fe6060f1SDimitry Andric BackBranch = cast<BranchInst>(Latch->getTerminator()); 431fe6060f1SDimitry Andric IterationInstructions.insert(BackBranch); 432fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump()); 433e8d8bef9SDimitry Andric IterationInstructions.insert(Compare); 434e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump()); 435e8d8bef9SDimitry Andric 436fe6060f1SDimitry Andric // Find increment and trip count. 437fe6060f1SDimitry Andric // There are exactly 2 incoming values to the induction phi; one from the 438fe6060f1SDimitry Andric // pre-header and one from the latch. The incoming latch value is the 439fe6060f1SDimitry Andric // increment variable. 440fe6060f1SDimitry Andric Increment = 44181ad6265SDimitry Andric cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch)); 442*bdd1243dSDimitry Andric if ((Compare->getOperand(0) != Increment || !Increment->hasNUses(2)) && 443*bdd1243dSDimitry Andric !Increment->hasNUses(1)) { 444fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid increment\n"); 445e8d8bef9SDimitry Andric return false; 446e8d8bef9SDimitry Andric } 447fe6060f1SDimitry Andric // The trip count is the RHS of the compare. If this doesn't match the trip 448349cc55cSDimitry Andric // count computed by SCEV then this is because the trip count variable 449349cc55cSDimitry Andric // has been widened so the types don't match, or because it is a constant and 450349cc55cSDimitry Andric // another transformation has changed the compare (e.g. icmp ult %inc, 451349cc55cSDimitry Andric // tripcount -> icmp ult %j, tripcount-1), or both. 452349cc55cSDimitry Andric Value *RHS = Compare->getOperand(1); 45304eeddc0SDimitry Andric 45404eeddc0SDimitry Andric return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount, 45504eeddc0SDimitry Andric Increment, BackBranch, SE, IsWidened); 456e8d8bef9SDimitry Andric } 457e8d8bef9SDimitry Andric 458fe6060f1SDimitry Andric static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) { 459e8d8bef9SDimitry Andric // All PHIs in the inner and outer headers must either be: 460e8d8bef9SDimitry Andric // - The induction PHI, which we are going to rewrite as one induction in 461e8d8bef9SDimitry Andric // the new loop. This is already checked by findLoopComponents. 462e8d8bef9SDimitry Andric // - An outer header PHI with all incoming values from outside the loop. 463e8d8bef9SDimitry Andric // LoopSimplify guarantees we have a pre-header, so we don't need to 464e8d8bef9SDimitry Andric // worry about that here. 465e8d8bef9SDimitry Andric // - Pairs of PHIs in the inner and outer headers, which implement a 466e8d8bef9SDimitry Andric // loop-carried dependency that will still be valid in the new loop. To 467e8d8bef9SDimitry Andric // be valid, this variable must be modified only in the inner loop. 468e8d8bef9SDimitry Andric 469e8d8bef9SDimitry Andric // The set of PHI nodes in the outer loop header that we know will still be 470e8d8bef9SDimitry Andric // valid after the transformation. These will not need to be modified (with 471e8d8bef9SDimitry Andric // the exception of the induction variable), but we do need to check that 472e8d8bef9SDimitry Andric // there are no unsafe PHI nodes. 473e8d8bef9SDimitry Andric SmallPtrSet<PHINode *, 4> SafeOuterPHIs; 474e8d8bef9SDimitry Andric SafeOuterPHIs.insert(FI.OuterInductionPHI); 475e8d8bef9SDimitry Andric 476e8d8bef9SDimitry Andric // Check that all PHI nodes in the inner loop header match one of the valid 477e8d8bef9SDimitry Andric // patterns. 478e8d8bef9SDimitry Andric for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) { 479e8d8bef9SDimitry Andric // The induction PHIs break these rules, and that's OK because we treat 480e8d8bef9SDimitry Andric // them specially when doing the transformation. 481e8d8bef9SDimitry Andric if (&InnerPHI == FI.InnerInductionPHI) 482e8d8bef9SDimitry Andric continue; 483349cc55cSDimitry Andric if (FI.isNarrowInductionPhi(&InnerPHI)) 484349cc55cSDimitry Andric continue; 485e8d8bef9SDimitry Andric 486e8d8bef9SDimitry Andric // Each inner loop PHI node must have two incoming values/blocks - one 487e8d8bef9SDimitry Andric // from the pre-header, and one from the latch. 488e8d8bef9SDimitry Andric assert(InnerPHI.getNumIncomingValues() == 2); 489e8d8bef9SDimitry Andric Value *PreHeaderValue = 490e8d8bef9SDimitry Andric InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader()); 491e8d8bef9SDimitry Andric Value *LatchValue = 492e8d8bef9SDimitry Andric InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch()); 493e8d8bef9SDimitry Andric 494e8d8bef9SDimitry Andric // The incoming value from the outer loop must be the PHI node in the 495e8d8bef9SDimitry Andric // outer loop header, with no modifications made in the top of the outer 496e8d8bef9SDimitry Andric // loop. 497e8d8bef9SDimitry Andric PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue); 498e8d8bef9SDimitry Andric if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) { 499e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n"); 500e8d8bef9SDimitry Andric return false; 501e8d8bef9SDimitry Andric } 502e8d8bef9SDimitry Andric 503e8d8bef9SDimitry Andric // The other incoming value must come from the inner loop, without any 504e8d8bef9SDimitry Andric // modifications in the tail end of the outer loop. We are in LCSSA form, 505e8d8bef9SDimitry Andric // so this will actually be a PHI in the inner loop's exit block, which 506e8d8bef9SDimitry Andric // only uses values from inside the inner loop. 507e8d8bef9SDimitry Andric PHINode *LCSSAPHI = dyn_cast<PHINode>( 508e8d8bef9SDimitry Andric OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch())); 509e8d8bef9SDimitry Andric if (!LCSSAPHI) { 510e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n"); 511e8d8bef9SDimitry Andric return false; 512e8d8bef9SDimitry Andric } 513e8d8bef9SDimitry Andric 514e8d8bef9SDimitry Andric // The value used by the LCSSA PHI must be the same one that the inner 515e8d8bef9SDimitry Andric // loop's PHI uses. 516e8d8bef9SDimitry Andric if (LCSSAPHI->hasConstantValue() != LatchValue) { 517e8d8bef9SDimitry Andric LLVM_DEBUG( 518e8d8bef9SDimitry Andric dbgs() << "LCSSA PHI incoming value does not match latch value\n"); 519e8d8bef9SDimitry Andric return false; 520e8d8bef9SDimitry Andric } 521e8d8bef9SDimitry Andric 522e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "PHI pair is safe:\n"); 523e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump()); 524e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump()); 525e8d8bef9SDimitry Andric SafeOuterPHIs.insert(OuterPHI); 526e8d8bef9SDimitry Andric FI.InnerPHIsToTransform.insert(&InnerPHI); 527e8d8bef9SDimitry Andric } 528e8d8bef9SDimitry Andric 529e8d8bef9SDimitry Andric for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) { 530349cc55cSDimitry Andric if (FI.isNarrowInductionPhi(&OuterPHI)) 531349cc55cSDimitry Andric continue; 532e8d8bef9SDimitry Andric if (!SafeOuterPHIs.count(&OuterPHI)) { 533e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump()); 534e8d8bef9SDimitry Andric return false; 535e8d8bef9SDimitry Andric } 536e8d8bef9SDimitry Andric } 537e8d8bef9SDimitry Andric 538e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkPHIs: OK\n"); 539e8d8bef9SDimitry Andric return true; 540e8d8bef9SDimitry Andric } 541e8d8bef9SDimitry Andric 542e8d8bef9SDimitry Andric static bool 543fe6060f1SDimitry Andric checkOuterLoopInsts(FlattenInfo &FI, 544e8d8bef9SDimitry Andric SmallPtrSetImpl<Instruction *> &IterationInstructions, 545e8d8bef9SDimitry Andric const TargetTransformInfo *TTI) { 546e8d8bef9SDimitry Andric // Check for instructions in the outer but not inner loop. If any of these 547e8d8bef9SDimitry Andric // have side-effects then this transformation is not legal, and if there is 548e8d8bef9SDimitry Andric // a significant amount of code here which can't be optimised out that it's 549e8d8bef9SDimitry Andric // not profitable (as these instructions would get executed for each 550e8d8bef9SDimitry Andric // iteration of the inner loop). 551fe6060f1SDimitry Andric InstructionCost RepeatedInstrCost = 0; 552e8d8bef9SDimitry Andric for (auto *B : FI.OuterLoop->getBlocks()) { 553e8d8bef9SDimitry Andric if (FI.InnerLoop->contains(B)) 554e8d8bef9SDimitry Andric continue; 555e8d8bef9SDimitry Andric 556e8d8bef9SDimitry Andric for (auto &I : *B) { 557e8d8bef9SDimitry Andric if (!isa<PHINode>(&I) && !I.isTerminator() && 558e8d8bef9SDimitry Andric !isSafeToSpeculativelyExecute(&I)) { 559e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have " 560e8d8bef9SDimitry Andric "side effects: "; 561e8d8bef9SDimitry Andric I.dump()); 562e8d8bef9SDimitry Andric return false; 563e8d8bef9SDimitry Andric } 564e8d8bef9SDimitry Andric // The execution count of the outer loop's iteration instructions 565e8d8bef9SDimitry Andric // (increment, compare and branch) will be increased, but the 566e8d8bef9SDimitry Andric // equivalent instructions will be removed from the inner loop, so 567e8d8bef9SDimitry Andric // they make a net difference of zero. 568e8d8bef9SDimitry Andric if (IterationInstructions.count(&I)) 569e8d8bef9SDimitry Andric continue; 570*bdd1243dSDimitry Andric // The unconditional branch to the inner loop's header will turn into 571e8d8bef9SDimitry Andric // a fall-through, so adds no cost. 572e8d8bef9SDimitry Andric BranchInst *Br = dyn_cast<BranchInst>(&I); 573e8d8bef9SDimitry Andric if (Br && Br->isUnconditional() && 574e8d8bef9SDimitry Andric Br->getSuccessor(0) == FI.InnerLoop->getHeader()) 575e8d8bef9SDimitry Andric continue; 576e8d8bef9SDimitry Andric // Multiplies of the outer iteration variable and inner iteration 577e8d8bef9SDimitry Andric // count will be optimised out. 578e8d8bef9SDimitry Andric if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI), 579fe6060f1SDimitry Andric m_Specific(FI.InnerTripCount)))) 580e8d8bef9SDimitry Andric continue; 581fe6060f1SDimitry Andric InstructionCost Cost = 582*bdd1243dSDimitry Andric TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 583e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump()); 584e8d8bef9SDimitry Andric RepeatedInstrCost += Cost; 585e8d8bef9SDimitry Andric } 586e8d8bef9SDimitry Andric } 587e8d8bef9SDimitry Andric 588e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: " 589e8d8bef9SDimitry Andric << RepeatedInstrCost << "\n"); 590e8d8bef9SDimitry Andric // Bail out if flattening the loops would cause instructions in the outer 591e8d8bef9SDimitry Andric // loop but not in the inner loop to be executed extra times. 592e8d8bef9SDimitry Andric if (RepeatedInstrCost > RepeatedInstructionThreshold) { 593e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n"); 594e8d8bef9SDimitry Andric return false; 595e8d8bef9SDimitry Andric } 596e8d8bef9SDimitry Andric 597e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n"); 598e8d8bef9SDimitry Andric return true; 599e8d8bef9SDimitry Andric } 600e8d8bef9SDimitry Andric 60104eeddc0SDimitry Andric 60204eeddc0SDimitry Andric 603e8d8bef9SDimitry Andric // We require all uses of both induction variables to match this pattern: 604e8d8bef9SDimitry Andric // 605fe6060f1SDimitry Andric // (OuterPHI * InnerTripCount) + InnerPHI 606e8d8bef9SDimitry Andric // 607e8d8bef9SDimitry Andric // Any uses of the induction variables not matching that pattern would 608e8d8bef9SDimitry Andric // require a div/mod to reconstruct in the flattened loop, so the 609e8d8bef9SDimitry Andric // transformation wouldn't be profitable. 61004eeddc0SDimitry Andric static bool checkIVUsers(FlattenInfo &FI) { 611e8d8bef9SDimitry Andric // Check that all uses of the inner loop's induction variable match the 612e8d8bef9SDimitry Andric // expected pattern, recording the uses of the outer IV. 613e8d8bef9SDimitry Andric SmallPtrSet<Value *, 4> ValidOuterPHIUses; 61404eeddc0SDimitry Andric if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses)) 615e8d8bef9SDimitry Andric return false; 616e8d8bef9SDimitry Andric 617e8d8bef9SDimitry Andric // Check that there are no uses of the outer IV other than the ones found 618e8d8bef9SDimitry Andric // as part of the pattern above. 61904eeddc0SDimitry Andric if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses)) 620e8d8bef9SDimitry Andric return false; 621e8d8bef9SDimitry Andric 622e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n"; 623e8d8bef9SDimitry Andric dbgs() << "Found " << FI.LinearIVUses.size() 624e8d8bef9SDimitry Andric << " value(s) that can be replaced:\n"; 625e8d8bef9SDimitry Andric for (Value *V : FI.LinearIVUses) { 626e8d8bef9SDimitry Andric dbgs() << " "; 627e8d8bef9SDimitry Andric V->dump(); 628e8d8bef9SDimitry Andric }); 629e8d8bef9SDimitry Andric return true; 630e8d8bef9SDimitry Andric } 631e8d8bef9SDimitry Andric 632e8d8bef9SDimitry Andric // Return an OverflowResult dependant on if overflow of the multiplication of 633fe6060f1SDimitry Andric // InnerTripCount and OuterTripCount can be assumed not to happen. 634fe6060f1SDimitry Andric static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, 635fe6060f1SDimitry Andric AssumptionCache *AC) { 636e8d8bef9SDimitry Andric Function *F = FI.OuterLoop->getHeader()->getParent(); 637e8d8bef9SDimitry Andric const DataLayout &DL = F->getParent()->getDataLayout(); 638e8d8bef9SDimitry Andric 639e8d8bef9SDimitry Andric // For debugging/testing. 640e8d8bef9SDimitry Andric if (AssumeNoOverflow) 641e8d8bef9SDimitry Andric return OverflowResult::NeverOverflows; 642e8d8bef9SDimitry Andric 643e8d8bef9SDimitry Andric // Check if the multiply could not overflow due to known ranges of the 644e8d8bef9SDimitry Andric // input values. 645e8d8bef9SDimitry Andric OverflowResult OR = computeOverflowForUnsignedMul( 646fe6060f1SDimitry Andric FI.InnerTripCount, FI.OuterTripCount, DL, AC, 647e8d8bef9SDimitry Andric FI.OuterLoop->getLoopPreheader()->getTerminator(), DT); 648e8d8bef9SDimitry Andric if (OR != OverflowResult::MayOverflow) 649e8d8bef9SDimitry Andric return OR; 650e8d8bef9SDimitry Andric 651e8d8bef9SDimitry Andric for (Value *V : FI.LinearIVUses) { 652e8d8bef9SDimitry Andric for (Value *U : V->users()) { 653e8d8bef9SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 654349cc55cSDimitry Andric for (Value *GEPUser : U->users()) { 65504eeddc0SDimitry Andric auto *GEPUserInst = cast<Instruction>(GEPUser); 656349cc55cSDimitry Andric if (!isa<LoadInst>(GEPUserInst) && 657349cc55cSDimitry Andric !(isa<StoreInst>(GEPUserInst) && 658349cc55cSDimitry Andric GEP == GEPUserInst->getOperand(1))) 659349cc55cSDimitry Andric continue; 660349cc55cSDimitry Andric if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst, 661349cc55cSDimitry Andric FI.InnerLoop)) 662349cc55cSDimitry Andric continue; 663349cc55cSDimitry Andric // The IV is used as the operand of a GEP which dominates the loop 664349cc55cSDimitry Andric // latch, and the IV is at least as wide as the address space of the 665349cc55cSDimitry Andric // GEP. In this case, the GEP would wrap around the address space 666349cc55cSDimitry Andric // before the IV increment wraps, which would be UB. 667e8d8bef9SDimitry Andric if (GEP->isInBounds() && 668e8d8bef9SDimitry Andric V->getType()->getIntegerBitWidth() >= 669e8d8bef9SDimitry Andric DL.getPointerTypeSizeInBits(GEP->getType())) { 670e8d8bef9SDimitry Andric LLVM_DEBUG( 671e8d8bef9SDimitry Andric dbgs() << "use of linear IV would be UB if overflow occurred: "; 672e8d8bef9SDimitry Andric GEP->dump()); 673e8d8bef9SDimitry Andric return OverflowResult::NeverOverflows; 674e8d8bef9SDimitry Andric } 675e8d8bef9SDimitry Andric } 676e8d8bef9SDimitry Andric } 677e8d8bef9SDimitry Andric } 678349cc55cSDimitry Andric } 679e8d8bef9SDimitry Andric 680e8d8bef9SDimitry Andric return OverflowResult::MayOverflow; 681e8d8bef9SDimitry Andric } 682e8d8bef9SDimitry Andric 683fe6060f1SDimitry Andric static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 684fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 685fe6060f1SDimitry Andric const TargetTransformInfo *TTI) { 686e8d8bef9SDimitry Andric SmallPtrSet<Instruction *, 8> IterationInstructions; 687fe6060f1SDimitry Andric if (!findLoopComponents(FI.InnerLoop, IterationInstructions, 688fe6060f1SDimitry Andric FI.InnerInductionPHI, FI.InnerTripCount, 689fe6060f1SDimitry Andric FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened)) 690e8d8bef9SDimitry Andric return false; 691fe6060f1SDimitry Andric if (!findLoopComponents(FI.OuterLoop, IterationInstructions, 692fe6060f1SDimitry Andric FI.OuterInductionPHI, FI.OuterTripCount, 693fe6060f1SDimitry Andric FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened)) 694e8d8bef9SDimitry Andric return false; 695e8d8bef9SDimitry Andric 696fe6060f1SDimitry Andric // Both of the loop trip count values must be invariant in the outer loop 697e8d8bef9SDimitry Andric // (non-instructions are all inherently invariant). 698fe6060f1SDimitry Andric if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) { 699fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n"); 700e8d8bef9SDimitry Andric return false; 701e8d8bef9SDimitry Andric } 702fe6060f1SDimitry Andric if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) { 703fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n"); 704e8d8bef9SDimitry Andric return false; 705e8d8bef9SDimitry Andric } 706e8d8bef9SDimitry Andric 707e8d8bef9SDimitry Andric if (!checkPHIs(FI, TTI)) 708e8d8bef9SDimitry Andric return false; 709e8d8bef9SDimitry Andric 710e8d8bef9SDimitry Andric // FIXME: it should be possible to handle different types correctly. 711e8d8bef9SDimitry Andric if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType()) 712e8d8bef9SDimitry Andric return false; 713e8d8bef9SDimitry Andric 714e8d8bef9SDimitry Andric if (!checkOuterLoopInsts(FI, IterationInstructions, TTI)) 715e8d8bef9SDimitry Andric return false; 716e8d8bef9SDimitry Andric 717e8d8bef9SDimitry Andric // Find the values in the loop that can be replaced with the linearized 718e8d8bef9SDimitry Andric // induction variable, and check that there are no other uses of the inner 719e8d8bef9SDimitry Andric // or outer induction variable. If there were, we could still do this 720e8d8bef9SDimitry Andric // transformation, but we'd have to insert a div/mod to calculate the 721e8d8bef9SDimitry Andric // original IVs, so it wouldn't be profitable. 722e8d8bef9SDimitry Andric if (!checkIVUsers(FI)) 723e8d8bef9SDimitry Andric return false; 724e8d8bef9SDimitry Andric 725e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n"); 726e8d8bef9SDimitry Andric return true; 727e8d8bef9SDimitry Andric } 728e8d8bef9SDimitry Andric 729fe6060f1SDimitry Andric static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 730fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 73104eeddc0SDimitry Andric const TargetTransformInfo *TTI, LPMUpdater *U, 73204eeddc0SDimitry Andric MemorySSAUpdater *MSSAU) { 733e8d8bef9SDimitry Andric Function *F = FI.OuterLoop->getHeader()->getParent(); 734e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n"); 735e8d8bef9SDimitry Andric { 736e8d8bef9SDimitry Andric using namespace ore; 737e8d8bef9SDimitry Andric OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(), 738e8d8bef9SDimitry Andric FI.InnerLoop->getHeader()); 739e8d8bef9SDimitry Andric OptimizationRemarkEmitter ORE(F); 740e8d8bef9SDimitry Andric Remark << "Flattened into outer loop"; 741e8d8bef9SDimitry Andric ORE.emit(Remark); 742e8d8bef9SDimitry Andric } 743e8d8bef9SDimitry Andric 744fe6060f1SDimitry Andric Value *NewTripCount = BinaryOperator::CreateMul( 745fe6060f1SDimitry Andric FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount", 746e8d8bef9SDimitry Andric FI.OuterLoop->getLoopPreheader()->getTerminator()); 747e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Created new trip count in preheader: "; 748e8d8bef9SDimitry Andric NewTripCount->dump()); 749e8d8bef9SDimitry Andric 750e8d8bef9SDimitry Andric // Fix up PHI nodes that take values from the inner loop back-edge, which 751e8d8bef9SDimitry Andric // we are about to remove. 752e8d8bef9SDimitry Andric FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 753e8d8bef9SDimitry Andric 754e8d8bef9SDimitry Andric // The old Phi will be optimised away later, but for now we can't leave 755e8d8bef9SDimitry Andric // leave it in an invalid state, so are updating them too. 756e8d8bef9SDimitry Andric for (PHINode *PHI : FI.InnerPHIsToTransform) 757e8d8bef9SDimitry Andric PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 758e8d8bef9SDimitry Andric 759e8d8bef9SDimitry Andric // Modify the trip count of the outer loop to be the product of the two 760e8d8bef9SDimitry Andric // trip counts. 761e8d8bef9SDimitry Andric cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount); 762e8d8bef9SDimitry Andric 763e8d8bef9SDimitry Andric // Replace the inner loop backedge with an unconditional branch to the exit. 764e8d8bef9SDimitry Andric BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock(); 765e8d8bef9SDimitry Andric BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock(); 766e8d8bef9SDimitry Andric InnerExitingBlock->getTerminator()->eraseFromParent(); 767e8d8bef9SDimitry Andric BranchInst::Create(InnerExitBlock, InnerExitingBlock); 76804eeddc0SDimitry Andric 76904eeddc0SDimitry Andric // Update the DomTree and MemorySSA. 770e8d8bef9SDimitry Andric DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); 77104eeddc0SDimitry Andric if (MSSAU) 77204eeddc0SDimitry Andric MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); 773e8d8bef9SDimitry Andric 774e8d8bef9SDimitry Andric // Replace all uses of the polynomial calculated from the two induction 775e8d8bef9SDimitry Andric // variables with the one new one. 776e8d8bef9SDimitry Andric IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator()); 777e8d8bef9SDimitry Andric for (Value *V : FI.LinearIVUses) { 778e8d8bef9SDimitry Andric Value *OuterValue = FI.OuterInductionPHI; 779e8d8bef9SDimitry Andric if (FI.Widened) 780e8d8bef9SDimitry Andric OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(), 781e8d8bef9SDimitry Andric "flatten.trunciv"); 782e8d8bef9SDimitry Andric 78304eeddc0SDimitry Andric LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with: "; 78404eeddc0SDimitry Andric OuterValue->dump()); 785e8d8bef9SDimitry Andric V->replaceAllUsesWith(OuterValue); 786e8d8bef9SDimitry Andric } 787e8d8bef9SDimitry Andric 788e8d8bef9SDimitry Andric // Tell LoopInfo, SCEV and the pass manager that the inner loop has been 789*bdd1243dSDimitry Andric // deleted, and invalidate any outer loop information. 790e8d8bef9SDimitry Andric SE->forgetLoop(FI.OuterLoop); 791*bdd1243dSDimitry Andric SE->forgetBlockAndLoopDispositions(); 792349cc55cSDimitry Andric if (U) 793349cc55cSDimitry Andric U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName()); 794e8d8bef9SDimitry Andric LI->erase(FI.InnerLoop); 795349cc55cSDimitry Andric 796349cc55cSDimitry Andric // Increment statistic value. 797349cc55cSDimitry Andric NumFlattened++; 798349cc55cSDimitry Andric 799e8d8bef9SDimitry Andric return true; 800e8d8bef9SDimitry Andric } 801e8d8bef9SDimitry Andric 802fe6060f1SDimitry Andric static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 803fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 804fe6060f1SDimitry Andric const TargetTransformInfo *TTI) { 805e8d8bef9SDimitry Andric if (!WidenIV) { 806e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n"); 807e8d8bef9SDimitry Andric return false; 808e8d8bef9SDimitry Andric } 809e8d8bef9SDimitry Andric 810e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Try widening the IVs\n"); 811e8d8bef9SDimitry Andric Module *M = FI.InnerLoop->getHeader()->getParent()->getParent(); 812e8d8bef9SDimitry Andric auto &DL = M->getDataLayout(); 813e8d8bef9SDimitry Andric auto *InnerType = FI.InnerInductionPHI->getType(); 814e8d8bef9SDimitry Andric auto *OuterType = FI.OuterInductionPHI->getType(); 815e8d8bef9SDimitry Andric unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits(); 816e8d8bef9SDimitry Andric auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext()); 817e8d8bef9SDimitry Andric 818e8d8bef9SDimitry Andric // If both induction types are less than the maximum legal integer width, 819e8d8bef9SDimitry Andric // promote both to the widest type available so we know calculating 820fe6060f1SDimitry Andric // (OuterTripCount * InnerTripCount) as the new trip count is safe. 821e8d8bef9SDimitry Andric if (InnerType != OuterType || 822e8d8bef9SDimitry Andric InnerType->getScalarSizeInBits() >= MaxLegalSize || 82304eeddc0SDimitry Andric MaxLegalType->getScalarSizeInBits() < 82404eeddc0SDimitry Andric InnerType->getScalarSizeInBits() * 2) { 825e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Can't widen the IV\n"); 826e8d8bef9SDimitry Andric return false; 827e8d8bef9SDimitry Andric } 828e8d8bef9SDimitry Andric 829e8d8bef9SDimitry Andric SCEVExpander Rewriter(*SE, DL, "loopflatten"); 830e8d8bef9SDimitry Andric SmallVector<WeakTrackingVH, 4> DeadInsts; 831fe6060f1SDimitry Andric unsigned ElimExt = 0; 832fe6060f1SDimitry Andric unsigned Widened = 0; 833e8d8bef9SDimitry Andric 834349cc55cSDimitry Andric auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool { 83504eeddc0SDimitry Andric PHINode *WidePhi = 83604eeddc0SDimitry Andric createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened, 83704eeddc0SDimitry Andric true /* HasGuards */, true /* UsePostIncrementRanges */); 838e8d8bef9SDimitry Andric if (!WidePhi) 839e8d8bef9SDimitry Andric return false; 840e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump()); 841fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump()); 842349cc55cSDimitry Andric Deleted = RecursivelyDeleteDeadPHINode(WideIV.NarrowIV); 843349cc55cSDimitry Andric return true; 844349cc55cSDimitry Andric }; 845349cc55cSDimitry Andric 846349cc55cSDimitry Andric bool Deleted; 847349cc55cSDimitry Andric if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted)) 848349cc55cSDimitry Andric return false; 849349cc55cSDimitry Andric // Add the narrow phi to list, so that it will be adjusted later when the 850349cc55cSDimitry Andric // the transformation is performed. 851349cc55cSDimitry Andric if (!Deleted) 852349cc55cSDimitry Andric FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI); 853349cc55cSDimitry Andric 854349cc55cSDimitry Andric if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted)) 855349cc55cSDimitry Andric return false; 856349cc55cSDimitry Andric 857fe6060f1SDimitry Andric assert(Widened && "Widened IV expected"); 858e8d8bef9SDimitry Andric FI.Widened = true; 859349cc55cSDimitry Andric 860349cc55cSDimitry Andric // Save the old/narrow induction phis, which we need to ignore in CheckPHIs. 861349cc55cSDimitry Andric FI.NarrowInnerInductionPHI = FI.InnerInductionPHI; 862349cc55cSDimitry Andric FI.NarrowOuterInductionPHI = FI.OuterInductionPHI; 863349cc55cSDimitry Andric 864349cc55cSDimitry Andric // After widening, rediscover all the loop components. 865e8d8bef9SDimitry Andric return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 866e8d8bef9SDimitry Andric } 867e8d8bef9SDimitry Andric 868fe6060f1SDimitry Andric static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 869fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 87004eeddc0SDimitry Andric const TargetTransformInfo *TTI, LPMUpdater *U, 87104eeddc0SDimitry Andric MemorySSAUpdater *MSSAU) { 872e8d8bef9SDimitry Andric LLVM_DEBUG( 873e8d8bef9SDimitry Andric dbgs() << "Loop flattening running on outer loop " 874e8d8bef9SDimitry Andric << FI.OuterLoop->getHeader()->getName() << " and inner loop " 875e8d8bef9SDimitry Andric << FI.InnerLoop->getHeader()->getName() << " in " 876e8d8bef9SDimitry Andric << FI.OuterLoop->getHeader()->getParent()->getName() << "\n"); 877e8d8bef9SDimitry Andric 878e8d8bef9SDimitry Andric if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI)) 879e8d8bef9SDimitry Andric return false; 880e8d8bef9SDimitry Andric 881e8d8bef9SDimitry Andric // Check if we can widen the induction variables to avoid overflow checks. 882349cc55cSDimitry Andric bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI); 883e8d8bef9SDimitry Andric 884349cc55cSDimitry Andric // It can happen that after widening of the IV, flattening may not be 885349cc55cSDimitry Andric // possible/happening, e.g. when it is deemed unprofitable. So bail here if 886349cc55cSDimitry Andric // that is the case. 887349cc55cSDimitry Andric // TODO: IV widening without performing the actual flattening transformation 888349cc55cSDimitry Andric // is not ideal. While this codegen change should not matter much, it is an 889349cc55cSDimitry Andric // unnecessary change which is better to avoid. It's unlikely this happens 890349cc55cSDimitry Andric // often, because if it's unprofitibale after widening, it should be 891349cc55cSDimitry Andric // unprofitabe before widening as checked in the first round of checks. But 892349cc55cSDimitry Andric // 'RepeatedInstructionThreshold' is set to only 2, which can probably be 893349cc55cSDimitry Andric // relaxed. Because this is making a code change (the IV widening, but not 894349cc55cSDimitry Andric // the flattening), we return true here. 895349cc55cSDimitry Andric if (FI.Widened && !CanFlatten) 896349cc55cSDimitry Andric return true; 897349cc55cSDimitry Andric 898349cc55cSDimitry Andric // If we have widened and can perform the transformation, do that here. 899349cc55cSDimitry Andric if (CanFlatten) 90004eeddc0SDimitry Andric return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU); 901349cc55cSDimitry Andric 902349cc55cSDimitry Andric // Otherwise, if we haven't widened the IV, check if the new iteration 903349cc55cSDimitry Andric // variable might overflow. In this case, we need to version the loop, and 904349cc55cSDimitry Andric // select the original version at runtime if the iteration space is too 905349cc55cSDimitry Andric // large. 906e8d8bef9SDimitry Andric // TODO: We currently don't version the loop. 907e8d8bef9SDimitry Andric OverflowResult OR = checkOverflow(FI, DT, AC); 908e8d8bef9SDimitry Andric if (OR == OverflowResult::AlwaysOverflowsHigh || 909e8d8bef9SDimitry Andric OR == OverflowResult::AlwaysOverflowsLow) { 910e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n"); 911e8d8bef9SDimitry Andric return false; 912e8d8bef9SDimitry Andric } else if (OR == OverflowResult::MayOverflow) { 913e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n"); 914e8d8bef9SDimitry Andric return false; 915e8d8bef9SDimitry Andric } 916e8d8bef9SDimitry Andric 917e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n"); 91804eeddc0SDimitry Andric return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU); 919e8d8bef9SDimitry Andric } 920e8d8bef9SDimitry Andric 921fe6060f1SDimitry Andric bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, 92204eeddc0SDimitry Andric AssumptionCache *AC, TargetTransformInfo *TTI, LPMUpdater *U, 92304eeddc0SDimitry Andric MemorySSAUpdater *MSSAU) { 924e8d8bef9SDimitry Andric bool Changed = false; 925fe6060f1SDimitry Andric for (Loop *InnerLoop : LN.getLoops()) { 926e8d8bef9SDimitry Andric auto *OuterLoop = InnerLoop->getParentLoop(); 927e8d8bef9SDimitry Andric if (!OuterLoop) 928e8d8bef9SDimitry Andric continue; 929fe6060f1SDimitry Andric FlattenInfo FI(OuterLoop, InnerLoop); 93004eeddc0SDimitry Andric Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU); 931e8d8bef9SDimitry Andric } 932e8d8bef9SDimitry Andric return Changed; 933e8d8bef9SDimitry Andric } 934e8d8bef9SDimitry Andric 935fe6060f1SDimitry Andric PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM, 936fe6060f1SDimitry Andric LoopStandardAnalysisResults &AR, 937fe6060f1SDimitry Andric LPMUpdater &U) { 938e8d8bef9SDimitry Andric 939fe6060f1SDimitry Andric bool Changed = false; 940fe6060f1SDimitry Andric 941*bdd1243dSDimitry Andric std::optional<MemorySSAUpdater> MSSAU; 94204eeddc0SDimitry Andric if (AR.MSSA) { 94304eeddc0SDimitry Andric MSSAU = MemorySSAUpdater(AR.MSSA); 94404eeddc0SDimitry Andric if (VerifyMemorySSA) 94504eeddc0SDimitry Andric AR.MSSA->verifyMemorySSA(); 94604eeddc0SDimitry Andric } 94704eeddc0SDimitry Andric 948fe6060f1SDimitry Andric // The loop flattening pass requires loops to be 949fe6060f1SDimitry Andric // in simplified form, and also needs LCSSA. Running 950fe6060f1SDimitry Andric // this pass will simplify all loops that contain inner loops, 951fe6060f1SDimitry Andric // regardless of whether anything ends up being flattened. 95204eeddc0SDimitry Andric Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U, 953*bdd1243dSDimitry Andric MSSAU ? &*MSSAU : nullptr); 954fe6060f1SDimitry Andric 955fe6060f1SDimitry Andric if (!Changed) 956e8d8bef9SDimitry Andric return PreservedAnalyses::all(); 957e8d8bef9SDimitry Andric 95804eeddc0SDimitry Andric if (AR.MSSA && VerifyMemorySSA) 95904eeddc0SDimitry Andric AR.MSSA->verifyMemorySSA(); 96004eeddc0SDimitry Andric 96104eeddc0SDimitry Andric auto PA = getLoopPassPreservedAnalyses(); 96204eeddc0SDimitry Andric if (AR.MSSA) 96304eeddc0SDimitry Andric PA.preserve<MemorySSAAnalysis>(); 96404eeddc0SDimitry Andric return PA; 965e8d8bef9SDimitry Andric } 966e8d8bef9SDimitry Andric 967e8d8bef9SDimitry Andric namespace { 968e8d8bef9SDimitry Andric class LoopFlattenLegacyPass : public FunctionPass { 969e8d8bef9SDimitry Andric public: 970e8d8bef9SDimitry Andric static char ID; // Pass ID, replacement for typeid 971e8d8bef9SDimitry Andric LoopFlattenLegacyPass() : FunctionPass(ID) { 972e8d8bef9SDimitry Andric initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry()); 973e8d8bef9SDimitry Andric } 974e8d8bef9SDimitry Andric 975e8d8bef9SDimitry Andric // Possibly flatten loop L into its child. 976e8d8bef9SDimitry Andric bool runOnFunction(Function &F) override; 977e8d8bef9SDimitry Andric 978e8d8bef9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 979e8d8bef9SDimitry Andric getLoopAnalysisUsage(AU); 980e8d8bef9SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>(); 981e8d8bef9SDimitry Andric AU.addPreserved<TargetTransformInfoWrapperPass>(); 982e8d8bef9SDimitry Andric AU.addRequired<AssumptionCacheTracker>(); 983e8d8bef9SDimitry Andric AU.addPreserved<AssumptionCacheTracker>(); 98404eeddc0SDimitry Andric AU.addPreserved<MemorySSAWrapperPass>(); 985e8d8bef9SDimitry Andric } 986e8d8bef9SDimitry Andric }; 987e8d8bef9SDimitry Andric } // namespace 988e8d8bef9SDimitry Andric 989e8d8bef9SDimitry Andric char LoopFlattenLegacyPass::ID = 0; 990e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 991e8d8bef9SDimitry Andric false, false) 992e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 993e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 994e8d8bef9SDimitry Andric INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 995e8d8bef9SDimitry Andric false, false) 996e8d8bef9SDimitry Andric 99704eeddc0SDimitry Andric FunctionPass *llvm::createLoopFlattenPass() { 99804eeddc0SDimitry Andric return new LoopFlattenLegacyPass(); 99904eeddc0SDimitry Andric } 1000e8d8bef9SDimitry Andric 1001e8d8bef9SDimitry Andric bool LoopFlattenLegacyPass::runOnFunction(Function &F) { 1002e8d8bef9SDimitry Andric ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1003e8d8bef9SDimitry Andric LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1004e8d8bef9SDimitry Andric auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 1005e8d8bef9SDimitry Andric DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 1006e8d8bef9SDimitry Andric auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>(); 1007e8d8bef9SDimitry Andric auto *TTI = &TTIP.getTTI(F); 1008e8d8bef9SDimitry Andric auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 100904eeddc0SDimitry Andric auto *MSSA = getAnalysisIfAvailable<MemorySSAWrapperPass>(); 101004eeddc0SDimitry Andric 1011*bdd1243dSDimitry Andric std::optional<MemorySSAUpdater> MSSAU; 101204eeddc0SDimitry Andric if (MSSA) 101304eeddc0SDimitry Andric MSSAU = MemorySSAUpdater(&MSSA->getMSSA()); 101404eeddc0SDimitry Andric 1015fe6060f1SDimitry Andric bool Changed = false; 1016fe6060f1SDimitry Andric for (Loop *L : *LI) { 1017fe6060f1SDimitry Andric auto LN = LoopNest::getLoopNest(*L, *SE); 1018*bdd1243dSDimitry Andric Changed |= 1019*bdd1243dSDimitry Andric Flatten(*LN, DT, LI, SE, AC, TTI, nullptr, MSSAU ? &*MSSAU : nullptr); 1020fe6060f1SDimitry Andric } 1021fe6060f1SDimitry Andric return Changed; 1022e8d8bef9SDimitry Andric } 1023