xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopFlatten.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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/Support/Debug.h"
69e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h"
7081ad6265SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h"
71e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
72e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
73*0fca6ea1SDimitry Andric #include "llvm/Transforms/Utils/LoopVersioning.h"
74e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
75e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/SimplifyIndVar.h"
76bdd1243dSDimitry Andric #include <optional>
77e8d8bef9SDimitry Andric 
78e8d8bef9SDimitry Andric using namespace llvm;
79e8d8bef9SDimitry Andric using namespace llvm::PatternMatch;
80e8d8bef9SDimitry Andric 
81349cc55cSDimitry Andric #define DEBUG_TYPE "loop-flatten"
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric STATISTIC(NumFlattened, "Number of loops flattened");
84349cc55cSDimitry Andric 
85e8d8bef9SDimitry Andric static cl::opt<unsigned> RepeatedInstructionThreshold(
86e8d8bef9SDimitry Andric     "loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
87e8d8bef9SDimitry Andric     cl::desc("Limit on the cost of instructions that can be repeated due to "
88e8d8bef9SDimitry Andric              "loop flattening"));
89e8d8bef9SDimitry Andric 
90e8d8bef9SDimitry Andric static cl::opt<bool>
91e8d8bef9SDimitry Andric     AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
92e8d8bef9SDimitry Andric                      cl::init(false),
93e8d8bef9SDimitry Andric                      cl::desc("Assume that the product of the two iteration "
94fe6060f1SDimitry Andric                               "trip counts will never overflow"));
95e8d8bef9SDimitry Andric 
96e8d8bef9SDimitry Andric static cl::opt<bool>
9704eeddc0SDimitry Andric     WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
98e8d8bef9SDimitry Andric             cl::desc("Widen the loop induction variables, if possible, so "
99e8d8bef9SDimitry Andric                      "overflow checks won't reject flattening"));
100e8d8bef9SDimitry Andric 
101*0fca6ea1SDimitry Andric static cl::opt<bool>
102*0fca6ea1SDimitry Andric     VersionLoops("loop-flatten-version-loops", cl::Hidden, cl::init(true),
103*0fca6ea1SDimitry Andric                  cl::desc("Version loops if flattened loop could overflow"));
104*0fca6ea1SDimitry Andric 
105bdd1243dSDimitry Andric namespace {
10604eeddc0SDimitry Andric // We require all uses of both induction variables to match this pattern:
10704eeddc0SDimitry Andric //
10804eeddc0SDimitry Andric //   (OuterPHI * InnerTripCount) + InnerPHI
10904eeddc0SDimitry Andric //
11004eeddc0SDimitry Andric // I.e., it needs to be a linear expression of the induction variables and the
11104eeddc0SDimitry Andric // inner loop trip count. We keep track of all different expressions on which
11204eeddc0SDimitry Andric // checks will be performed in this bookkeeping struct.
11304eeddc0SDimitry Andric //
114e8d8bef9SDimitry Andric struct FlattenInfo {
11504eeddc0SDimitry Andric   Loop *OuterLoop = nullptr;  // The loop pair to be flattened.
116e8d8bef9SDimitry Andric   Loop *InnerLoop = nullptr;
11704eeddc0SDimitry Andric 
11804eeddc0SDimitry Andric   PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
11904eeddc0SDimitry Andric   PHINode *OuterInductionPHI = nullptr; // induction variables, which are
12004eeddc0SDimitry Andric                                         // expected to start at zero and
12104eeddc0SDimitry Andric                                         // increment by one on each loop.
12204eeddc0SDimitry Andric 
12304eeddc0SDimitry Andric   Value *InnerTripCount = nullptr; // The product of these two tripcounts
12404eeddc0SDimitry Andric   Value *OuterTripCount = nullptr; // will be the new flattened loop
12504eeddc0SDimitry Andric                                    // tripcount. Also used to recognise a
12604eeddc0SDimitry Andric                                    // linear expression that will be replaced.
12704eeddc0SDimitry Andric 
12804eeddc0SDimitry Andric   SmallPtrSet<Value *, 4> LinearIVUses;  // Contains the linear expressions
12904eeddc0SDimitry Andric                                          // of the form i*M+j that will be
13004eeddc0SDimitry Andric                                          // replaced.
13104eeddc0SDimitry Andric 
13204eeddc0SDimitry Andric   BinaryOperator *InnerIncrement = nullptr;  // Uses of induction variables in
13304eeddc0SDimitry Andric   BinaryOperator *OuterIncrement = nullptr;  // loop control statements that
13404eeddc0SDimitry Andric   BranchInst *InnerBranch = nullptr;         // are safe to ignore.
13504eeddc0SDimitry Andric 
13604eeddc0SDimitry Andric   BranchInst *OuterBranch = nullptr; // The instruction that needs to be
13704eeddc0SDimitry Andric                                      // updated with new tripcount.
13804eeddc0SDimitry Andric 
139e8d8bef9SDimitry Andric   SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
140e8d8bef9SDimitry Andric 
14104eeddc0SDimitry Andric   bool Widened = false; // Whether this holds the flatten info before or after
14204eeddc0SDimitry Andric                         // widening.
143e8d8bef9SDimitry Andric 
14404eeddc0SDimitry Andric   PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
14504eeddc0SDimitry Andric   PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
146bdd1243dSDimitry Andric                                               // has been applied. Used to skip
14704eeddc0SDimitry Andric                                               // checks on phi nodes.
148349cc55cSDimitry Andric 
149*0fca6ea1SDimitry Andric   Value *NewTripCount = nullptr; // The tripcount of the flattened loop.
150*0fca6ea1SDimitry Andric 
151e8d8bef9SDimitry Andric   FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
152349cc55cSDimitry Andric 
153349cc55cSDimitry Andric   bool isNarrowInductionPhi(PHINode *Phi) {
154349cc55cSDimitry Andric     // This can't be the narrow phi if we haven't widened the IV first.
155349cc55cSDimitry Andric     if (!Widened)
156349cc55cSDimitry Andric       return false;
157349cc55cSDimitry Andric     return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
158349cc55cSDimitry Andric   }
15904eeddc0SDimitry Andric   bool isInnerLoopIncrement(User *U) {
16004eeddc0SDimitry Andric     return InnerIncrement == U;
16104eeddc0SDimitry Andric   }
16204eeddc0SDimitry Andric   bool isOuterLoopIncrement(User *U) {
16304eeddc0SDimitry Andric     return OuterIncrement == U;
16404eeddc0SDimitry Andric   }
16504eeddc0SDimitry Andric   bool isInnerLoopTest(User *U) {
16604eeddc0SDimitry Andric     return InnerBranch->getCondition() == U;
16704eeddc0SDimitry Andric   }
16804eeddc0SDimitry Andric 
16904eeddc0SDimitry Andric   bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
17004eeddc0SDimitry Andric     for (User *U : OuterInductionPHI->users()) {
17104eeddc0SDimitry Andric       if (isOuterLoopIncrement(U))
17204eeddc0SDimitry Andric         continue;
17304eeddc0SDimitry Andric 
17404eeddc0SDimitry Andric       auto IsValidOuterPHIUses = [&] (User *U) -> bool {
17504eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
17604eeddc0SDimitry Andric         if (!ValidOuterPHIUses.count(U)) {
17704eeddc0SDimitry Andric           LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
17804eeddc0SDimitry Andric           return false;
17904eeddc0SDimitry Andric         }
18004eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Use is optimisable\n");
18104eeddc0SDimitry Andric         return true;
18204eeddc0SDimitry Andric       };
18304eeddc0SDimitry Andric 
18404eeddc0SDimitry Andric       if (auto *V = dyn_cast<TruncInst>(U)) {
18504eeddc0SDimitry Andric         for (auto *K : V->users()) {
18604eeddc0SDimitry Andric           if (!IsValidOuterPHIUses(K))
18704eeddc0SDimitry Andric             return false;
18804eeddc0SDimitry Andric         }
18904eeddc0SDimitry Andric         continue;
19004eeddc0SDimitry Andric       }
19104eeddc0SDimitry Andric 
19204eeddc0SDimitry Andric       if (!IsValidOuterPHIUses(U))
19304eeddc0SDimitry Andric         return false;
19404eeddc0SDimitry Andric     }
19504eeddc0SDimitry Andric     return true;
19604eeddc0SDimitry Andric   }
19704eeddc0SDimitry Andric 
19804eeddc0SDimitry Andric   bool matchLinearIVUser(User *U, Value *InnerTripCount,
19904eeddc0SDimitry Andric                          SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
200bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Checking linear i*M+j expression for: "; U->dump());
20104eeddc0SDimitry Andric     Value *MatchedMul = nullptr;
20204eeddc0SDimitry Andric     Value *MatchedItCount = nullptr;
20304eeddc0SDimitry Andric 
20404eeddc0SDimitry Andric     bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
20504eeddc0SDimitry Andric                                   m_Value(MatchedMul))) &&
20604eeddc0SDimitry Andric                  match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
20704eeddc0SDimitry Andric                                            m_Value(MatchedItCount)));
20804eeddc0SDimitry Andric 
20904eeddc0SDimitry Andric     // Matches the same pattern as above, except it also looks for truncs
21004eeddc0SDimitry Andric     // on the phi, which can be the result of widening the induction variables.
21104eeddc0SDimitry Andric     bool IsAddTrunc =
21204eeddc0SDimitry Andric         match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
21304eeddc0SDimitry Andric                          m_Value(MatchedMul))) &&
21404eeddc0SDimitry Andric         match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
21504eeddc0SDimitry Andric                                   m_Value(MatchedItCount)));
21604eeddc0SDimitry Andric 
217297eecfbSDimitry Andric     // Matches the pattern ptr+i*M+j, with the two additions being done via GEP.
218297eecfbSDimitry Andric     bool IsGEP = match(U, m_GEP(m_GEP(m_Value(), m_Value(MatchedMul)),
219297eecfbSDimitry Andric                                 m_Specific(InnerInductionPHI))) &&
220297eecfbSDimitry Andric                  match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
221297eecfbSDimitry Andric                                            m_Value(MatchedItCount)));
222297eecfbSDimitry Andric 
22304eeddc0SDimitry Andric     if (!MatchedItCount)
22404eeddc0SDimitry Andric       return false;
22504eeddc0SDimitry Andric 
226bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Matched multiplication: "; MatchedMul->dump());
227bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Matched iteration count: "; MatchedItCount->dump());
228bdd1243dSDimitry Andric 
229bdd1243dSDimitry Andric     // The mul should not have any other uses. Widening may leave trivially dead
230bdd1243dSDimitry Andric     // uses, which can be ignored.
231bdd1243dSDimitry Andric     if (count_if(MatchedMul->users(), [](User *U) {
232bdd1243dSDimitry Andric           return !isInstructionTriviallyDead(cast<Instruction>(U));
233bdd1243dSDimitry Andric         }) > 1) {
234bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "Multiply has more than one use\n");
235bdd1243dSDimitry Andric       return false;
236bdd1243dSDimitry Andric     }
237bdd1243dSDimitry Andric 
23881ad6265SDimitry Andric     // Look through extends if the IV has been widened. Don't look through
23981ad6265SDimitry Andric     // extends if we already looked through a trunc.
240297eecfbSDimitry Andric     if (Widened && (IsAdd || IsGEP) &&
24104eeddc0SDimitry Andric         (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
24204eeddc0SDimitry Andric       assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
24304eeddc0SDimitry Andric              "Unexpected type mismatch in types after widening");
24404eeddc0SDimitry Andric       MatchedItCount = isa<SExtInst>(MatchedItCount)
24504eeddc0SDimitry Andric                            ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
24604eeddc0SDimitry Andric                            : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
24704eeddc0SDimitry Andric     }
24804eeddc0SDimitry Andric 
249bdd1243dSDimitry Andric     LLVM_DEBUG(dbgs() << "Looking for inner trip count: ";
250bdd1243dSDimitry Andric                InnerTripCount->dump());
251bdd1243dSDimitry Andric 
252297eecfbSDimitry Andric     if ((IsAdd || IsAddTrunc || IsGEP) && MatchedItCount == InnerTripCount) {
253bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "Found. This sse is optimisable\n");
25404eeddc0SDimitry Andric       ValidOuterPHIUses.insert(MatchedMul);
25504eeddc0SDimitry Andric       LinearIVUses.insert(U);
25604eeddc0SDimitry Andric       return true;
25704eeddc0SDimitry Andric     }
25804eeddc0SDimitry Andric 
25904eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
26004eeddc0SDimitry Andric     return false;
26104eeddc0SDimitry Andric   }
26204eeddc0SDimitry Andric 
26304eeddc0SDimitry Andric   bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
26404eeddc0SDimitry Andric     Value *SExtInnerTripCount = InnerTripCount;
26504eeddc0SDimitry Andric     if (Widened &&
26604eeddc0SDimitry Andric         (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
26704eeddc0SDimitry Andric       SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
26804eeddc0SDimitry Andric 
26904eeddc0SDimitry Andric     for (User *U : InnerInductionPHI->users()) {
270bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "Checking User: "; U->dump());
271bdd1243dSDimitry Andric       if (isInnerLoopIncrement(U)) {
272bdd1243dSDimitry Andric         LLVM_DEBUG(dbgs() << "Use is inner loop increment, continuing\n");
27304eeddc0SDimitry Andric         continue;
274bdd1243dSDimitry Andric       }
27504eeddc0SDimitry Andric 
27604eeddc0SDimitry Andric       // After widening the IVs, a trunc instruction might have been introduced,
27704eeddc0SDimitry Andric       // so look through truncs.
27804eeddc0SDimitry Andric       if (isa<TruncInst>(U)) {
27904eeddc0SDimitry Andric         if (!U->hasOneUse())
28004eeddc0SDimitry Andric           return false;
28104eeddc0SDimitry Andric         U = *U->user_begin();
28204eeddc0SDimitry Andric       }
28304eeddc0SDimitry Andric 
28404eeddc0SDimitry Andric       // If the use is in the compare (which is also the condition of the inner
28504eeddc0SDimitry Andric       // branch) then the compare has been altered by another transformation e.g
28604eeddc0SDimitry Andric       // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
28704eeddc0SDimitry Andric       // a constant. Ignore this use as the compare gets removed later anyway.
288bdd1243dSDimitry Andric       if (isInnerLoopTest(U)) {
289bdd1243dSDimitry Andric         LLVM_DEBUG(dbgs() << "Use is the inner loop test, continuing\n");
29004eeddc0SDimitry Andric         continue;
291bdd1243dSDimitry Andric       }
29204eeddc0SDimitry Andric 
293bdd1243dSDimitry Andric       if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses)) {
294bdd1243dSDimitry Andric         LLVM_DEBUG(dbgs() << "Not a linear IV user\n");
29504eeddc0SDimitry Andric         return false;
29604eeddc0SDimitry Andric       }
297bdd1243dSDimitry Andric       LLVM_DEBUG(dbgs() << "Linear IV users found!\n");
298bdd1243dSDimitry Andric     }
29904eeddc0SDimitry Andric     return true;
30004eeddc0SDimitry Andric   }
301e8d8bef9SDimitry Andric };
302bdd1243dSDimitry Andric } // namespace
303e8d8bef9SDimitry Andric 
304349cc55cSDimitry Andric static bool
305349cc55cSDimitry Andric setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment,
306349cc55cSDimitry Andric                   SmallPtrSetImpl<Instruction *> &IterationInstructions) {
307349cc55cSDimitry Andric   TripCount = TC;
308349cc55cSDimitry Andric   IterationInstructions.insert(Increment);
309349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
310349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
311349cc55cSDimitry Andric   LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
312349cc55cSDimitry Andric   return true;
313349cc55cSDimitry Andric }
314349cc55cSDimitry Andric 
31504eeddc0SDimitry Andric // Given the RHS of the loop latch compare instruction, verify with SCEV
31604eeddc0SDimitry Andric // that this is indeed the loop tripcount.
31704eeddc0SDimitry Andric // TODO: This used to be a straightforward check but has grown to be quite
31804eeddc0SDimitry Andric // complicated now. It is therefore worth revisiting what the additional
31904eeddc0SDimitry Andric // benefits are of this (compared to relying on canonical loops and pattern
32004eeddc0SDimitry Andric // matching).
32104eeddc0SDimitry Andric static bool verifyTripCount(Value *RHS, Loop *L,
32204eeddc0SDimitry Andric      SmallPtrSetImpl<Instruction *> &IterationInstructions,
32304eeddc0SDimitry Andric     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
32404eeddc0SDimitry Andric     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
32504eeddc0SDimitry Andric   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
32604eeddc0SDimitry Andric   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
32704eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
32804eeddc0SDimitry Andric     return false;
32904eeddc0SDimitry Andric   }
33004eeddc0SDimitry Andric 
33106c3fb27SDimitry Andric   // Evaluating in the trip count's type can not overflow here as the overflow
33206c3fb27SDimitry Andric   // checks are performed in checkOverflow, but are first tried to avoid by
33306c3fb27SDimitry Andric   // widening the IV.
33404eeddc0SDimitry Andric   const SCEV *SCEVTripCount =
33506c3fb27SDimitry Andric     SE->getTripCountFromExitCount(BackedgeTakenCount,
33606c3fb27SDimitry Andric                                   BackedgeTakenCount->getType(), L);
33704eeddc0SDimitry Andric 
33804eeddc0SDimitry Andric   const SCEV *SCEVRHS = SE->getSCEV(RHS);
33904eeddc0SDimitry Andric   if (SCEVRHS == SCEVTripCount)
34004eeddc0SDimitry Andric     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
34104eeddc0SDimitry Andric   ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
34204eeddc0SDimitry Andric   if (ConstantRHS) {
34304eeddc0SDimitry Andric     const SCEV *BackedgeTCExt = nullptr;
34404eeddc0SDimitry Andric     if (IsWidened) {
34504eeddc0SDimitry Andric       const SCEV *SCEVTripCountExt;
34604eeddc0SDimitry Andric       // Find the extended backedge taken count and extended trip count using
34704eeddc0SDimitry Andric       // SCEV. One of these should now match the RHS of the compare.
34804eeddc0SDimitry Andric       BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
34906c3fb27SDimitry Andric       SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt,
35006c3fb27SDimitry Andric                                                        RHS->getType(), L);
35104eeddc0SDimitry Andric       if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
35204eeddc0SDimitry Andric         LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
35304eeddc0SDimitry Andric         return false;
35404eeddc0SDimitry Andric       }
35504eeddc0SDimitry Andric     }
35604eeddc0SDimitry Andric     // If the RHS of the compare is equal to the backedge taken count we need
35704eeddc0SDimitry Andric     // to add one to get the trip count.
35804eeddc0SDimitry Andric     if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
359cb14a3feSDimitry Andric       Value *NewRHS = ConstantInt::get(ConstantRHS->getContext(),
360cb14a3feSDimitry Andric                                        ConstantRHS->getValue() + 1);
36104eeddc0SDimitry Andric       return setLoopComponents(NewRHS, TripCount, Increment,
36204eeddc0SDimitry Andric                                IterationInstructions);
36304eeddc0SDimitry Andric     }
36404eeddc0SDimitry Andric     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
36504eeddc0SDimitry Andric   }
36604eeddc0SDimitry Andric   // If the RHS isn't a constant then check that the reason it doesn't match
36704eeddc0SDimitry Andric   // the SCEV trip count is because the RHS is a ZExt or SExt instruction
36804eeddc0SDimitry Andric   // (and take the trip count to be the RHS).
36904eeddc0SDimitry Andric   if (!IsWidened) {
37004eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
37104eeddc0SDimitry Andric     return false;
37204eeddc0SDimitry Andric   }
37304eeddc0SDimitry Andric   auto *TripCountInst = dyn_cast<Instruction>(RHS);
37404eeddc0SDimitry Andric   if (!TripCountInst) {
37504eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
37604eeddc0SDimitry Andric     return false;
37704eeddc0SDimitry Andric   }
37804eeddc0SDimitry Andric   if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
37904eeddc0SDimitry Andric       SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
38004eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
38104eeddc0SDimitry Andric     return false;
38204eeddc0SDimitry Andric   }
38304eeddc0SDimitry Andric   return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
38404eeddc0SDimitry Andric }
38504eeddc0SDimitry Andric 
386fe6060f1SDimitry Andric // Finds the induction variable, increment and trip count for a simple loop that
387fe6060f1SDimitry Andric // we can flatten.
388e8d8bef9SDimitry Andric static bool findLoopComponents(
389e8d8bef9SDimitry Andric     Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
390fe6060f1SDimitry Andric     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
391fe6060f1SDimitry Andric     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
392e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
393e8d8bef9SDimitry Andric 
394e8d8bef9SDimitry Andric   if (!L->isLoopSimplifyForm()) {
395e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
396e8d8bef9SDimitry Andric     return false;
397e8d8bef9SDimitry Andric   }
398e8d8bef9SDimitry Andric 
399fe6060f1SDimitry Andric   // Currently, to simplify the implementation, the Loop induction variable must
400fe6060f1SDimitry Andric   // start at zero and increment with a step size of one.
401fe6060f1SDimitry Andric   if (!L->isCanonical(*SE)) {
402fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
403fe6060f1SDimitry Andric     return false;
404fe6060f1SDimitry Andric   }
405fe6060f1SDimitry Andric 
406e8d8bef9SDimitry Andric   // There must be exactly one exiting block, and it must be the same at the
407e8d8bef9SDimitry Andric   // latch.
408e8d8bef9SDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
409e8d8bef9SDimitry Andric   if (L->getExitingBlock() != Latch) {
410e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
411e8d8bef9SDimitry Andric     return false;
412e8d8bef9SDimitry Andric   }
413e8d8bef9SDimitry Andric 
414e8d8bef9SDimitry Andric   // Find the induction PHI. If there is no induction PHI, we can't do the
415e8d8bef9SDimitry Andric   // transformation. TODO: could other variables trigger this? Do we have to
416e8d8bef9SDimitry Andric   // search for the best one?
417fe6060f1SDimitry Andric   InductionPHI = L->getInductionVariable(*SE);
418e8d8bef9SDimitry Andric   if (!InductionPHI) {
419e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
420e8d8bef9SDimitry Andric     return false;
421e8d8bef9SDimitry Andric   }
422fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
423e8d8bef9SDimitry Andric 
424fe6060f1SDimitry Andric   bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
425e8d8bef9SDimitry Andric   auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
426e8d8bef9SDimitry Andric     if (ContinueOnTrue)
427e8d8bef9SDimitry Andric       return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
428e8d8bef9SDimitry Andric     else
429e8d8bef9SDimitry Andric       return Pred == CmpInst::ICMP_EQ;
430e8d8bef9SDimitry Andric   };
431e8d8bef9SDimitry Andric 
432fe6060f1SDimitry Andric   // Find Compare and make sure it is valid. getLatchCmpInst checks that the
433fe6060f1SDimitry Andric   // back branch of the latch is conditional.
434fe6060f1SDimitry Andric   ICmpInst *Compare = L->getLatchCmpInst();
435e8d8bef9SDimitry Andric   if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
436e8d8bef9SDimitry Andric       Compare->hasNUsesOrMore(2)) {
437e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
438e8d8bef9SDimitry Andric     return false;
439e8d8bef9SDimitry Andric   }
440fe6060f1SDimitry Andric   BackBranch = cast<BranchInst>(Latch->getTerminator());
441fe6060f1SDimitry Andric   IterationInstructions.insert(BackBranch);
442fe6060f1SDimitry Andric   LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
443e8d8bef9SDimitry Andric   IterationInstructions.insert(Compare);
444e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
445e8d8bef9SDimitry Andric 
446fe6060f1SDimitry Andric   // Find increment and trip count.
447fe6060f1SDimitry Andric   // There are exactly 2 incoming values to the induction phi; one from the
448fe6060f1SDimitry Andric   // pre-header and one from the latch. The incoming latch value is the
449fe6060f1SDimitry Andric   // increment variable.
450fe6060f1SDimitry Andric   Increment =
45181ad6265SDimitry Andric       cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch));
452bdd1243dSDimitry Andric   if ((Compare->getOperand(0) != Increment || !Increment->hasNUses(2)) &&
453bdd1243dSDimitry Andric       !Increment->hasNUses(1)) {
454fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
455e8d8bef9SDimitry Andric     return false;
456e8d8bef9SDimitry Andric   }
457fe6060f1SDimitry Andric   // The trip count is the RHS of the compare. If this doesn't match the trip
458349cc55cSDimitry Andric   // count computed by SCEV then this is because the trip count variable
459349cc55cSDimitry Andric   // has been widened so the types don't match, or because it is a constant and
460349cc55cSDimitry Andric   // another transformation has changed the compare (e.g. icmp ult %inc,
461349cc55cSDimitry Andric   // tripcount -> icmp ult %j, tripcount-1), or both.
462349cc55cSDimitry Andric   Value *RHS = Compare->getOperand(1);
46304eeddc0SDimitry Andric 
46404eeddc0SDimitry Andric   return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
46504eeddc0SDimitry Andric                          Increment, BackBranch, SE, IsWidened);
466e8d8bef9SDimitry Andric }
467e8d8bef9SDimitry Andric 
468fe6060f1SDimitry Andric static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
469e8d8bef9SDimitry Andric   // All PHIs in the inner and outer headers must either be:
470e8d8bef9SDimitry Andric   // - The induction PHI, which we are going to rewrite as one induction in
471e8d8bef9SDimitry Andric   //   the new loop. This is already checked by findLoopComponents.
472e8d8bef9SDimitry Andric   // - An outer header PHI with all incoming values from outside the loop.
473e8d8bef9SDimitry Andric   //   LoopSimplify guarantees we have a pre-header, so we don't need to
474e8d8bef9SDimitry Andric   //   worry about that here.
475e8d8bef9SDimitry Andric   // - Pairs of PHIs in the inner and outer headers, which implement a
476e8d8bef9SDimitry Andric   //   loop-carried dependency that will still be valid in the new loop. To
477e8d8bef9SDimitry Andric   //   be valid, this variable must be modified only in the inner loop.
478e8d8bef9SDimitry Andric 
479e8d8bef9SDimitry Andric   // The set of PHI nodes in the outer loop header that we know will still be
480e8d8bef9SDimitry Andric   // valid after the transformation. These will not need to be modified (with
481e8d8bef9SDimitry Andric   // the exception of the induction variable), but we do need to check that
482e8d8bef9SDimitry Andric   // there are no unsafe PHI nodes.
483e8d8bef9SDimitry Andric   SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
484e8d8bef9SDimitry Andric   SafeOuterPHIs.insert(FI.OuterInductionPHI);
485e8d8bef9SDimitry Andric 
486e8d8bef9SDimitry Andric   // Check that all PHI nodes in the inner loop header match one of the valid
487e8d8bef9SDimitry Andric   // patterns.
488e8d8bef9SDimitry Andric   for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
489e8d8bef9SDimitry Andric     // The induction PHIs break these rules, and that's OK because we treat
490e8d8bef9SDimitry Andric     // them specially when doing the transformation.
491e8d8bef9SDimitry Andric     if (&InnerPHI == FI.InnerInductionPHI)
492e8d8bef9SDimitry Andric       continue;
493349cc55cSDimitry Andric     if (FI.isNarrowInductionPhi(&InnerPHI))
494349cc55cSDimitry Andric       continue;
495e8d8bef9SDimitry Andric 
496e8d8bef9SDimitry Andric     // Each inner loop PHI node must have two incoming values/blocks - one
497e8d8bef9SDimitry Andric     // from the pre-header, and one from the latch.
498e8d8bef9SDimitry Andric     assert(InnerPHI.getNumIncomingValues() == 2);
499e8d8bef9SDimitry Andric     Value *PreHeaderValue =
500e8d8bef9SDimitry Andric         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
501e8d8bef9SDimitry Andric     Value *LatchValue =
502e8d8bef9SDimitry Andric         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
503e8d8bef9SDimitry Andric 
504e8d8bef9SDimitry Andric     // The incoming value from the outer loop must be the PHI node in the
505e8d8bef9SDimitry Andric     // outer loop header, with no modifications made in the top of the outer
506e8d8bef9SDimitry Andric     // loop.
507e8d8bef9SDimitry Andric     PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
508e8d8bef9SDimitry Andric     if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
509e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
510e8d8bef9SDimitry Andric       return false;
511e8d8bef9SDimitry Andric     }
512e8d8bef9SDimitry Andric 
513e8d8bef9SDimitry Andric     // The other incoming value must come from the inner loop, without any
514e8d8bef9SDimitry Andric     // modifications in the tail end of the outer loop. We are in LCSSA form,
515e8d8bef9SDimitry Andric     // so this will actually be a PHI in the inner loop's exit block, which
516e8d8bef9SDimitry Andric     // only uses values from inside the inner loop.
517e8d8bef9SDimitry Andric     PHINode *LCSSAPHI = dyn_cast<PHINode>(
518e8d8bef9SDimitry Andric         OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
519e8d8bef9SDimitry Andric     if (!LCSSAPHI) {
520e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
521e8d8bef9SDimitry Andric       return false;
522e8d8bef9SDimitry Andric     }
523e8d8bef9SDimitry Andric 
524e8d8bef9SDimitry Andric     // The value used by the LCSSA PHI must be the same one that the inner
525e8d8bef9SDimitry Andric     // loop's PHI uses.
526e8d8bef9SDimitry Andric     if (LCSSAPHI->hasConstantValue() != LatchValue) {
527e8d8bef9SDimitry Andric       LLVM_DEBUG(
528e8d8bef9SDimitry Andric           dbgs() << "LCSSA PHI incoming value does not match latch value\n");
529e8d8bef9SDimitry Andric       return false;
530e8d8bef9SDimitry Andric     }
531e8d8bef9SDimitry Andric 
532e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
533e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "  Inner: "; InnerPHI.dump());
534e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "  Outer: "; OuterPHI->dump());
535e8d8bef9SDimitry Andric     SafeOuterPHIs.insert(OuterPHI);
536e8d8bef9SDimitry Andric     FI.InnerPHIsToTransform.insert(&InnerPHI);
537e8d8bef9SDimitry Andric   }
538e8d8bef9SDimitry Andric 
539e8d8bef9SDimitry Andric   for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
540349cc55cSDimitry Andric     if (FI.isNarrowInductionPhi(&OuterPHI))
541349cc55cSDimitry Andric       continue;
542e8d8bef9SDimitry Andric     if (!SafeOuterPHIs.count(&OuterPHI)) {
543e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
544e8d8bef9SDimitry Andric       return false;
545e8d8bef9SDimitry Andric     }
546e8d8bef9SDimitry Andric   }
547e8d8bef9SDimitry Andric 
548e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
549e8d8bef9SDimitry Andric   return true;
550e8d8bef9SDimitry Andric }
551e8d8bef9SDimitry Andric 
552e8d8bef9SDimitry Andric static bool
553fe6060f1SDimitry Andric checkOuterLoopInsts(FlattenInfo &FI,
554e8d8bef9SDimitry Andric                     SmallPtrSetImpl<Instruction *> &IterationInstructions,
555e8d8bef9SDimitry Andric                     const TargetTransformInfo *TTI) {
556e8d8bef9SDimitry Andric   // Check for instructions in the outer but not inner loop. If any of these
557e8d8bef9SDimitry Andric   // have side-effects then this transformation is not legal, and if there is
558e8d8bef9SDimitry Andric   // a significant amount of code here which can't be optimised out that it's
559e8d8bef9SDimitry Andric   // not profitable (as these instructions would get executed for each
560e8d8bef9SDimitry Andric   // iteration of the inner loop).
561fe6060f1SDimitry Andric   InstructionCost RepeatedInstrCost = 0;
562e8d8bef9SDimitry Andric   for (auto *B : FI.OuterLoop->getBlocks()) {
563e8d8bef9SDimitry Andric     if (FI.InnerLoop->contains(B))
564e8d8bef9SDimitry Andric       continue;
565e8d8bef9SDimitry Andric 
566e8d8bef9SDimitry Andric     for (auto &I : *B) {
567e8d8bef9SDimitry Andric       if (!isa<PHINode>(&I) && !I.isTerminator() &&
568e8d8bef9SDimitry Andric           !isSafeToSpeculativelyExecute(&I)) {
569e8d8bef9SDimitry Andric         LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
570e8d8bef9SDimitry Andric                              "side effects: ";
571e8d8bef9SDimitry Andric                    I.dump());
572e8d8bef9SDimitry Andric         return false;
573e8d8bef9SDimitry Andric       }
574e8d8bef9SDimitry Andric       // The execution count of the outer loop's iteration instructions
575e8d8bef9SDimitry Andric       // (increment, compare and branch) will be increased, but the
576e8d8bef9SDimitry Andric       // equivalent instructions will be removed from the inner loop, so
577e8d8bef9SDimitry Andric       // they make a net difference of zero.
578e8d8bef9SDimitry Andric       if (IterationInstructions.count(&I))
579e8d8bef9SDimitry Andric         continue;
580bdd1243dSDimitry Andric       // The unconditional branch to the inner loop's header will turn into
581e8d8bef9SDimitry Andric       // a fall-through, so adds no cost.
582e8d8bef9SDimitry Andric       BranchInst *Br = dyn_cast<BranchInst>(&I);
583e8d8bef9SDimitry Andric       if (Br && Br->isUnconditional() &&
584e8d8bef9SDimitry Andric           Br->getSuccessor(0) == FI.InnerLoop->getHeader())
585e8d8bef9SDimitry Andric         continue;
586e8d8bef9SDimitry Andric       // Multiplies of the outer iteration variable and inner iteration
587e8d8bef9SDimitry Andric       // count will be optimised out.
588e8d8bef9SDimitry Andric       if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
589fe6060f1SDimitry Andric                             m_Specific(FI.InnerTripCount))))
590e8d8bef9SDimitry Andric         continue;
591fe6060f1SDimitry Andric       InstructionCost Cost =
592bdd1243dSDimitry Andric           TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
593e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
594e8d8bef9SDimitry Andric       RepeatedInstrCost += Cost;
595e8d8bef9SDimitry Andric     }
596e8d8bef9SDimitry Andric   }
597e8d8bef9SDimitry Andric 
598e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
599e8d8bef9SDimitry Andric                     << RepeatedInstrCost << "\n");
600e8d8bef9SDimitry Andric   // Bail out if flattening the loops would cause instructions in the outer
601e8d8bef9SDimitry Andric   // loop but not in the inner loop to be executed extra times.
602e8d8bef9SDimitry Andric   if (RepeatedInstrCost > RepeatedInstructionThreshold) {
603e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
604e8d8bef9SDimitry Andric     return false;
605e8d8bef9SDimitry Andric   }
606e8d8bef9SDimitry Andric 
607e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
608e8d8bef9SDimitry Andric   return true;
609e8d8bef9SDimitry Andric }
610e8d8bef9SDimitry Andric 
61104eeddc0SDimitry Andric 
61204eeddc0SDimitry Andric 
613e8d8bef9SDimitry Andric // We require all uses of both induction variables to match this pattern:
614e8d8bef9SDimitry Andric //
615fe6060f1SDimitry Andric //   (OuterPHI * InnerTripCount) + InnerPHI
616e8d8bef9SDimitry Andric //
617e8d8bef9SDimitry Andric // Any uses of the induction variables not matching that pattern would
618e8d8bef9SDimitry Andric // require a div/mod to reconstruct in the flattened loop, so the
619e8d8bef9SDimitry Andric // transformation wouldn't be profitable.
62004eeddc0SDimitry Andric static bool checkIVUsers(FlattenInfo &FI) {
621e8d8bef9SDimitry Andric   // Check that all uses of the inner loop's induction variable match the
622e8d8bef9SDimitry Andric   // expected pattern, recording the uses of the outer IV.
623e8d8bef9SDimitry Andric   SmallPtrSet<Value *, 4> ValidOuterPHIUses;
62404eeddc0SDimitry Andric   if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
625e8d8bef9SDimitry Andric     return false;
626e8d8bef9SDimitry Andric 
627e8d8bef9SDimitry Andric   // Check that there are no uses of the outer IV other than the ones found
628e8d8bef9SDimitry Andric   // as part of the pattern above.
62904eeddc0SDimitry Andric   if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
630e8d8bef9SDimitry Andric     return false;
631e8d8bef9SDimitry Andric 
632e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
633e8d8bef9SDimitry Andric              dbgs() << "Found " << FI.LinearIVUses.size()
634e8d8bef9SDimitry Andric                     << " value(s) that can be replaced:\n";
635e8d8bef9SDimitry Andric              for (Value *V : FI.LinearIVUses) {
636e8d8bef9SDimitry Andric                dbgs() << "  ";
637e8d8bef9SDimitry Andric                V->dump();
638e8d8bef9SDimitry Andric              });
639e8d8bef9SDimitry Andric   return true;
640e8d8bef9SDimitry Andric }
641e8d8bef9SDimitry Andric 
642e8d8bef9SDimitry Andric // Return an OverflowResult dependant on if overflow of the multiplication of
643fe6060f1SDimitry Andric // InnerTripCount and OuterTripCount can be assumed not to happen.
644fe6060f1SDimitry Andric static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
645fe6060f1SDimitry Andric                                     AssumptionCache *AC) {
646e8d8bef9SDimitry Andric   Function *F = FI.OuterLoop->getHeader()->getParent();
647*0fca6ea1SDimitry Andric   const DataLayout &DL = F->getDataLayout();
648e8d8bef9SDimitry Andric 
649e8d8bef9SDimitry Andric   // For debugging/testing.
650e8d8bef9SDimitry Andric   if (AssumeNoOverflow)
651e8d8bef9SDimitry Andric     return OverflowResult::NeverOverflows;
652e8d8bef9SDimitry Andric 
653e8d8bef9SDimitry Andric   // Check if the multiply could not overflow due to known ranges of the
654e8d8bef9SDimitry Andric   // input values.
655e8d8bef9SDimitry Andric   OverflowResult OR = computeOverflowForUnsignedMul(
6565f757f3fSDimitry Andric       FI.InnerTripCount, FI.OuterTripCount,
6575f757f3fSDimitry Andric       SimplifyQuery(DL, DT, AC,
6585f757f3fSDimitry Andric                     FI.OuterLoop->getLoopPreheader()->getTerminator()));
659e8d8bef9SDimitry Andric   if (OR != OverflowResult::MayOverflow)
660e8d8bef9SDimitry Andric     return OR;
661e8d8bef9SDimitry Andric 
662297eecfbSDimitry Andric   auto CheckGEP = [&](GetElementPtrInst *GEP, Value *GEPOperand) {
663297eecfbSDimitry Andric     for (Value *GEPUser : GEP->users()) {
66404eeddc0SDimitry Andric       auto *GEPUserInst = cast<Instruction>(GEPUser);
665349cc55cSDimitry Andric       if (!isa<LoadInst>(GEPUserInst) &&
666297eecfbSDimitry Andric           !(isa<StoreInst>(GEPUserInst) && GEP == GEPUserInst->getOperand(1)))
667349cc55cSDimitry Andric         continue;
668297eecfbSDimitry Andric       if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst, FI.InnerLoop))
669349cc55cSDimitry Andric         continue;
670349cc55cSDimitry Andric       // The IV is used as the operand of a GEP which dominates the loop
671349cc55cSDimitry Andric       // latch, and the IV is at least as wide as the address space of the
672349cc55cSDimitry Andric       // GEP. In this case, the GEP would wrap around the address space
673349cc55cSDimitry Andric       // before the IV increment wraps, which would be UB.
674e8d8bef9SDimitry Andric       if (GEP->isInBounds() &&
675297eecfbSDimitry Andric           GEPOperand->getType()->getIntegerBitWidth() >=
676e8d8bef9SDimitry Andric               DL.getPointerTypeSizeInBits(GEP->getType())) {
677e8d8bef9SDimitry Andric         LLVM_DEBUG(
678e8d8bef9SDimitry Andric             dbgs() << "use of linear IV would be UB if overflow occurred: ";
679e8d8bef9SDimitry Andric             GEP->dump());
680297eecfbSDimitry Andric         return true;
681297eecfbSDimitry Andric       }
682297eecfbSDimitry Andric     }
683297eecfbSDimitry Andric     return false;
684297eecfbSDimitry Andric   };
685297eecfbSDimitry Andric 
686297eecfbSDimitry Andric   // Check if any IV user is, or is used by, a GEP that would cause UB if the
687297eecfbSDimitry Andric   // multiply overflows.
688297eecfbSDimitry Andric   for (Value *V : FI.LinearIVUses) {
689297eecfbSDimitry Andric     if (auto *GEP = dyn_cast<GetElementPtrInst>(V))
690297eecfbSDimitry Andric       if (GEP->getNumIndices() == 1 && CheckGEP(GEP, GEP->getOperand(1)))
691e8d8bef9SDimitry Andric         return OverflowResult::NeverOverflows;
692297eecfbSDimitry Andric     for (Value *U : V->users())
693297eecfbSDimitry Andric       if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
694297eecfbSDimitry Andric         if (CheckGEP(GEP, V))
695297eecfbSDimitry Andric           return OverflowResult::NeverOverflows;
696349cc55cSDimitry Andric   }
697e8d8bef9SDimitry Andric 
698e8d8bef9SDimitry Andric   return OverflowResult::MayOverflow;
699e8d8bef9SDimitry Andric }
700e8d8bef9SDimitry Andric 
701fe6060f1SDimitry Andric static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
702fe6060f1SDimitry Andric                                ScalarEvolution *SE, AssumptionCache *AC,
703fe6060f1SDimitry Andric                                const TargetTransformInfo *TTI) {
704e8d8bef9SDimitry Andric   SmallPtrSet<Instruction *, 8> IterationInstructions;
705fe6060f1SDimitry Andric   if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
706fe6060f1SDimitry Andric                           FI.InnerInductionPHI, FI.InnerTripCount,
707fe6060f1SDimitry Andric                           FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
708e8d8bef9SDimitry Andric     return false;
709fe6060f1SDimitry Andric   if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
710fe6060f1SDimitry Andric                           FI.OuterInductionPHI, FI.OuterTripCount,
711fe6060f1SDimitry Andric                           FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
712e8d8bef9SDimitry Andric     return false;
713e8d8bef9SDimitry Andric 
714fe6060f1SDimitry Andric   // Both of the loop trip count values must be invariant in the outer loop
715e8d8bef9SDimitry Andric   // (non-instructions are all inherently invariant).
716fe6060f1SDimitry Andric   if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
717fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
718e8d8bef9SDimitry Andric     return false;
719e8d8bef9SDimitry Andric   }
720fe6060f1SDimitry Andric   if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
721fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
722e8d8bef9SDimitry Andric     return false;
723e8d8bef9SDimitry Andric   }
724e8d8bef9SDimitry Andric 
725e8d8bef9SDimitry Andric   if (!checkPHIs(FI, TTI))
726e8d8bef9SDimitry Andric     return false;
727e8d8bef9SDimitry Andric 
728e8d8bef9SDimitry Andric   // FIXME: it should be possible to handle different types correctly.
729e8d8bef9SDimitry Andric   if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
730e8d8bef9SDimitry Andric     return false;
731e8d8bef9SDimitry Andric 
732e8d8bef9SDimitry Andric   if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
733e8d8bef9SDimitry Andric     return false;
734e8d8bef9SDimitry Andric 
735e8d8bef9SDimitry Andric   // Find the values in the loop that can be replaced with the linearized
736e8d8bef9SDimitry Andric   // induction variable, and check that there are no other uses of the inner
737e8d8bef9SDimitry Andric   // or outer induction variable. If there were, we could still do this
738e8d8bef9SDimitry Andric   // transformation, but we'd have to insert a div/mod to calculate the
739e8d8bef9SDimitry Andric   // original IVs, so it wouldn't be profitable.
740e8d8bef9SDimitry Andric   if (!checkIVUsers(FI))
741e8d8bef9SDimitry Andric     return false;
742e8d8bef9SDimitry Andric 
743e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
744e8d8bef9SDimitry Andric   return true;
745e8d8bef9SDimitry Andric }
746e8d8bef9SDimitry Andric 
747fe6060f1SDimitry Andric static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
748fe6060f1SDimitry Andric                               ScalarEvolution *SE, AssumptionCache *AC,
74904eeddc0SDimitry Andric                               const TargetTransformInfo *TTI, LPMUpdater *U,
75004eeddc0SDimitry Andric                               MemorySSAUpdater *MSSAU) {
751e8d8bef9SDimitry Andric   Function *F = FI.OuterLoop->getHeader()->getParent();
752e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
753e8d8bef9SDimitry Andric   {
754e8d8bef9SDimitry Andric     using namespace ore;
755e8d8bef9SDimitry Andric     OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
756e8d8bef9SDimitry Andric                               FI.InnerLoop->getHeader());
757e8d8bef9SDimitry Andric     OptimizationRemarkEmitter ORE(F);
758e8d8bef9SDimitry Andric     Remark << "Flattened into outer loop";
759e8d8bef9SDimitry Andric     ORE.emit(Remark);
760e8d8bef9SDimitry Andric   }
761e8d8bef9SDimitry Andric 
762*0fca6ea1SDimitry Andric   if (!FI.NewTripCount) {
763*0fca6ea1SDimitry Andric     FI.NewTripCount = BinaryOperator::CreateMul(
764fe6060f1SDimitry Andric         FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
765*0fca6ea1SDimitry Andric         FI.OuterLoop->getLoopPreheader()->getTerminator()->getIterator());
766e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
767*0fca6ea1SDimitry Andric                FI.NewTripCount->dump());
768*0fca6ea1SDimitry Andric   }
769e8d8bef9SDimitry Andric 
770e8d8bef9SDimitry Andric   // Fix up PHI nodes that take values from the inner loop back-edge, which
771e8d8bef9SDimitry Andric   // we are about to remove.
772e8d8bef9SDimitry Andric   FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
773e8d8bef9SDimitry Andric 
774e8d8bef9SDimitry Andric   // The old Phi will be optimised away later, but for now we can't leave
775e8d8bef9SDimitry Andric   // leave it in an invalid state, so are updating them too.
776e8d8bef9SDimitry Andric   for (PHINode *PHI : FI.InnerPHIsToTransform)
777e8d8bef9SDimitry Andric     PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
778e8d8bef9SDimitry Andric 
779e8d8bef9SDimitry Andric   // Modify the trip count of the outer loop to be the product of the two
780e8d8bef9SDimitry Andric   // trip counts.
781*0fca6ea1SDimitry Andric   cast<User>(FI.OuterBranch->getCondition())->setOperand(1, FI.NewTripCount);
782e8d8bef9SDimitry Andric 
783e8d8bef9SDimitry Andric   // Replace the inner loop backedge with an unconditional branch to the exit.
784e8d8bef9SDimitry Andric   BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
785e8d8bef9SDimitry Andric   BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
786*0fca6ea1SDimitry Andric   Instruction *Term = InnerExitingBlock->getTerminator();
787*0fca6ea1SDimitry Andric   Instruction *BI = BranchInst::Create(InnerExitBlock, InnerExitingBlock);
788*0fca6ea1SDimitry Andric   BI->setDebugLoc(Term->getDebugLoc());
789*0fca6ea1SDimitry Andric   Term->eraseFromParent();
79004eeddc0SDimitry Andric 
79104eeddc0SDimitry Andric   // Update the DomTree and MemorySSA.
792e8d8bef9SDimitry Andric   DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
79304eeddc0SDimitry Andric   if (MSSAU)
79404eeddc0SDimitry Andric     MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
795e8d8bef9SDimitry Andric 
796e8d8bef9SDimitry Andric   // Replace all uses of the polynomial calculated from the two induction
797e8d8bef9SDimitry Andric   // variables with the one new one.
798e8d8bef9SDimitry Andric   IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
799e8d8bef9SDimitry Andric   for (Value *V : FI.LinearIVUses) {
800e8d8bef9SDimitry Andric     Value *OuterValue = FI.OuterInductionPHI;
801e8d8bef9SDimitry Andric     if (FI.Widened)
802e8d8bef9SDimitry Andric       OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
803e8d8bef9SDimitry Andric                                        "flatten.trunciv");
804e8d8bef9SDimitry Andric 
805297eecfbSDimitry Andric     if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
806297eecfbSDimitry Andric       // Replace the GEP with one that uses OuterValue as the offset.
807297eecfbSDimitry Andric       auto *InnerGEP = cast<GetElementPtrInst>(GEP->getOperand(0));
808297eecfbSDimitry Andric       Value *Base = InnerGEP->getOperand(0);
809297eecfbSDimitry Andric       // When the base of the GEP doesn't dominate the outer induction phi then
810297eecfbSDimitry Andric       // we need to insert the new GEP where the old GEP was.
811297eecfbSDimitry Andric       if (!DT->dominates(Base, &*Builder.GetInsertPoint()))
812297eecfbSDimitry Andric         Builder.SetInsertPoint(cast<Instruction>(V));
813*0fca6ea1SDimitry Andric       OuterValue =
814*0fca6ea1SDimitry Andric           Builder.CreateGEP(GEP->getSourceElementType(), Base, OuterValue,
815*0fca6ea1SDimitry Andric                             "flatten." + V->getName(),
816*0fca6ea1SDimitry Andric                             GEP->isInBounds() && InnerGEP->isInBounds());
817297eecfbSDimitry Andric     }
818297eecfbSDimitry Andric 
81904eeddc0SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with:      ";
82004eeddc0SDimitry Andric                OuterValue->dump());
821e8d8bef9SDimitry Andric     V->replaceAllUsesWith(OuterValue);
822e8d8bef9SDimitry Andric   }
823e8d8bef9SDimitry Andric 
824e8d8bef9SDimitry Andric   // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
825bdd1243dSDimitry Andric   // deleted, and invalidate any outer loop information.
826e8d8bef9SDimitry Andric   SE->forgetLoop(FI.OuterLoop);
827bdd1243dSDimitry Andric   SE->forgetBlockAndLoopDispositions();
828349cc55cSDimitry Andric   if (U)
829349cc55cSDimitry Andric     U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
830e8d8bef9SDimitry Andric   LI->erase(FI.InnerLoop);
831349cc55cSDimitry Andric 
832349cc55cSDimitry Andric   // Increment statistic value.
833349cc55cSDimitry Andric   NumFlattened++;
834349cc55cSDimitry Andric 
835e8d8bef9SDimitry Andric   return true;
836e8d8bef9SDimitry Andric }
837e8d8bef9SDimitry Andric 
838fe6060f1SDimitry Andric static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
839fe6060f1SDimitry Andric                        ScalarEvolution *SE, AssumptionCache *AC,
840fe6060f1SDimitry Andric                        const TargetTransformInfo *TTI) {
841e8d8bef9SDimitry Andric   if (!WidenIV) {
842e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
843e8d8bef9SDimitry Andric     return false;
844e8d8bef9SDimitry Andric   }
845e8d8bef9SDimitry Andric 
846e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
847e8d8bef9SDimitry Andric   Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
848e8d8bef9SDimitry Andric   auto &DL = M->getDataLayout();
849e8d8bef9SDimitry Andric   auto *InnerType = FI.InnerInductionPHI->getType();
850e8d8bef9SDimitry Andric   auto *OuterType = FI.OuterInductionPHI->getType();
851e8d8bef9SDimitry Andric   unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
852e8d8bef9SDimitry Andric   auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
853e8d8bef9SDimitry Andric 
854e8d8bef9SDimitry Andric   // If both induction types are less than the maximum legal integer width,
855e8d8bef9SDimitry Andric   // promote both to the widest type available so we know calculating
856fe6060f1SDimitry Andric   // (OuterTripCount * InnerTripCount) as the new trip count is safe.
857e8d8bef9SDimitry Andric   if (InnerType != OuterType ||
858e8d8bef9SDimitry Andric       InnerType->getScalarSizeInBits() >= MaxLegalSize ||
85904eeddc0SDimitry Andric       MaxLegalType->getScalarSizeInBits() <
86004eeddc0SDimitry Andric           InnerType->getScalarSizeInBits() * 2) {
861e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
862e8d8bef9SDimitry Andric     return false;
863e8d8bef9SDimitry Andric   }
864e8d8bef9SDimitry Andric 
865e8d8bef9SDimitry Andric   SCEVExpander Rewriter(*SE, DL, "loopflatten");
866e8d8bef9SDimitry Andric   SmallVector<WeakTrackingVH, 4> DeadInsts;
867fe6060f1SDimitry Andric   unsigned ElimExt = 0;
868fe6060f1SDimitry Andric   unsigned Widened = 0;
869e8d8bef9SDimitry Andric 
870349cc55cSDimitry Andric   auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
87104eeddc0SDimitry Andric     PHINode *WidePhi =
87204eeddc0SDimitry Andric         createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
87304eeddc0SDimitry Andric                      true /* HasGuards */, true /* UsePostIncrementRanges */);
874e8d8bef9SDimitry Andric     if (!WidePhi)
875e8d8bef9SDimitry Andric       return false;
876e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
877fe6060f1SDimitry Andric     LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
878349cc55cSDimitry Andric     Deleted = RecursivelyDeleteDeadPHINode(WideIV.NarrowIV);
879349cc55cSDimitry Andric     return true;
880349cc55cSDimitry Andric   };
881349cc55cSDimitry Andric 
882349cc55cSDimitry Andric   bool Deleted;
883349cc55cSDimitry Andric   if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
884349cc55cSDimitry Andric     return false;
885349cc55cSDimitry Andric   // Add the narrow phi to list, so that it will be adjusted later when the
886349cc55cSDimitry Andric   // the transformation is performed.
887349cc55cSDimitry Andric   if (!Deleted)
888349cc55cSDimitry Andric     FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
889349cc55cSDimitry Andric 
890349cc55cSDimitry Andric   if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
891349cc55cSDimitry Andric     return false;
892349cc55cSDimitry Andric 
893fe6060f1SDimitry Andric   assert(Widened && "Widened IV expected");
894e8d8bef9SDimitry Andric   FI.Widened = true;
895349cc55cSDimitry Andric 
896349cc55cSDimitry Andric   // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
897349cc55cSDimitry Andric   FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
898349cc55cSDimitry Andric   FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
899349cc55cSDimitry Andric 
900349cc55cSDimitry Andric   // After widening, rediscover all the loop components.
901e8d8bef9SDimitry Andric   return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
902e8d8bef9SDimitry Andric }
903e8d8bef9SDimitry Andric 
904fe6060f1SDimitry Andric static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
905fe6060f1SDimitry Andric                             ScalarEvolution *SE, AssumptionCache *AC,
90604eeddc0SDimitry Andric                             const TargetTransformInfo *TTI, LPMUpdater *U,
907*0fca6ea1SDimitry Andric                             MemorySSAUpdater *MSSAU,
908*0fca6ea1SDimitry Andric                             const LoopAccessInfo &LAI) {
909e8d8bef9SDimitry Andric   LLVM_DEBUG(
910e8d8bef9SDimitry Andric       dbgs() << "Loop flattening running on outer loop "
911e8d8bef9SDimitry Andric              << FI.OuterLoop->getHeader()->getName() << " and inner loop "
912e8d8bef9SDimitry Andric              << FI.InnerLoop->getHeader()->getName() << " in "
913e8d8bef9SDimitry Andric              << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
914e8d8bef9SDimitry Andric 
915e8d8bef9SDimitry Andric   if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
916e8d8bef9SDimitry Andric     return false;
917e8d8bef9SDimitry Andric 
918e8d8bef9SDimitry Andric   // Check if we can widen the induction variables to avoid overflow checks.
919349cc55cSDimitry Andric   bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
920e8d8bef9SDimitry Andric 
921349cc55cSDimitry Andric   // It can happen that after widening of the IV, flattening may not be
922349cc55cSDimitry Andric   // possible/happening, e.g. when it is deemed unprofitable. So bail here if
923349cc55cSDimitry Andric   // that is the case.
924349cc55cSDimitry Andric   // TODO: IV widening without performing the actual flattening transformation
925349cc55cSDimitry Andric   // is not ideal. While this codegen change should not matter much, it is an
926349cc55cSDimitry Andric   // unnecessary change which is better to avoid. It's unlikely this happens
927349cc55cSDimitry Andric   // often, because if it's unprofitibale after widening, it should be
928349cc55cSDimitry Andric   // unprofitabe before widening as checked in the first round of checks. But
929349cc55cSDimitry Andric   // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
930349cc55cSDimitry Andric   // relaxed. Because this is making a code change (the IV widening, but not
931349cc55cSDimitry Andric   // the flattening), we return true here.
932349cc55cSDimitry Andric   if (FI.Widened && !CanFlatten)
933349cc55cSDimitry Andric     return true;
934349cc55cSDimitry Andric 
935349cc55cSDimitry Andric   // If we have widened and can perform the transformation, do that here.
936349cc55cSDimitry Andric   if (CanFlatten)
93704eeddc0SDimitry Andric     return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
938349cc55cSDimitry Andric 
939349cc55cSDimitry Andric   // Otherwise, if we haven't widened the IV, check if the new iteration
940349cc55cSDimitry Andric   // variable might overflow. In this case, we need to version the loop, and
941349cc55cSDimitry Andric   // select the original version at runtime if the iteration space is too
942349cc55cSDimitry Andric   // large.
943e8d8bef9SDimitry Andric   OverflowResult OR = checkOverflow(FI, DT, AC);
944e8d8bef9SDimitry Andric   if (OR == OverflowResult::AlwaysOverflowsHigh ||
945e8d8bef9SDimitry Andric       OR == OverflowResult::AlwaysOverflowsLow) {
946e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
947e8d8bef9SDimitry Andric     return false;
948e8d8bef9SDimitry Andric   } else if (OR == OverflowResult::MayOverflow) {
949*0fca6ea1SDimitry Andric     Module *M = FI.OuterLoop->getHeader()->getParent()->getParent();
950*0fca6ea1SDimitry Andric     const DataLayout &DL = M->getDataLayout();
951*0fca6ea1SDimitry Andric     if (!VersionLoops) {
952e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
953e8d8bef9SDimitry Andric       return false;
954*0fca6ea1SDimitry Andric     } else if (!DL.isLegalInteger(
955*0fca6ea1SDimitry Andric                    FI.OuterTripCount->getType()->getScalarSizeInBits())) {
956*0fca6ea1SDimitry Andric       // If the trip count type isn't legal then it won't be possible to check
957*0fca6ea1SDimitry Andric       // for overflow using only a single multiply instruction, so don't
958*0fca6ea1SDimitry Andric       // flatten.
959*0fca6ea1SDimitry Andric       LLVM_DEBUG(
960*0fca6ea1SDimitry Andric           dbgs() << "Can't check overflow efficiently, not flattening\n");
961*0fca6ea1SDimitry Andric       return false;
962*0fca6ea1SDimitry Andric     }
963*0fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply might overflow, versioning loop\n");
964*0fca6ea1SDimitry Andric 
965*0fca6ea1SDimitry Andric     // Version the loop. The overflow check isn't a runtime pointer check, so we
966*0fca6ea1SDimitry Andric     // pass an empty list of runtime pointer checks, causing LoopVersioning to
967*0fca6ea1SDimitry Andric     // emit 'false' as the branch condition, and add our own check afterwards.
968*0fca6ea1SDimitry Andric     BasicBlock *CheckBlock = FI.OuterLoop->getLoopPreheader();
969*0fca6ea1SDimitry Andric     ArrayRef<RuntimePointerCheck> Checks(nullptr, nullptr);
970*0fca6ea1SDimitry Andric     LoopVersioning LVer(LAI, Checks, FI.OuterLoop, LI, DT, SE);
971*0fca6ea1SDimitry Andric     LVer.versionLoop();
972*0fca6ea1SDimitry Andric 
973*0fca6ea1SDimitry Andric     // Check for overflow by calculating the new tripcount using
974*0fca6ea1SDimitry Andric     // umul_with_overflow and then checking if it overflowed.
975*0fca6ea1SDimitry Andric     BranchInst *Br = cast<BranchInst>(CheckBlock->getTerminator());
976*0fca6ea1SDimitry Andric     assert(Br->isConditional() &&
977*0fca6ea1SDimitry Andric            "Expected LoopVersioning to generate a conditional branch");
978*0fca6ea1SDimitry Andric     assert(match(Br->getCondition(), m_Zero()) &&
979*0fca6ea1SDimitry Andric            "Expected branch condition to be false");
980*0fca6ea1SDimitry Andric     IRBuilder<> Builder(Br);
981*0fca6ea1SDimitry Andric     Function *F = Intrinsic::getDeclaration(M, Intrinsic::umul_with_overflow,
982*0fca6ea1SDimitry Andric                                             FI.OuterTripCount->getType());
983*0fca6ea1SDimitry Andric     Value *Call = Builder.CreateCall(F, {FI.OuterTripCount, FI.InnerTripCount},
984*0fca6ea1SDimitry Andric                                      "flatten.mul");
985*0fca6ea1SDimitry Andric     FI.NewTripCount = Builder.CreateExtractValue(Call, 0, "flatten.tripcount");
986*0fca6ea1SDimitry Andric     Value *Overflow = Builder.CreateExtractValue(Call, 1, "flatten.overflow");
987*0fca6ea1SDimitry Andric     Br->setCondition(Overflow);
988*0fca6ea1SDimitry Andric   } else {
989*0fca6ea1SDimitry Andric     LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
990e8d8bef9SDimitry Andric   }
991e8d8bef9SDimitry Andric 
99204eeddc0SDimitry Andric   return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
993e8d8bef9SDimitry Andric }
994e8d8bef9SDimitry Andric 
995fe6060f1SDimitry Andric PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM,
996fe6060f1SDimitry Andric                                        LoopStandardAnalysisResults &AR,
997fe6060f1SDimitry Andric                                        LPMUpdater &U) {
998e8d8bef9SDimitry Andric 
999fe6060f1SDimitry Andric   bool Changed = false;
1000fe6060f1SDimitry Andric 
1001bdd1243dSDimitry Andric   std::optional<MemorySSAUpdater> MSSAU;
100204eeddc0SDimitry Andric   if (AR.MSSA) {
100304eeddc0SDimitry Andric     MSSAU = MemorySSAUpdater(AR.MSSA);
100404eeddc0SDimitry Andric     if (VerifyMemorySSA)
100504eeddc0SDimitry Andric       AR.MSSA->verifyMemorySSA();
100604eeddc0SDimitry Andric   }
100704eeddc0SDimitry Andric 
1008fe6060f1SDimitry Andric   // The loop flattening pass requires loops to be
1009fe6060f1SDimitry Andric   // in simplified form, and also needs LCSSA. Running
1010fe6060f1SDimitry Andric   // this pass will simplify all loops that contain inner loops,
1011fe6060f1SDimitry Andric   // regardless of whether anything ends up being flattened.
1012*0fca6ea1SDimitry Andric   LoopAccessInfoManager LAIM(AR.SE, AR.AA, AR.DT, AR.LI, &AR.TTI, nullptr);
101306c3fb27SDimitry Andric   for (Loop *InnerLoop : LN.getLoops()) {
101406c3fb27SDimitry Andric     auto *OuterLoop = InnerLoop->getParentLoop();
101506c3fb27SDimitry Andric     if (!OuterLoop)
101606c3fb27SDimitry Andric       continue;
101706c3fb27SDimitry Andric     FlattenInfo FI(OuterLoop, InnerLoop);
1018*0fca6ea1SDimitry Andric     Changed |=
1019*0fca6ea1SDimitry Andric         FlattenLoopPair(FI, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
1020*0fca6ea1SDimitry Andric                         MSSAU ? &*MSSAU : nullptr, LAIM.getInfo(*OuterLoop));
102106c3fb27SDimitry Andric   }
1022fe6060f1SDimitry Andric 
1023fe6060f1SDimitry Andric   if (!Changed)
1024e8d8bef9SDimitry Andric     return PreservedAnalyses::all();
1025e8d8bef9SDimitry Andric 
102604eeddc0SDimitry Andric   if (AR.MSSA && VerifyMemorySSA)
102704eeddc0SDimitry Andric     AR.MSSA->verifyMemorySSA();
102804eeddc0SDimitry Andric 
102904eeddc0SDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
103004eeddc0SDimitry Andric   if (AR.MSSA)
103104eeddc0SDimitry Andric     PA.preserve<MemorySSAAnalysis>();
103204eeddc0SDimitry Andric   return PA;
1033e8d8bef9SDimitry Andric }
1034