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: 13e8d8bef9SDimitry Andric // for (int i = 0; i < N; ++i) 14e8d8bef9SDimitry Andric // for (int j = 0; j < M; ++j) 15e8d8bef9SDimitry Andric // f(A[i*M+j]); 16e8d8bef9SDimitry Andric // into one loop: 17e8d8bef9SDimitry Andric // for (int i = 0; i < (N*M); ++i) 18e8d8bef9SDimitry Andric // f(A[i]); 19e8d8bef9SDimitry Andric // 20e8d8bef9SDimitry Andric // It can also flatten loops where the induction variables are not used in the 21e8d8bef9SDimitry Andric // loop. This is only worth doing if the induction variables are only used in an 22e8d8bef9SDimitry Andric // expression like i*M+j. If they had any other uses, we would have to insert a 23e8d8bef9SDimitry Andric // div/mod to reconstruct the original values, so this wouldn't be profitable. 24e8d8bef9SDimitry Andric // 25e8d8bef9SDimitry Andric // We also need to prove that N*M will not overflow. 26e8d8bef9SDimitry Andric // 27e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 28e8d8bef9SDimitry Andric 29e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/LoopFlatten.h" 30e8d8bef9SDimitry Andric #include "llvm/Analysis/AssumptionCache.h" 31e8d8bef9SDimitry Andric #include "llvm/Analysis/LoopInfo.h" 32e8d8bef9SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h" 33e8d8bef9SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 34e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 35e8d8bef9SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 36e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 37e8d8bef9SDimitry Andric #include "llvm/IR/Function.h" 38e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h" 39e8d8bef9SDimitry Andric #include "llvm/IR/Module.h" 40e8d8bef9SDimitry Andric #include "llvm/IR/PatternMatch.h" 41e8d8bef9SDimitry Andric #include "llvm/IR/Verifier.h" 42e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h" 43e8d8bef9SDimitry Andric #include "llvm/Pass.h" 44e8d8bef9SDimitry Andric #include "llvm/Support/Debug.h" 45e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 46e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar.h" 47e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h" 48e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 49e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 50e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h" 51e8d8bef9SDimitry Andric 52e8d8bef9SDimitry Andric #define DEBUG_TYPE "loop-flatten" 53e8d8bef9SDimitry Andric 54e8d8bef9SDimitry Andric using namespace llvm; 55e8d8bef9SDimitry Andric using namespace llvm::PatternMatch; 56e8d8bef9SDimitry Andric 57e8d8bef9SDimitry Andric static cl::opt<unsigned> RepeatedInstructionThreshold( 58e8d8bef9SDimitry Andric "loop-flatten-cost-threshold", cl::Hidden, cl::init(2), 59e8d8bef9SDimitry Andric cl::desc("Limit on the cost of instructions that can be repeated due to " 60e8d8bef9SDimitry Andric "loop flattening")); 61e8d8bef9SDimitry Andric 62e8d8bef9SDimitry Andric static cl::opt<bool> 63e8d8bef9SDimitry Andric AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, 64e8d8bef9SDimitry Andric cl::init(false), 65e8d8bef9SDimitry Andric cl::desc("Assume that the product of the two iteration " 66*fe6060f1SDimitry Andric "trip counts will never overflow")); 67e8d8bef9SDimitry Andric 68e8d8bef9SDimitry Andric static cl::opt<bool> 69e8d8bef9SDimitry Andric WidenIV("loop-flatten-widen-iv", cl::Hidden, 70e8d8bef9SDimitry Andric cl::init(true), 71e8d8bef9SDimitry Andric cl::desc("Widen the loop induction variables, if possible, so " 72e8d8bef9SDimitry Andric "overflow checks won't reject flattening")); 73e8d8bef9SDimitry Andric 74e8d8bef9SDimitry Andric struct FlattenInfo { 75e8d8bef9SDimitry Andric Loop *OuterLoop = nullptr; 76e8d8bef9SDimitry Andric Loop *InnerLoop = nullptr; 77*fe6060f1SDimitry Andric // These PHINodes correspond to loop induction variables, which are expected 78*fe6060f1SDimitry Andric // to start at zero and increment by one on each loop. 79e8d8bef9SDimitry Andric PHINode *InnerInductionPHI = nullptr; 80e8d8bef9SDimitry Andric PHINode *OuterInductionPHI = nullptr; 81*fe6060f1SDimitry Andric Value *InnerTripCount = nullptr; 82*fe6060f1SDimitry Andric Value *OuterTripCount = nullptr; 83e8d8bef9SDimitry Andric BinaryOperator *InnerIncrement = nullptr; 84e8d8bef9SDimitry Andric BinaryOperator *OuterIncrement = nullptr; 85e8d8bef9SDimitry Andric BranchInst *InnerBranch = nullptr; 86e8d8bef9SDimitry Andric BranchInst *OuterBranch = nullptr; 87e8d8bef9SDimitry Andric SmallPtrSet<Value *, 4> LinearIVUses; 88e8d8bef9SDimitry Andric SmallPtrSet<PHINode *, 4> InnerPHIsToTransform; 89e8d8bef9SDimitry Andric 90e8d8bef9SDimitry Andric // Whether this holds the flatten info before or after widening. 91e8d8bef9SDimitry Andric bool Widened = false; 92e8d8bef9SDimitry Andric 93e8d8bef9SDimitry Andric FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL) {}; 94e8d8bef9SDimitry Andric }; 95e8d8bef9SDimitry Andric 96*fe6060f1SDimitry Andric // Finds the induction variable, increment and trip count for a simple loop that 97*fe6060f1SDimitry Andric // we can flatten. 98e8d8bef9SDimitry Andric static bool findLoopComponents( 99e8d8bef9SDimitry Andric Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions, 100*fe6060f1SDimitry Andric PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment, 101*fe6060f1SDimitry Andric BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) { 102e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n"); 103e8d8bef9SDimitry Andric 104e8d8bef9SDimitry Andric if (!L->isLoopSimplifyForm()) { 105e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Loop is not in normal form\n"); 106e8d8bef9SDimitry Andric return false; 107e8d8bef9SDimitry Andric } 108e8d8bef9SDimitry Andric 109*fe6060f1SDimitry Andric // Currently, to simplify the implementation, the Loop induction variable must 110*fe6060f1SDimitry Andric // start at zero and increment with a step size of one. 111*fe6060f1SDimitry Andric if (!L->isCanonical(*SE)) { 112*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Loop is not canonical\n"); 113*fe6060f1SDimitry Andric return false; 114*fe6060f1SDimitry Andric } 115*fe6060f1SDimitry Andric 116e8d8bef9SDimitry Andric // There must be exactly one exiting block, and it must be the same at the 117e8d8bef9SDimitry Andric // latch. 118e8d8bef9SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 119e8d8bef9SDimitry Andric if (L->getExitingBlock() != Latch) { 120e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n"); 121e8d8bef9SDimitry Andric return false; 122e8d8bef9SDimitry Andric } 123e8d8bef9SDimitry Andric 124e8d8bef9SDimitry Andric // Find the induction PHI. If there is no induction PHI, we can't do the 125e8d8bef9SDimitry Andric // transformation. TODO: could other variables trigger this? Do we have to 126e8d8bef9SDimitry Andric // search for the best one? 127*fe6060f1SDimitry Andric InductionPHI = L->getInductionVariable(*SE); 128e8d8bef9SDimitry Andric if (!InductionPHI) { 129e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find induction PHI\n"); 130e8d8bef9SDimitry Andric return false; 131e8d8bef9SDimitry Andric } 132*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump()); 133e8d8bef9SDimitry Andric 134*fe6060f1SDimitry Andric bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0)); 135e8d8bef9SDimitry Andric auto IsValidPredicate = [&](ICmpInst::Predicate Pred) { 136e8d8bef9SDimitry Andric if (ContinueOnTrue) 137e8d8bef9SDimitry Andric return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT; 138e8d8bef9SDimitry Andric else 139e8d8bef9SDimitry Andric return Pred == CmpInst::ICMP_EQ; 140e8d8bef9SDimitry Andric }; 141e8d8bef9SDimitry Andric 142*fe6060f1SDimitry Andric // Find Compare and make sure it is valid. getLatchCmpInst checks that the 143*fe6060f1SDimitry Andric // back branch of the latch is conditional. 144*fe6060f1SDimitry Andric ICmpInst *Compare = L->getLatchCmpInst(); 145e8d8bef9SDimitry Andric if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) || 146e8d8bef9SDimitry Andric Compare->hasNUsesOrMore(2)) { 147e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid comparison\n"); 148e8d8bef9SDimitry Andric return false; 149e8d8bef9SDimitry Andric } 150*fe6060f1SDimitry Andric BackBranch = cast<BranchInst>(Latch->getTerminator()); 151*fe6060f1SDimitry Andric IterationInstructions.insert(BackBranch); 152*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump()); 153e8d8bef9SDimitry Andric IterationInstructions.insert(Compare); 154e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump()); 155e8d8bef9SDimitry Andric 156*fe6060f1SDimitry Andric // Find increment and trip count. 157*fe6060f1SDimitry Andric // There are exactly 2 incoming values to the induction phi; one from the 158*fe6060f1SDimitry Andric // pre-header and one from the latch. The incoming latch value is the 159*fe6060f1SDimitry Andric // increment variable. 160*fe6060f1SDimitry Andric Increment = 161*fe6060f1SDimitry Andric dyn_cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch)); 162*fe6060f1SDimitry Andric if (Increment->hasNUsesOrMore(3)) { 163*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid increment\n"); 164e8d8bef9SDimitry Andric return false; 165e8d8bef9SDimitry Andric } 166*fe6060f1SDimitry Andric // The trip count is the RHS of the compare. If this doesn't match the trip 167*fe6060f1SDimitry Andric // count computed by SCEV then this is either because the trip count variable 168*fe6060f1SDimitry Andric // has been widened (then leave the trip count as it is), or because it is a 169*fe6060f1SDimitry Andric // constant and another transformation has changed the compare, e.g. 170*fe6060f1SDimitry Andric // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, then we don't flatten 171*fe6060f1SDimitry Andric // the loop (yet). 172*fe6060f1SDimitry Andric TripCount = Compare->getOperand(1); 173*fe6060f1SDimitry Andric const SCEV *SCEVTripCount = 174*fe6060f1SDimitry Andric SE->getTripCountFromExitCount(SE->getBackedgeTakenCount(L)); 175*fe6060f1SDimitry Andric if (SE->getSCEV(TripCount) != SCEVTripCount) { 176*fe6060f1SDimitry Andric if (!IsWidened) { 177*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid trip count\n"); 178*fe6060f1SDimitry Andric return false; 179*fe6060f1SDimitry Andric } 180*fe6060f1SDimitry Andric auto TripCountInst = dyn_cast<Instruction>(TripCount); 181*fe6060f1SDimitry Andric if (!TripCountInst) { 182*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n"); 183*fe6060f1SDimitry Andric return false; 184*fe6060f1SDimitry Andric } 185*fe6060f1SDimitry Andric if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) || 186*fe6060f1SDimitry Andric SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) { 187*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n"); 188*fe6060f1SDimitry Andric return false; 189*fe6060f1SDimitry Andric } 190*fe6060f1SDimitry Andric } 191e8d8bef9SDimitry Andric IterationInstructions.insert(Increment); 192e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Found increment: "; Increment->dump()); 193*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump()); 194e8d8bef9SDimitry Andric 195e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Successfully found all loop components\n"); 196e8d8bef9SDimitry Andric return true; 197e8d8bef9SDimitry Andric } 198e8d8bef9SDimitry Andric 199*fe6060f1SDimitry Andric static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) { 200e8d8bef9SDimitry Andric // All PHIs in the inner and outer headers must either be: 201e8d8bef9SDimitry Andric // - The induction PHI, which we are going to rewrite as one induction in 202e8d8bef9SDimitry Andric // the new loop. This is already checked by findLoopComponents. 203e8d8bef9SDimitry Andric // - An outer header PHI with all incoming values from outside the loop. 204e8d8bef9SDimitry Andric // LoopSimplify guarantees we have a pre-header, so we don't need to 205e8d8bef9SDimitry Andric // worry about that here. 206e8d8bef9SDimitry Andric // - Pairs of PHIs in the inner and outer headers, which implement a 207e8d8bef9SDimitry Andric // loop-carried dependency that will still be valid in the new loop. To 208e8d8bef9SDimitry Andric // be valid, this variable must be modified only in the inner loop. 209e8d8bef9SDimitry Andric 210e8d8bef9SDimitry Andric // The set of PHI nodes in the outer loop header that we know will still be 211e8d8bef9SDimitry Andric // valid after the transformation. These will not need to be modified (with 212e8d8bef9SDimitry Andric // the exception of the induction variable), but we do need to check that 213e8d8bef9SDimitry Andric // there are no unsafe PHI nodes. 214e8d8bef9SDimitry Andric SmallPtrSet<PHINode *, 4> SafeOuterPHIs; 215e8d8bef9SDimitry Andric SafeOuterPHIs.insert(FI.OuterInductionPHI); 216e8d8bef9SDimitry Andric 217e8d8bef9SDimitry Andric // Check that all PHI nodes in the inner loop header match one of the valid 218e8d8bef9SDimitry Andric // patterns. 219e8d8bef9SDimitry Andric for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) { 220e8d8bef9SDimitry Andric // The induction PHIs break these rules, and that's OK because we treat 221e8d8bef9SDimitry Andric // them specially when doing the transformation. 222e8d8bef9SDimitry Andric if (&InnerPHI == FI.InnerInductionPHI) 223e8d8bef9SDimitry Andric continue; 224e8d8bef9SDimitry Andric 225e8d8bef9SDimitry Andric // Each inner loop PHI node must have two incoming values/blocks - one 226e8d8bef9SDimitry Andric // from the pre-header, and one from the latch. 227e8d8bef9SDimitry Andric assert(InnerPHI.getNumIncomingValues() == 2); 228e8d8bef9SDimitry Andric Value *PreHeaderValue = 229e8d8bef9SDimitry Andric InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader()); 230e8d8bef9SDimitry Andric Value *LatchValue = 231e8d8bef9SDimitry Andric InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch()); 232e8d8bef9SDimitry Andric 233e8d8bef9SDimitry Andric // The incoming value from the outer loop must be the PHI node in the 234e8d8bef9SDimitry Andric // outer loop header, with no modifications made in the top of the outer 235e8d8bef9SDimitry Andric // loop. 236e8d8bef9SDimitry Andric PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue); 237e8d8bef9SDimitry Andric if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) { 238e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n"); 239e8d8bef9SDimitry Andric return false; 240e8d8bef9SDimitry Andric } 241e8d8bef9SDimitry Andric 242e8d8bef9SDimitry Andric // The other incoming value must come from the inner loop, without any 243e8d8bef9SDimitry Andric // modifications in the tail end of the outer loop. We are in LCSSA form, 244e8d8bef9SDimitry Andric // so this will actually be a PHI in the inner loop's exit block, which 245e8d8bef9SDimitry Andric // only uses values from inside the inner loop. 246e8d8bef9SDimitry Andric PHINode *LCSSAPHI = dyn_cast<PHINode>( 247e8d8bef9SDimitry Andric OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch())); 248e8d8bef9SDimitry Andric if (!LCSSAPHI) { 249e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n"); 250e8d8bef9SDimitry Andric return false; 251e8d8bef9SDimitry Andric } 252e8d8bef9SDimitry Andric 253e8d8bef9SDimitry Andric // The value used by the LCSSA PHI must be the same one that the inner 254e8d8bef9SDimitry Andric // loop's PHI uses. 255e8d8bef9SDimitry Andric if (LCSSAPHI->hasConstantValue() != LatchValue) { 256e8d8bef9SDimitry Andric LLVM_DEBUG( 257e8d8bef9SDimitry Andric dbgs() << "LCSSA PHI incoming value does not match latch value\n"); 258e8d8bef9SDimitry Andric return false; 259e8d8bef9SDimitry Andric } 260e8d8bef9SDimitry Andric 261e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "PHI pair is safe:\n"); 262e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump()); 263e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump()); 264e8d8bef9SDimitry Andric SafeOuterPHIs.insert(OuterPHI); 265e8d8bef9SDimitry Andric FI.InnerPHIsToTransform.insert(&InnerPHI); 266e8d8bef9SDimitry Andric } 267e8d8bef9SDimitry Andric 268e8d8bef9SDimitry Andric for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) { 269e8d8bef9SDimitry Andric if (!SafeOuterPHIs.count(&OuterPHI)) { 270e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump()); 271e8d8bef9SDimitry Andric return false; 272e8d8bef9SDimitry Andric } 273e8d8bef9SDimitry Andric } 274e8d8bef9SDimitry Andric 275e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkPHIs: OK\n"); 276e8d8bef9SDimitry Andric return true; 277e8d8bef9SDimitry Andric } 278e8d8bef9SDimitry Andric 279e8d8bef9SDimitry Andric static bool 280*fe6060f1SDimitry Andric checkOuterLoopInsts(FlattenInfo &FI, 281e8d8bef9SDimitry Andric SmallPtrSetImpl<Instruction *> &IterationInstructions, 282e8d8bef9SDimitry Andric const TargetTransformInfo *TTI) { 283e8d8bef9SDimitry Andric // Check for instructions in the outer but not inner loop. If any of these 284e8d8bef9SDimitry Andric // have side-effects then this transformation is not legal, and if there is 285e8d8bef9SDimitry Andric // a significant amount of code here which can't be optimised out that it's 286e8d8bef9SDimitry Andric // not profitable (as these instructions would get executed for each 287e8d8bef9SDimitry Andric // iteration of the inner loop). 288*fe6060f1SDimitry Andric InstructionCost RepeatedInstrCost = 0; 289e8d8bef9SDimitry Andric for (auto *B : FI.OuterLoop->getBlocks()) { 290e8d8bef9SDimitry Andric if (FI.InnerLoop->contains(B)) 291e8d8bef9SDimitry Andric continue; 292e8d8bef9SDimitry Andric 293e8d8bef9SDimitry Andric for (auto &I : *B) { 294e8d8bef9SDimitry Andric if (!isa<PHINode>(&I) && !I.isTerminator() && 295e8d8bef9SDimitry Andric !isSafeToSpeculativelyExecute(&I)) { 296e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have " 297e8d8bef9SDimitry Andric "side effects: "; 298e8d8bef9SDimitry Andric I.dump()); 299e8d8bef9SDimitry Andric return false; 300e8d8bef9SDimitry Andric } 301e8d8bef9SDimitry Andric // The execution count of the outer loop's iteration instructions 302e8d8bef9SDimitry Andric // (increment, compare and branch) will be increased, but the 303e8d8bef9SDimitry Andric // equivalent instructions will be removed from the inner loop, so 304e8d8bef9SDimitry Andric // they make a net difference of zero. 305e8d8bef9SDimitry Andric if (IterationInstructions.count(&I)) 306e8d8bef9SDimitry Andric continue; 307e8d8bef9SDimitry Andric // The uncoditional branch to the inner loop's header will turn into 308e8d8bef9SDimitry Andric // a fall-through, so adds no cost. 309e8d8bef9SDimitry Andric BranchInst *Br = dyn_cast<BranchInst>(&I); 310e8d8bef9SDimitry Andric if (Br && Br->isUnconditional() && 311e8d8bef9SDimitry Andric Br->getSuccessor(0) == FI.InnerLoop->getHeader()) 312e8d8bef9SDimitry Andric continue; 313e8d8bef9SDimitry Andric // Multiplies of the outer iteration variable and inner iteration 314e8d8bef9SDimitry Andric // count will be optimised out. 315e8d8bef9SDimitry Andric if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI), 316*fe6060f1SDimitry Andric m_Specific(FI.InnerTripCount)))) 317e8d8bef9SDimitry Andric continue; 318*fe6060f1SDimitry Andric InstructionCost Cost = 319*fe6060f1SDimitry Andric TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 320e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump()); 321e8d8bef9SDimitry Andric RepeatedInstrCost += Cost; 322e8d8bef9SDimitry Andric } 323e8d8bef9SDimitry Andric } 324e8d8bef9SDimitry Andric 325e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: " 326e8d8bef9SDimitry Andric << RepeatedInstrCost << "\n"); 327e8d8bef9SDimitry Andric // Bail out if flattening the loops would cause instructions in the outer 328e8d8bef9SDimitry Andric // loop but not in the inner loop to be executed extra times. 329e8d8bef9SDimitry Andric if (RepeatedInstrCost > RepeatedInstructionThreshold) { 330e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n"); 331e8d8bef9SDimitry Andric return false; 332e8d8bef9SDimitry Andric } 333e8d8bef9SDimitry Andric 334e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n"); 335e8d8bef9SDimitry Andric return true; 336e8d8bef9SDimitry Andric } 337e8d8bef9SDimitry Andric 338*fe6060f1SDimitry Andric static bool checkIVUsers(FlattenInfo &FI) { 339e8d8bef9SDimitry Andric // We require all uses of both induction variables to match this pattern: 340e8d8bef9SDimitry Andric // 341*fe6060f1SDimitry Andric // (OuterPHI * InnerTripCount) + InnerPHI 342e8d8bef9SDimitry Andric // 343e8d8bef9SDimitry Andric // Any uses of the induction variables not matching that pattern would 344e8d8bef9SDimitry Andric // require a div/mod to reconstruct in the flattened loop, so the 345e8d8bef9SDimitry Andric // transformation wouldn't be profitable. 346e8d8bef9SDimitry Andric 347*fe6060f1SDimitry Andric Value *InnerTripCount = FI.InnerTripCount; 348e8d8bef9SDimitry Andric if (FI.Widened && 349*fe6060f1SDimitry Andric (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount))) 350*fe6060f1SDimitry Andric InnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0); 351e8d8bef9SDimitry Andric 352e8d8bef9SDimitry Andric // Check that all uses of the inner loop's induction variable match the 353e8d8bef9SDimitry Andric // expected pattern, recording the uses of the outer IV. 354e8d8bef9SDimitry Andric SmallPtrSet<Value *, 4> ValidOuterPHIUses; 355e8d8bef9SDimitry Andric for (User *U : FI.InnerInductionPHI->users()) { 356e8d8bef9SDimitry Andric if (U == FI.InnerIncrement) 357e8d8bef9SDimitry Andric continue; 358e8d8bef9SDimitry Andric 359e8d8bef9SDimitry Andric // After widening the IVs, a trunc instruction might have been introduced, so 360e8d8bef9SDimitry Andric // look through truncs. 361e8d8bef9SDimitry Andric if (isa<TruncInst>(U)) { 362e8d8bef9SDimitry Andric if (!U->hasOneUse()) 363e8d8bef9SDimitry Andric return false; 364e8d8bef9SDimitry Andric U = *U->user_begin(); 365e8d8bef9SDimitry Andric } 366e8d8bef9SDimitry Andric 367e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump()); 368e8d8bef9SDimitry Andric 369e8d8bef9SDimitry Andric Value *MatchedMul; 370e8d8bef9SDimitry Andric Value *MatchedItCount; 371e8d8bef9SDimitry Andric bool IsAdd = match(U, m_c_Add(m_Specific(FI.InnerInductionPHI), 372e8d8bef9SDimitry Andric m_Value(MatchedMul))) && 373e8d8bef9SDimitry Andric match(MatchedMul, m_c_Mul(m_Specific(FI.OuterInductionPHI), 374e8d8bef9SDimitry Andric m_Value(MatchedItCount))); 375e8d8bef9SDimitry Andric 376e8d8bef9SDimitry Andric // Matches the same pattern as above, except it also looks for truncs 377e8d8bef9SDimitry Andric // on the phi, which can be the result of widening the induction variables. 378e8d8bef9SDimitry Andric bool IsAddTrunc = match(U, m_c_Add(m_Trunc(m_Specific(FI.InnerInductionPHI)), 379e8d8bef9SDimitry Andric m_Value(MatchedMul))) && 380e8d8bef9SDimitry Andric match(MatchedMul, 381e8d8bef9SDimitry Andric m_c_Mul(m_Trunc(m_Specific(FI.OuterInductionPHI)), 382e8d8bef9SDimitry Andric m_Value(MatchedItCount))); 383e8d8bef9SDimitry Andric 384*fe6060f1SDimitry Andric if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) { 385e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 386e8d8bef9SDimitry Andric ValidOuterPHIUses.insert(MatchedMul); 387e8d8bef9SDimitry Andric FI.LinearIVUses.insert(U); 388e8d8bef9SDimitry Andric } else { 389e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 390e8d8bef9SDimitry Andric return false; 391e8d8bef9SDimitry Andric } 392e8d8bef9SDimitry Andric } 393e8d8bef9SDimitry Andric 394e8d8bef9SDimitry Andric // Check that there are no uses of the outer IV other than the ones found 395e8d8bef9SDimitry Andric // as part of the pattern above. 396e8d8bef9SDimitry Andric for (User *U : FI.OuterInductionPHI->users()) { 397e8d8bef9SDimitry Andric if (U == FI.OuterIncrement) 398e8d8bef9SDimitry Andric continue; 399e8d8bef9SDimitry Andric 400e8d8bef9SDimitry Andric auto IsValidOuterPHIUses = [&] (User *U) -> bool { 401e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump()); 402e8d8bef9SDimitry Andric if (!ValidOuterPHIUses.count(U)) { 403e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 404e8d8bef9SDimitry Andric return false; 405e8d8bef9SDimitry Andric } 406e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 407e8d8bef9SDimitry Andric return true; 408e8d8bef9SDimitry Andric }; 409e8d8bef9SDimitry Andric 410e8d8bef9SDimitry Andric if (auto *V = dyn_cast<TruncInst>(U)) { 411e8d8bef9SDimitry Andric for (auto *K : V->users()) { 412e8d8bef9SDimitry Andric if (!IsValidOuterPHIUses(K)) 413e8d8bef9SDimitry Andric return false; 414e8d8bef9SDimitry Andric } 415e8d8bef9SDimitry Andric continue; 416e8d8bef9SDimitry Andric } 417e8d8bef9SDimitry Andric 418e8d8bef9SDimitry Andric if (!IsValidOuterPHIUses(U)) 419e8d8bef9SDimitry Andric return false; 420e8d8bef9SDimitry Andric } 421e8d8bef9SDimitry Andric 422e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n"; 423e8d8bef9SDimitry Andric dbgs() << "Found " << FI.LinearIVUses.size() 424e8d8bef9SDimitry Andric << " value(s) that can be replaced:\n"; 425e8d8bef9SDimitry Andric for (Value *V : FI.LinearIVUses) { 426e8d8bef9SDimitry Andric dbgs() << " "; 427e8d8bef9SDimitry Andric V->dump(); 428e8d8bef9SDimitry Andric }); 429e8d8bef9SDimitry Andric return true; 430e8d8bef9SDimitry Andric } 431e8d8bef9SDimitry Andric 432e8d8bef9SDimitry Andric // Return an OverflowResult dependant on if overflow of the multiplication of 433*fe6060f1SDimitry Andric // InnerTripCount and OuterTripCount can be assumed not to happen. 434*fe6060f1SDimitry Andric static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, 435*fe6060f1SDimitry Andric AssumptionCache *AC) { 436e8d8bef9SDimitry Andric Function *F = FI.OuterLoop->getHeader()->getParent(); 437e8d8bef9SDimitry Andric const DataLayout &DL = F->getParent()->getDataLayout(); 438e8d8bef9SDimitry Andric 439e8d8bef9SDimitry Andric // For debugging/testing. 440e8d8bef9SDimitry Andric if (AssumeNoOverflow) 441e8d8bef9SDimitry Andric return OverflowResult::NeverOverflows; 442e8d8bef9SDimitry Andric 443e8d8bef9SDimitry Andric // Check if the multiply could not overflow due to known ranges of the 444e8d8bef9SDimitry Andric // input values. 445e8d8bef9SDimitry Andric OverflowResult OR = computeOverflowForUnsignedMul( 446*fe6060f1SDimitry Andric FI.InnerTripCount, FI.OuterTripCount, DL, AC, 447e8d8bef9SDimitry Andric FI.OuterLoop->getLoopPreheader()->getTerminator(), DT); 448e8d8bef9SDimitry Andric if (OR != OverflowResult::MayOverflow) 449e8d8bef9SDimitry Andric return OR; 450e8d8bef9SDimitry Andric 451e8d8bef9SDimitry Andric for (Value *V : FI.LinearIVUses) { 452e8d8bef9SDimitry Andric for (Value *U : V->users()) { 453e8d8bef9SDimitry Andric if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 454e8d8bef9SDimitry Andric // The IV is used as the operand of a GEP, and the IV is at least as 455e8d8bef9SDimitry Andric // wide as the address space of the GEP. In this case, the GEP would 456e8d8bef9SDimitry Andric // wrap around the address space before the IV increment wraps, which 457e8d8bef9SDimitry Andric // would be UB. 458e8d8bef9SDimitry Andric if (GEP->isInBounds() && 459e8d8bef9SDimitry Andric V->getType()->getIntegerBitWidth() >= 460e8d8bef9SDimitry Andric DL.getPointerTypeSizeInBits(GEP->getType())) { 461e8d8bef9SDimitry Andric LLVM_DEBUG( 462e8d8bef9SDimitry Andric dbgs() << "use of linear IV would be UB if overflow occurred: "; 463e8d8bef9SDimitry Andric GEP->dump()); 464e8d8bef9SDimitry Andric return OverflowResult::NeverOverflows; 465e8d8bef9SDimitry Andric } 466e8d8bef9SDimitry Andric } 467e8d8bef9SDimitry Andric } 468e8d8bef9SDimitry Andric } 469e8d8bef9SDimitry Andric 470e8d8bef9SDimitry Andric return OverflowResult::MayOverflow; 471e8d8bef9SDimitry Andric } 472e8d8bef9SDimitry Andric 473*fe6060f1SDimitry Andric static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 474*fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 475*fe6060f1SDimitry Andric const TargetTransformInfo *TTI) { 476e8d8bef9SDimitry Andric SmallPtrSet<Instruction *, 8> IterationInstructions; 477*fe6060f1SDimitry Andric if (!findLoopComponents(FI.InnerLoop, IterationInstructions, 478*fe6060f1SDimitry Andric FI.InnerInductionPHI, FI.InnerTripCount, 479*fe6060f1SDimitry Andric FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened)) 480e8d8bef9SDimitry Andric return false; 481*fe6060f1SDimitry Andric if (!findLoopComponents(FI.OuterLoop, IterationInstructions, 482*fe6060f1SDimitry Andric FI.OuterInductionPHI, FI.OuterTripCount, 483*fe6060f1SDimitry Andric FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened)) 484e8d8bef9SDimitry Andric return false; 485e8d8bef9SDimitry Andric 486*fe6060f1SDimitry Andric // Both of the loop trip count values must be invariant in the outer loop 487e8d8bef9SDimitry Andric // (non-instructions are all inherently invariant). 488*fe6060f1SDimitry Andric if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) { 489*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n"); 490e8d8bef9SDimitry Andric return false; 491e8d8bef9SDimitry Andric } 492*fe6060f1SDimitry Andric if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) { 493*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n"); 494e8d8bef9SDimitry Andric return false; 495e8d8bef9SDimitry Andric } 496e8d8bef9SDimitry Andric 497e8d8bef9SDimitry Andric if (!checkPHIs(FI, TTI)) 498e8d8bef9SDimitry Andric return false; 499e8d8bef9SDimitry Andric 500e8d8bef9SDimitry Andric // FIXME: it should be possible to handle different types correctly. 501e8d8bef9SDimitry Andric if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType()) 502e8d8bef9SDimitry Andric return false; 503e8d8bef9SDimitry Andric 504e8d8bef9SDimitry Andric if (!checkOuterLoopInsts(FI, IterationInstructions, TTI)) 505e8d8bef9SDimitry Andric return false; 506e8d8bef9SDimitry Andric 507e8d8bef9SDimitry Andric // Find the values in the loop that can be replaced with the linearized 508e8d8bef9SDimitry Andric // induction variable, and check that there are no other uses of the inner 509e8d8bef9SDimitry Andric // or outer induction variable. If there were, we could still do this 510e8d8bef9SDimitry Andric // transformation, but we'd have to insert a div/mod to calculate the 511e8d8bef9SDimitry Andric // original IVs, so it wouldn't be profitable. 512e8d8bef9SDimitry Andric if (!checkIVUsers(FI)) 513e8d8bef9SDimitry Andric return false; 514e8d8bef9SDimitry Andric 515e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n"); 516e8d8bef9SDimitry Andric return true; 517e8d8bef9SDimitry Andric } 518e8d8bef9SDimitry Andric 519*fe6060f1SDimitry Andric static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 520*fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 521e8d8bef9SDimitry Andric const TargetTransformInfo *TTI) { 522e8d8bef9SDimitry Andric Function *F = FI.OuterLoop->getHeader()->getParent(); 523e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n"); 524e8d8bef9SDimitry Andric { 525e8d8bef9SDimitry Andric using namespace ore; 526e8d8bef9SDimitry Andric OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(), 527e8d8bef9SDimitry Andric FI.InnerLoop->getHeader()); 528e8d8bef9SDimitry Andric OptimizationRemarkEmitter ORE(F); 529e8d8bef9SDimitry Andric Remark << "Flattened into outer loop"; 530e8d8bef9SDimitry Andric ORE.emit(Remark); 531e8d8bef9SDimitry Andric } 532e8d8bef9SDimitry Andric 533*fe6060f1SDimitry Andric Value *NewTripCount = BinaryOperator::CreateMul( 534*fe6060f1SDimitry Andric FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount", 535e8d8bef9SDimitry Andric FI.OuterLoop->getLoopPreheader()->getTerminator()); 536e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Created new trip count in preheader: "; 537e8d8bef9SDimitry Andric NewTripCount->dump()); 538e8d8bef9SDimitry Andric 539e8d8bef9SDimitry Andric // Fix up PHI nodes that take values from the inner loop back-edge, which 540e8d8bef9SDimitry Andric // we are about to remove. 541e8d8bef9SDimitry Andric FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 542e8d8bef9SDimitry Andric 543e8d8bef9SDimitry Andric // The old Phi will be optimised away later, but for now we can't leave 544e8d8bef9SDimitry Andric // leave it in an invalid state, so are updating them too. 545e8d8bef9SDimitry Andric for (PHINode *PHI : FI.InnerPHIsToTransform) 546e8d8bef9SDimitry Andric PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 547e8d8bef9SDimitry Andric 548e8d8bef9SDimitry Andric // Modify the trip count of the outer loop to be the product of the two 549e8d8bef9SDimitry Andric // trip counts. 550e8d8bef9SDimitry Andric cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount); 551e8d8bef9SDimitry Andric 552e8d8bef9SDimitry Andric // Replace the inner loop backedge with an unconditional branch to the exit. 553e8d8bef9SDimitry Andric BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock(); 554e8d8bef9SDimitry Andric BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock(); 555e8d8bef9SDimitry Andric InnerExitingBlock->getTerminator()->eraseFromParent(); 556e8d8bef9SDimitry Andric BranchInst::Create(InnerExitBlock, InnerExitingBlock); 557e8d8bef9SDimitry Andric DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); 558e8d8bef9SDimitry Andric 559e8d8bef9SDimitry Andric // Replace all uses of the polynomial calculated from the two induction 560e8d8bef9SDimitry Andric // variables with the one new one. 561e8d8bef9SDimitry Andric IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator()); 562e8d8bef9SDimitry Andric for (Value *V : FI.LinearIVUses) { 563e8d8bef9SDimitry Andric Value *OuterValue = FI.OuterInductionPHI; 564e8d8bef9SDimitry Andric if (FI.Widened) 565e8d8bef9SDimitry Andric OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(), 566e8d8bef9SDimitry Andric "flatten.trunciv"); 567e8d8bef9SDimitry Andric 568e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); 569e8d8bef9SDimitry Andric dbgs() << "with: "; OuterValue->dump()); 570e8d8bef9SDimitry Andric V->replaceAllUsesWith(OuterValue); 571e8d8bef9SDimitry Andric } 572e8d8bef9SDimitry Andric 573e8d8bef9SDimitry Andric // Tell LoopInfo, SCEV and the pass manager that the inner loop has been 574e8d8bef9SDimitry Andric // deleted, and any information that have about the outer loop invalidated. 575e8d8bef9SDimitry Andric SE->forgetLoop(FI.OuterLoop); 576e8d8bef9SDimitry Andric SE->forgetLoop(FI.InnerLoop); 577e8d8bef9SDimitry Andric LI->erase(FI.InnerLoop); 578e8d8bef9SDimitry Andric return true; 579e8d8bef9SDimitry Andric } 580e8d8bef9SDimitry Andric 581*fe6060f1SDimitry Andric static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 582*fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 583*fe6060f1SDimitry Andric const TargetTransformInfo *TTI) { 584e8d8bef9SDimitry Andric if (!WidenIV) { 585e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n"); 586e8d8bef9SDimitry Andric return false; 587e8d8bef9SDimitry Andric } 588e8d8bef9SDimitry Andric 589e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Try widening the IVs\n"); 590e8d8bef9SDimitry Andric Module *M = FI.InnerLoop->getHeader()->getParent()->getParent(); 591e8d8bef9SDimitry Andric auto &DL = M->getDataLayout(); 592e8d8bef9SDimitry Andric auto *InnerType = FI.InnerInductionPHI->getType(); 593e8d8bef9SDimitry Andric auto *OuterType = FI.OuterInductionPHI->getType(); 594e8d8bef9SDimitry Andric unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits(); 595e8d8bef9SDimitry Andric auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext()); 596e8d8bef9SDimitry Andric 597e8d8bef9SDimitry Andric // If both induction types are less than the maximum legal integer width, 598e8d8bef9SDimitry Andric // promote both to the widest type available so we know calculating 599*fe6060f1SDimitry Andric // (OuterTripCount * InnerTripCount) as the new trip count is safe. 600e8d8bef9SDimitry Andric if (InnerType != OuterType || 601e8d8bef9SDimitry Andric InnerType->getScalarSizeInBits() >= MaxLegalSize || 602e8d8bef9SDimitry Andric MaxLegalType->getScalarSizeInBits() < InnerType->getScalarSizeInBits() * 2) { 603e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Can't widen the IV\n"); 604e8d8bef9SDimitry Andric return false; 605e8d8bef9SDimitry Andric } 606e8d8bef9SDimitry Andric 607e8d8bef9SDimitry Andric SCEVExpander Rewriter(*SE, DL, "loopflatten"); 608e8d8bef9SDimitry Andric SmallVector<WideIVInfo, 2> WideIVs; 609e8d8bef9SDimitry Andric SmallVector<WeakTrackingVH, 4> DeadInsts; 610e8d8bef9SDimitry Andric WideIVs.push_back( {FI.InnerInductionPHI, MaxLegalType, false }); 611e8d8bef9SDimitry Andric WideIVs.push_back( {FI.OuterInductionPHI, MaxLegalType, false }); 612*fe6060f1SDimitry Andric unsigned ElimExt = 0; 613*fe6060f1SDimitry Andric unsigned Widened = 0; 614e8d8bef9SDimitry Andric 615*fe6060f1SDimitry Andric for (const auto &WideIV : WideIVs) { 616*fe6060f1SDimitry Andric PHINode *WidePhi = createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, 617e8d8bef9SDimitry Andric ElimExt, Widened, true /* HasGuards */, 618e8d8bef9SDimitry Andric true /* UsePostIncrementRanges */); 619e8d8bef9SDimitry Andric if (!WidePhi) 620e8d8bef9SDimitry Andric return false; 621e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump()); 622*fe6060f1SDimitry Andric LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump()); 623*fe6060f1SDimitry Andric RecursivelyDeleteDeadPHINode(WideIV.NarrowIV); 624e8d8bef9SDimitry Andric } 625e8d8bef9SDimitry Andric // After widening, rediscover all the loop components. 626*fe6060f1SDimitry Andric assert(Widened && "Widened IV expected"); 627e8d8bef9SDimitry Andric FI.Widened = true; 628e8d8bef9SDimitry Andric return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 629e8d8bef9SDimitry Andric } 630e8d8bef9SDimitry Andric 631*fe6060f1SDimitry Andric static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 632*fe6060f1SDimitry Andric ScalarEvolution *SE, AssumptionCache *AC, 633e8d8bef9SDimitry Andric const TargetTransformInfo *TTI) { 634e8d8bef9SDimitry Andric LLVM_DEBUG( 635e8d8bef9SDimitry Andric dbgs() << "Loop flattening running on outer loop " 636e8d8bef9SDimitry Andric << FI.OuterLoop->getHeader()->getName() << " and inner loop " 637e8d8bef9SDimitry Andric << FI.InnerLoop->getHeader()->getName() << " in " 638e8d8bef9SDimitry Andric << FI.OuterLoop->getHeader()->getParent()->getName() << "\n"); 639e8d8bef9SDimitry Andric 640e8d8bef9SDimitry Andric if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI)) 641e8d8bef9SDimitry Andric return false; 642e8d8bef9SDimitry Andric 643e8d8bef9SDimitry Andric // Check if we can widen the induction variables to avoid overflow checks. 644e8d8bef9SDimitry Andric if (CanWidenIV(FI, DT, LI, SE, AC, TTI)) 645e8d8bef9SDimitry Andric return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 646e8d8bef9SDimitry Andric 647e8d8bef9SDimitry Andric // Check if the new iteration variable might overflow. In this case, we 648e8d8bef9SDimitry Andric // need to version the loop, and select the original version at runtime if 649e8d8bef9SDimitry Andric // the iteration space is too large. 650e8d8bef9SDimitry Andric // TODO: We currently don't version the loop. 651e8d8bef9SDimitry Andric OverflowResult OR = checkOverflow(FI, DT, AC); 652e8d8bef9SDimitry Andric if (OR == OverflowResult::AlwaysOverflowsHigh || 653e8d8bef9SDimitry Andric OR == OverflowResult::AlwaysOverflowsLow) { 654e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n"); 655e8d8bef9SDimitry Andric return false; 656e8d8bef9SDimitry Andric } else if (OR == OverflowResult::MayOverflow) { 657e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n"); 658e8d8bef9SDimitry Andric return false; 659e8d8bef9SDimitry Andric } 660e8d8bef9SDimitry Andric 661e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n"); 662e8d8bef9SDimitry Andric return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 663e8d8bef9SDimitry Andric } 664e8d8bef9SDimitry Andric 665*fe6060f1SDimitry Andric bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, 666e8d8bef9SDimitry Andric AssumptionCache *AC, TargetTransformInfo *TTI) { 667e8d8bef9SDimitry Andric bool Changed = false; 668*fe6060f1SDimitry Andric for (Loop *InnerLoop : LN.getLoops()) { 669e8d8bef9SDimitry Andric auto *OuterLoop = InnerLoop->getParentLoop(); 670e8d8bef9SDimitry Andric if (!OuterLoop) 671e8d8bef9SDimitry Andric continue; 672*fe6060f1SDimitry Andric FlattenInfo FI(OuterLoop, InnerLoop); 673e8d8bef9SDimitry Andric Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI); 674e8d8bef9SDimitry Andric } 675e8d8bef9SDimitry Andric return Changed; 676e8d8bef9SDimitry Andric } 677e8d8bef9SDimitry Andric 678*fe6060f1SDimitry Andric PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM, 679*fe6060f1SDimitry Andric LoopStandardAnalysisResults &AR, 680*fe6060f1SDimitry Andric LPMUpdater &U) { 681e8d8bef9SDimitry Andric 682*fe6060f1SDimitry Andric bool Changed = false; 683*fe6060f1SDimitry Andric 684*fe6060f1SDimitry Andric // The loop flattening pass requires loops to be 685*fe6060f1SDimitry Andric // in simplified form, and also needs LCSSA. Running 686*fe6060f1SDimitry Andric // this pass will simplify all loops that contain inner loops, 687*fe6060f1SDimitry Andric // regardless of whether anything ends up being flattened. 688*fe6060f1SDimitry Andric Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI); 689*fe6060f1SDimitry Andric 690*fe6060f1SDimitry Andric if (!Changed) 691e8d8bef9SDimitry Andric return PreservedAnalyses::all(); 692e8d8bef9SDimitry Andric 693*fe6060f1SDimitry Andric return PreservedAnalyses::none(); 694e8d8bef9SDimitry Andric } 695e8d8bef9SDimitry Andric 696e8d8bef9SDimitry Andric namespace { 697e8d8bef9SDimitry Andric class LoopFlattenLegacyPass : public FunctionPass { 698e8d8bef9SDimitry Andric public: 699e8d8bef9SDimitry Andric static char ID; // Pass ID, replacement for typeid 700e8d8bef9SDimitry Andric LoopFlattenLegacyPass() : FunctionPass(ID) { 701e8d8bef9SDimitry Andric initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry()); 702e8d8bef9SDimitry Andric } 703e8d8bef9SDimitry Andric 704e8d8bef9SDimitry Andric // Possibly flatten loop L into its child. 705e8d8bef9SDimitry Andric bool runOnFunction(Function &F) override; 706e8d8bef9SDimitry Andric 707e8d8bef9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 708e8d8bef9SDimitry Andric getLoopAnalysisUsage(AU); 709e8d8bef9SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>(); 710e8d8bef9SDimitry Andric AU.addPreserved<TargetTransformInfoWrapperPass>(); 711e8d8bef9SDimitry Andric AU.addRequired<AssumptionCacheTracker>(); 712e8d8bef9SDimitry Andric AU.addPreserved<AssumptionCacheTracker>(); 713e8d8bef9SDimitry Andric } 714e8d8bef9SDimitry Andric }; 715e8d8bef9SDimitry Andric } // namespace 716e8d8bef9SDimitry Andric 717e8d8bef9SDimitry Andric char LoopFlattenLegacyPass::ID = 0; 718e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 719e8d8bef9SDimitry Andric false, false) 720e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 721e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 722e8d8bef9SDimitry Andric INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 723e8d8bef9SDimitry Andric false, false) 724e8d8bef9SDimitry Andric 725e8d8bef9SDimitry Andric FunctionPass *llvm::createLoopFlattenPass() { return new LoopFlattenLegacyPass(); } 726e8d8bef9SDimitry Andric 727e8d8bef9SDimitry Andric bool LoopFlattenLegacyPass::runOnFunction(Function &F) { 728e8d8bef9SDimitry Andric ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 729e8d8bef9SDimitry Andric LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 730e8d8bef9SDimitry Andric auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 731e8d8bef9SDimitry Andric DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 732e8d8bef9SDimitry Andric auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>(); 733e8d8bef9SDimitry Andric auto *TTI = &TTIP.getTTI(F); 734e8d8bef9SDimitry Andric auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 735*fe6060f1SDimitry Andric bool Changed = false; 736*fe6060f1SDimitry Andric for (Loop *L : *LI) { 737*fe6060f1SDimitry Andric auto LN = LoopNest::getLoopNest(*L, *SE); 738*fe6060f1SDimitry Andric Changed |= Flatten(*LN, DT, LI, SE, AC, TTI); 739*fe6060f1SDimitry Andric } 740*fe6060f1SDimitry Andric return Changed; 741e8d8bef9SDimitry Andric } 742