xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopFlatten.cpp (revision 8e9e22f07bcbe2ee95478684cf31948370e4e51e)
1 //===- LoopFlatten.cpp - Loop flattening pass------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass flattens pairs nested loops into a single loop.
10 //
11 // The intention is to optimise loop nests like this, which together access an
12 // array linearly:
13 //
14 //   for (int i = 0; i < N; ++i)
15 //     for (int j = 0; j < M; ++j)
16 //       f(A[i*M+j]);
17 //
18 // into one loop:
19 //
20 //   for (int i = 0; i < (N*M); ++i)
21 //     f(A[i]);
22 //
23 // It can also flatten loops where the induction variables are not used in the
24 // loop. This is only worth doing if the induction variables are only used in an
25 // expression like i*M+j. If they had any other uses, we would have to insert a
26 // div/mod to reconstruct the original values, so this wouldn't be profitable.
27 //
28 // We also need to prove that N*M will not overflow. The preferred solution is
29 // to widen the IV, which avoids overflow checks, so that is tried first. If
30 // the IV cannot be widened, then we try to determine that this new tripcount
31 // expression won't overflow.
32 //
33 // Q: Does LoopFlatten use SCEV?
34 // Short answer: Yes and no.
35 //
36 // Long answer:
37 // For this transformation to be valid, we require all uses of the induction
38 // variables to be linear expressions of the form i*M+j. The different Loop
39 // APIs are used to get some loop components like the induction variable,
40 // compare statement, etc. In addition, we do some pattern matching to find the
41 // linear expressions and other loop components like the loop increment. The
42 // latter are examples of expressions that do use the induction variable, but
43 // are safe to ignore when we check all uses to be of the form i*M+j. We keep
44 // track of all of this in bookkeeping struct FlattenInfo.
45 // We assume the loops to be canonical, i.e. starting at 0 and increment with
46 // 1. This makes RHS of the compare the loop tripcount (with the right
47 // predicate). We use SCEV to then sanity check that this tripcount matches
48 // with the tripcount as computed by SCEV.
49 //
50 //===----------------------------------------------------------------------===//
51 
52 #include "llvm/Transforms/Scalar/LoopFlatten.h"
53 
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/Analysis/AssumptionCache.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/LoopNestAnalysis.h"
58 #include "llvm/Analysis/MemorySSAUpdater.h"
59 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
60 #include "llvm/Analysis/ScalarEvolution.h"
61 #include "llvm/Analysis/TargetTransformInfo.h"
62 #include "llvm/Analysis/ValueTracking.h"
63 #include "llvm/IR/Dominators.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/IRBuilder.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/InitializePasses.h"
69 #include "llvm/Pass.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Transforms/Scalar.h"
73 #include "llvm/Transforms/Scalar/LoopPassManager.h"
74 #include "llvm/Transforms/Utils/Local.h"
75 #include "llvm/Transforms/Utils/LoopUtils.h"
76 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
77 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
78 
79 using namespace llvm;
80 using namespace llvm::PatternMatch;
81 
82 #define DEBUG_TYPE "loop-flatten"
83 
84 STATISTIC(NumFlattened, "Number of loops flattened");
85 
86 static cl::opt<unsigned> RepeatedInstructionThreshold(
87     "loop-flatten-cost-threshold", cl::Hidden, cl::init(2),
88     cl::desc("Limit on the cost of instructions that can be repeated due to "
89              "loop flattening"));
90 
91 static cl::opt<bool>
92     AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden,
93                      cl::init(false),
94                      cl::desc("Assume that the product of the two iteration "
95                               "trip counts will never overflow"));
96 
97 static cl::opt<bool>
98     WidenIV("loop-flatten-widen-iv", cl::Hidden, cl::init(true),
99             cl::desc("Widen the loop induction variables, if possible, so "
100                      "overflow checks won't reject flattening"));
101 
102 // We require all uses of both induction variables to match this pattern:
103 //
104 //   (OuterPHI * InnerTripCount) + InnerPHI
105 //
106 // I.e., it needs to be a linear expression of the induction variables and the
107 // inner loop trip count. We keep track of all different expressions on which
108 // checks will be performed in this bookkeeping struct.
109 //
110 struct FlattenInfo {
111   Loop *OuterLoop = nullptr;  // The loop pair to be flattened.
112   Loop *InnerLoop = nullptr;
113 
114   PHINode *InnerInductionPHI = nullptr; // These PHINodes correspond to loop
115   PHINode *OuterInductionPHI = nullptr; // induction variables, which are
116                                         // expected to start at zero and
117                                         // increment by one on each loop.
118 
119   Value *InnerTripCount = nullptr; // The product of these two tripcounts
120   Value *OuterTripCount = nullptr; // will be the new flattened loop
121                                    // tripcount. Also used to recognise a
122                                    // linear expression that will be replaced.
123 
124   SmallPtrSet<Value *, 4> LinearIVUses;  // Contains the linear expressions
125                                          // of the form i*M+j that will be
126                                          // replaced.
127 
128   BinaryOperator *InnerIncrement = nullptr;  // Uses of induction variables in
129   BinaryOperator *OuterIncrement = nullptr;  // loop control statements that
130   BranchInst *InnerBranch = nullptr;         // are safe to ignore.
131 
132   BranchInst *OuterBranch = nullptr; // The instruction that needs to be
133                                      // updated with new tripcount.
134 
135   SmallPtrSet<PHINode *, 4> InnerPHIsToTransform;
136 
137   bool Widened = false; // Whether this holds the flatten info before or after
138                         // widening.
139 
140   PHINode *NarrowInnerInductionPHI = nullptr; // Holds the old/narrow induction
141   PHINode *NarrowOuterInductionPHI = nullptr; // phis, i.e. the Phis before IV
142                                               // has been applied. Used to skip
143                                               // checks on phi nodes.
144 
145   FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL){};
146 
147   bool isNarrowInductionPhi(PHINode *Phi) {
148     // This can't be the narrow phi if we haven't widened the IV first.
149     if (!Widened)
150       return false;
151     return NarrowInnerInductionPHI == Phi || NarrowOuterInductionPHI == Phi;
152   }
153   bool isInnerLoopIncrement(User *U) {
154     return InnerIncrement == U;
155   }
156   bool isOuterLoopIncrement(User *U) {
157     return OuterIncrement == U;
158   }
159   bool isInnerLoopTest(User *U) {
160     return InnerBranch->getCondition() == U;
161   }
162 
163   bool checkOuterInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
164     for (User *U : OuterInductionPHI->users()) {
165       if (isOuterLoopIncrement(U))
166         continue;
167 
168       auto IsValidOuterPHIUses = [&] (User *U) -> bool {
169         LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump());
170         if (!ValidOuterPHIUses.count(U)) {
171           LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
172           return false;
173         }
174         LLVM_DEBUG(dbgs() << "Use is optimisable\n");
175         return true;
176       };
177 
178       if (auto *V = dyn_cast<TruncInst>(U)) {
179         for (auto *K : V->users()) {
180           if (!IsValidOuterPHIUses(K))
181             return false;
182         }
183         continue;
184       }
185 
186       if (!IsValidOuterPHIUses(U))
187         return false;
188     }
189     return true;
190   }
191 
192   bool matchLinearIVUser(User *U, Value *InnerTripCount,
193                          SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
194     LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump());
195     Value *MatchedMul = nullptr;
196     Value *MatchedItCount = nullptr;
197 
198     bool IsAdd = match(U, m_c_Add(m_Specific(InnerInductionPHI),
199                                   m_Value(MatchedMul))) &&
200                  match(MatchedMul, m_c_Mul(m_Specific(OuterInductionPHI),
201                                            m_Value(MatchedItCount)));
202 
203     // Matches the same pattern as above, except it also looks for truncs
204     // on the phi, which can be the result of widening the induction variables.
205     bool IsAddTrunc =
206         match(U, m_c_Add(m_Trunc(m_Specific(InnerInductionPHI)),
207                          m_Value(MatchedMul))) &&
208         match(MatchedMul, m_c_Mul(m_Trunc(m_Specific(OuterInductionPHI)),
209                                   m_Value(MatchedItCount)));
210 
211     if (!MatchedItCount)
212       return false;
213 
214     // Look through extends if the IV has been widened. Don't look through
215     // extends if we already looked through a trunc.
216     if (Widened && IsAdd &&
217         (isa<SExtInst>(MatchedItCount) || isa<ZExtInst>(MatchedItCount))) {
218       assert(MatchedItCount->getType() == InnerInductionPHI->getType() &&
219              "Unexpected type mismatch in types after widening");
220       MatchedItCount = isa<SExtInst>(MatchedItCount)
221                            ? dyn_cast<SExtInst>(MatchedItCount)->getOperand(0)
222                            : dyn_cast<ZExtInst>(MatchedItCount)->getOperand(0);
223     }
224 
225     if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerTripCount) {
226       LLVM_DEBUG(dbgs() << "Use is optimisable\n");
227       ValidOuterPHIUses.insert(MatchedMul);
228       LinearIVUses.insert(U);
229       return true;
230     }
231 
232     LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n");
233     return false;
234   }
235 
236   bool checkInnerInductionPhiUsers(SmallPtrSet<Value *, 4> &ValidOuterPHIUses) {
237     Value *SExtInnerTripCount = InnerTripCount;
238     if (Widened &&
239         (isa<SExtInst>(InnerTripCount) || isa<ZExtInst>(InnerTripCount)))
240       SExtInnerTripCount = cast<Instruction>(InnerTripCount)->getOperand(0);
241 
242     for (User *U : InnerInductionPHI->users()) {
243       if (isInnerLoopIncrement(U))
244         continue;
245 
246       // After widening the IVs, a trunc instruction might have been introduced,
247       // so look through truncs.
248       if (isa<TruncInst>(U)) {
249         if (!U->hasOneUse())
250           return false;
251         U = *U->user_begin();
252       }
253 
254       // If the use is in the compare (which is also the condition of the inner
255       // branch) then the compare has been altered by another transformation e.g
256       // icmp ult %inc, tripcount -> icmp ult %j, tripcount-1, where tripcount is
257       // a constant. Ignore this use as the compare gets removed later anyway.
258       if (isInnerLoopTest(U))
259         continue;
260 
261       if (!matchLinearIVUser(U, SExtInnerTripCount, ValidOuterPHIUses))
262         return false;
263     }
264     return true;
265   }
266 };
267 
268 static bool
269 setLoopComponents(Value *&TC, Value *&TripCount, BinaryOperator *&Increment,
270                   SmallPtrSetImpl<Instruction *> &IterationInstructions) {
271   TripCount = TC;
272   IterationInstructions.insert(Increment);
273   LLVM_DEBUG(dbgs() << "Found Increment: "; Increment->dump());
274   LLVM_DEBUG(dbgs() << "Found trip count: "; TripCount->dump());
275   LLVM_DEBUG(dbgs() << "Successfully found all loop components\n");
276   return true;
277 }
278 
279 // Given the RHS of the loop latch compare instruction, verify with SCEV
280 // that this is indeed the loop tripcount.
281 // TODO: This used to be a straightforward check but has grown to be quite
282 // complicated now. It is therefore worth revisiting what the additional
283 // benefits are of this (compared to relying on canonical loops and pattern
284 // matching).
285 static bool verifyTripCount(Value *RHS, Loop *L,
286      SmallPtrSetImpl<Instruction *> &IterationInstructions,
287     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
288     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
289   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
290   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
291     LLVM_DEBUG(dbgs() << "Backedge-taken count is not predictable\n");
292     return false;
293   }
294 
295   // The Extend=false flag is used for getTripCountFromExitCount as we want
296   // to verify and match it with the pattern matched tripcount. Please note
297   // that overflow checks are performed in checkOverflow, but are first tried
298   // to avoid by widening the IV.
299   const SCEV *SCEVTripCount =
300       SE->getTripCountFromExitCount(BackedgeTakenCount, /*Extend=*/false);
301 
302   const SCEV *SCEVRHS = SE->getSCEV(RHS);
303   if (SCEVRHS == SCEVTripCount)
304     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
305   ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(RHS);
306   if (ConstantRHS) {
307     const SCEV *BackedgeTCExt = nullptr;
308     if (IsWidened) {
309       const SCEV *SCEVTripCountExt;
310       // Find the extended backedge taken count and extended trip count using
311       // SCEV. One of these should now match the RHS of the compare.
312       BackedgeTCExt = SE->getZeroExtendExpr(BackedgeTakenCount, RHS->getType());
313       SCEVTripCountExt = SE->getTripCountFromExitCount(BackedgeTCExt, false);
314       if (SCEVRHS != BackedgeTCExt && SCEVRHS != SCEVTripCountExt) {
315         LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
316         return false;
317       }
318     }
319     // If the RHS of the compare is equal to the backedge taken count we need
320     // to add one to get the trip count.
321     if (SCEVRHS == BackedgeTCExt || SCEVRHS == BackedgeTakenCount) {
322       ConstantInt *One = ConstantInt::get(ConstantRHS->getType(), 1);
323       Value *NewRHS = ConstantInt::get(
324           ConstantRHS->getContext(), ConstantRHS->getValue() + One->getValue());
325       return setLoopComponents(NewRHS, TripCount, Increment,
326                                IterationInstructions);
327     }
328     return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
329   }
330   // If the RHS isn't a constant then check that the reason it doesn't match
331   // the SCEV trip count is because the RHS is a ZExt or SExt instruction
332   // (and take the trip count to be the RHS).
333   if (!IsWidened) {
334     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
335     return false;
336   }
337   auto *TripCountInst = dyn_cast<Instruction>(RHS);
338   if (!TripCountInst) {
339     LLVM_DEBUG(dbgs() << "Could not find valid trip count\n");
340     return false;
341   }
342   if ((!isa<ZExtInst>(TripCountInst) && !isa<SExtInst>(TripCountInst)) ||
343       SE->getSCEV(TripCountInst->getOperand(0)) != SCEVTripCount) {
344     LLVM_DEBUG(dbgs() << "Could not find valid extended trip count\n");
345     return false;
346   }
347   return setLoopComponents(RHS, TripCount, Increment, IterationInstructions);
348 }
349 
350 // Finds the induction variable, increment and trip count for a simple loop that
351 // we can flatten.
352 static bool findLoopComponents(
353     Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions,
354     PHINode *&InductionPHI, Value *&TripCount, BinaryOperator *&Increment,
355     BranchInst *&BackBranch, ScalarEvolution *SE, bool IsWidened) {
356   LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n");
357 
358   if (!L->isLoopSimplifyForm()) {
359     LLVM_DEBUG(dbgs() << "Loop is not in normal form\n");
360     return false;
361   }
362 
363   // Currently, to simplify the implementation, the Loop induction variable must
364   // start at zero and increment with a step size of one.
365   if (!L->isCanonical(*SE)) {
366     LLVM_DEBUG(dbgs() << "Loop is not canonical\n");
367     return false;
368   }
369 
370   // There must be exactly one exiting block, and it must be the same at the
371   // latch.
372   BasicBlock *Latch = L->getLoopLatch();
373   if (L->getExitingBlock() != Latch) {
374     LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n");
375     return false;
376   }
377 
378   // Find the induction PHI. If there is no induction PHI, we can't do the
379   // transformation. TODO: could other variables trigger this? Do we have to
380   // search for the best one?
381   InductionPHI = L->getInductionVariable(*SE);
382   if (!InductionPHI) {
383     LLVM_DEBUG(dbgs() << "Could not find induction PHI\n");
384     return false;
385   }
386   LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump());
387 
388   bool ContinueOnTrue = L->contains(Latch->getTerminator()->getSuccessor(0));
389   auto IsValidPredicate = [&](ICmpInst::Predicate Pred) {
390     if (ContinueOnTrue)
391       return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT;
392     else
393       return Pred == CmpInst::ICMP_EQ;
394   };
395 
396   // Find Compare and make sure it is valid. getLatchCmpInst checks that the
397   // back branch of the latch is conditional.
398   ICmpInst *Compare = L->getLatchCmpInst();
399   if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) ||
400       Compare->hasNUsesOrMore(2)) {
401     LLVM_DEBUG(dbgs() << "Could not find valid comparison\n");
402     return false;
403   }
404   BackBranch = cast<BranchInst>(Latch->getTerminator());
405   IterationInstructions.insert(BackBranch);
406   LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump());
407   IterationInstructions.insert(Compare);
408   LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump());
409 
410   // Find increment and trip count.
411   // There are exactly 2 incoming values to the induction phi; one from the
412   // pre-header and one from the latch. The incoming latch value is the
413   // increment variable.
414   Increment =
415       cast<BinaryOperator>(InductionPHI->getIncomingValueForBlock(Latch));
416   if ((Compare->getOperand(0) != Increment || !Increment->hasNUses(2)) &&
417       !Increment->hasNUses(1)) {
418     LLVM_DEBUG(dbgs() << "Could not find valid increment\n");
419     return false;
420   }
421   // The trip count is the RHS of the compare. If this doesn't match the trip
422   // count computed by SCEV then this is because the trip count variable
423   // has been widened so the types don't match, or because it is a constant and
424   // another transformation has changed the compare (e.g. icmp ult %inc,
425   // tripcount -> icmp ult %j, tripcount-1), or both.
426   Value *RHS = Compare->getOperand(1);
427 
428   return verifyTripCount(RHS, L, IterationInstructions, InductionPHI, TripCount,
429                          Increment, BackBranch, SE, IsWidened);
430 }
431 
432 static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) {
433   // All PHIs in the inner and outer headers must either be:
434   // - The induction PHI, which we are going to rewrite as one induction in
435   //   the new loop. This is already checked by findLoopComponents.
436   // - An outer header PHI with all incoming values from outside the loop.
437   //   LoopSimplify guarantees we have a pre-header, so we don't need to
438   //   worry about that here.
439   // - Pairs of PHIs in the inner and outer headers, which implement a
440   //   loop-carried dependency that will still be valid in the new loop. To
441   //   be valid, this variable must be modified only in the inner loop.
442 
443   // The set of PHI nodes in the outer loop header that we know will still be
444   // valid after the transformation. These will not need to be modified (with
445   // the exception of the induction variable), but we do need to check that
446   // there are no unsafe PHI nodes.
447   SmallPtrSet<PHINode *, 4> SafeOuterPHIs;
448   SafeOuterPHIs.insert(FI.OuterInductionPHI);
449 
450   // Check that all PHI nodes in the inner loop header match one of the valid
451   // patterns.
452   for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) {
453     // The induction PHIs break these rules, and that's OK because we treat
454     // them specially when doing the transformation.
455     if (&InnerPHI == FI.InnerInductionPHI)
456       continue;
457     if (FI.isNarrowInductionPhi(&InnerPHI))
458       continue;
459 
460     // Each inner loop PHI node must have two incoming values/blocks - one
461     // from the pre-header, and one from the latch.
462     assert(InnerPHI.getNumIncomingValues() == 2);
463     Value *PreHeaderValue =
464         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader());
465     Value *LatchValue =
466         InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch());
467 
468     // The incoming value from the outer loop must be the PHI node in the
469     // outer loop header, with no modifications made in the top of the outer
470     // loop.
471     PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue);
472     if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) {
473       LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n");
474       return false;
475     }
476 
477     // The other incoming value must come from the inner loop, without any
478     // modifications in the tail end of the outer loop. We are in LCSSA form,
479     // so this will actually be a PHI in the inner loop's exit block, which
480     // only uses values from inside the inner loop.
481     PHINode *LCSSAPHI = dyn_cast<PHINode>(
482         OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch()));
483     if (!LCSSAPHI) {
484       LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n");
485       return false;
486     }
487 
488     // The value used by the LCSSA PHI must be the same one that the inner
489     // loop's PHI uses.
490     if (LCSSAPHI->hasConstantValue() != LatchValue) {
491       LLVM_DEBUG(
492           dbgs() << "LCSSA PHI incoming value does not match latch value\n");
493       return false;
494     }
495 
496     LLVM_DEBUG(dbgs() << "PHI pair is safe:\n");
497     LLVM_DEBUG(dbgs() << "  Inner: "; InnerPHI.dump());
498     LLVM_DEBUG(dbgs() << "  Outer: "; OuterPHI->dump());
499     SafeOuterPHIs.insert(OuterPHI);
500     FI.InnerPHIsToTransform.insert(&InnerPHI);
501   }
502 
503   for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) {
504     if (FI.isNarrowInductionPhi(&OuterPHI))
505       continue;
506     if (!SafeOuterPHIs.count(&OuterPHI)) {
507       LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump());
508       return false;
509     }
510   }
511 
512   LLVM_DEBUG(dbgs() << "checkPHIs: OK\n");
513   return true;
514 }
515 
516 static bool
517 checkOuterLoopInsts(FlattenInfo &FI,
518                     SmallPtrSetImpl<Instruction *> &IterationInstructions,
519                     const TargetTransformInfo *TTI) {
520   // Check for instructions in the outer but not inner loop. If any of these
521   // have side-effects then this transformation is not legal, and if there is
522   // a significant amount of code here which can't be optimised out that it's
523   // not profitable (as these instructions would get executed for each
524   // iteration of the inner loop).
525   InstructionCost RepeatedInstrCost = 0;
526   for (auto *B : FI.OuterLoop->getBlocks()) {
527     if (FI.InnerLoop->contains(B))
528       continue;
529 
530     for (auto &I : *B) {
531       if (!isa<PHINode>(&I) && !I.isTerminator() &&
532           !isSafeToSpeculativelyExecute(&I)) {
533         LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have "
534                              "side effects: ";
535                    I.dump());
536         return false;
537       }
538       // The execution count of the outer loop's iteration instructions
539       // (increment, compare and branch) will be increased, but the
540       // equivalent instructions will be removed from the inner loop, so
541       // they make a net difference of zero.
542       if (IterationInstructions.count(&I))
543         continue;
544       // The unconditional branch to the inner loop's header will turn into
545       // a fall-through, so adds no cost.
546       BranchInst *Br = dyn_cast<BranchInst>(&I);
547       if (Br && Br->isUnconditional() &&
548           Br->getSuccessor(0) == FI.InnerLoop->getHeader())
549         continue;
550       // Multiplies of the outer iteration variable and inner iteration
551       // count will be optimised out.
552       if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI),
553                             m_Specific(FI.InnerTripCount))))
554         continue;
555       InstructionCost Cost =
556           TTI->getInstructionCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
557       LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump());
558       RepeatedInstrCost += Cost;
559     }
560   }
561 
562   LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: "
563                     << RepeatedInstrCost << "\n");
564   // Bail out if flattening the loops would cause instructions in the outer
565   // loop but not in the inner loop to be executed extra times.
566   if (RepeatedInstrCost > RepeatedInstructionThreshold) {
567     LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n");
568     return false;
569   }
570 
571   LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n");
572   return true;
573 }
574 
575 
576 
577 // We require all uses of both induction variables to match this pattern:
578 //
579 //   (OuterPHI * InnerTripCount) + InnerPHI
580 //
581 // Any uses of the induction variables not matching that pattern would
582 // require a div/mod to reconstruct in the flattened loop, so the
583 // transformation wouldn't be profitable.
584 static bool checkIVUsers(FlattenInfo &FI) {
585   // Check that all uses of the inner loop's induction variable match the
586   // expected pattern, recording the uses of the outer IV.
587   SmallPtrSet<Value *, 4> ValidOuterPHIUses;
588   if (!FI.checkInnerInductionPhiUsers(ValidOuterPHIUses))
589     return false;
590 
591   // Check that there are no uses of the outer IV other than the ones found
592   // as part of the pattern above.
593   if (!FI.checkOuterInductionPhiUsers(ValidOuterPHIUses))
594     return false;
595 
596   LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n";
597              dbgs() << "Found " << FI.LinearIVUses.size()
598                     << " value(s) that can be replaced:\n";
599              for (Value *V : FI.LinearIVUses) {
600                dbgs() << "  ";
601                V->dump();
602              });
603   return true;
604 }
605 
606 // Return an OverflowResult dependant on if overflow of the multiplication of
607 // InnerTripCount and OuterTripCount can be assumed not to happen.
608 static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT,
609                                     AssumptionCache *AC) {
610   Function *F = FI.OuterLoop->getHeader()->getParent();
611   const DataLayout &DL = F->getParent()->getDataLayout();
612 
613   // For debugging/testing.
614   if (AssumeNoOverflow)
615     return OverflowResult::NeverOverflows;
616 
617   // Check if the multiply could not overflow due to known ranges of the
618   // input values.
619   OverflowResult OR = computeOverflowForUnsignedMul(
620       FI.InnerTripCount, FI.OuterTripCount, DL, AC,
621       FI.OuterLoop->getLoopPreheader()->getTerminator(), DT);
622   if (OR != OverflowResult::MayOverflow)
623     return OR;
624 
625   for (Value *V : FI.LinearIVUses) {
626     for (Value *U : V->users()) {
627       if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
628         for (Value *GEPUser : U->users()) {
629           auto *GEPUserInst = cast<Instruction>(GEPUser);
630           if (!isa<LoadInst>(GEPUserInst) &&
631               !(isa<StoreInst>(GEPUserInst) &&
632                 GEP == GEPUserInst->getOperand(1)))
633             continue;
634           if (!isGuaranteedToExecuteForEveryIteration(GEPUserInst,
635                                                       FI.InnerLoop))
636             continue;
637           // The IV is used as the operand of a GEP which dominates the loop
638           // latch, and the IV is at least as wide as the address space of the
639           // GEP. In this case, the GEP would wrap around the address space
640           // before the IV increment wraps, which would be UB.
641           if (GEP->isInBounds() &&
642               V->getType()->getIntegerBitWidth() >=
643                   DL.getPointerTypeSizeInBits(GEP->getType())) {
644             LLVM_DEBUG(
645                 dbgs() << "use of linear IV would be UB if overflow occurred: ";
646                 GEP->dump());
647             return OverflowResult::NeverOverflows;
648           }
649         }
650       }
651     }
652   }
653 
654   return OverflowResult::MayOverflow;
655 }
656 
657 static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
658                                ScalarEvolution *SE, AssumptionCache *AC,
659                                const TargetTransformInfo *TTI) {
660   SmallPtrSet<Instruction *, 8> IterationInstructions;
661   if (!findLoopComponents(FI.InnerLoop, IterationInstructions,
662                           FI.InnerInductionPHI, FI.InnerTripCount,
663                           FI.InnerIncrement, FI.InnerBranch, SE, FI.Widened))
664     return false;
665   if (!findLoopComponents(FI.OuterLoop, IterationInstructions,
666                           FI.OuterInductionPHI, FI.OuterTripCount,
667                           FI.OuterIncrement, FI.OuterBranch, SE, FI.Widened))
668     return false;
669 
670   // Both of the loop trip count values must be invariant in the outer loop
671   // (non-instructions are all inherently invariant).
672   if (!FI.OuterLoop->isLoopInvariant(FI.InnerTripCount)) {
673     LLVM_DEBUG(dbgs() << "inner loop trip count not invariant\n");
674     return false;
675   }
676   if (!FI.OuterLoop->isLoopInvariant(FI.OuterTripCount)) {
677     LLVM_DEBUG(dbgs() << "outer loop trip count not invariant\n");
678     return false;
679   }
680 
681   if (!checkPHIs(FI, TTI))
682     return false;
683 
684   // FIXME: it should be possible to handle different types correctly.
685   if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType())
686     return false;
687 
688   if (!checkOuterLoopInsts(FI, IterationInstructions, TTI))
689     return false;
690 
691   // Find the values in the loop that can be replaced with the linearized
692   // induction variable, and check that there are no other uses of the inner
693   // or outer induction variable. If there were, we could still do this
694   // transformation, but we'd have to insert a div/mod to calculate the
695   // original IVs, so it wouldn't be profitable.
696   if (!checkIVUsers(FI))
697     return false;
698 
699   LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n");
700   return true;
701 }
702 
703 static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
704                               ScalarEvolution *SE, AssumptionCache *AC,
705                               const TargetTransformInfo *TTI, LPMUpdater *U,
706                               MemorySSAUpdater *MSSAU) {
707   Function *F = FI.OuterLoop->getHeader()->getParent();
708   LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n");
709   {
710     using namespace ore;
711     OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(),
712                               FI.InnerLoop->getHeader());
713     OptimizationRemarkEmitter ORE(F);
714     Remark << "Flattened into outer loop";
715     ORE.emit(Remark);
716   }
717 
718   Value *NewTripCount = BinaryOperator::CreateMul(
719       FI.InnerTripCount, FI.OuterTripCount, "flatten.tripcount",
720       FI.OuterLoop->getLoopPreheader()->getTerminator());
721   LLVM_DEBUG(dbgs() << "Created new trip count in preheader: ";
722              NewTripCount->dump());
723 
724   // Fix up PHI nodes that take values from the inner loop back-edge, which
725   // we are about to remove.
726   FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
727 
728   // The old Phi will be optimised away later, but for now we can't leave
729   // leave it in an invalid state, so are updating them too.
730   for (PHINode *PHI : FI.InnerPHIsToTransform)
731     PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch());
732 
733   // Modify the trip count of the outer loop to be the product of the two
734   // trip counts.
735   cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount);
736 
737   // Replace the inner loop backedge with an unconditional branch to the exit.
738   BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock();
739   BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock();
740   InnerExitingBlock->getTerminator()->eraseFromParent();
741   BranchInst::Create(InnerExitBlock, InnerExitingBlock);
742 
743   // Update the DomTree and MemorySSA.
744   DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
745   if (MSSAU)
746     MSSAU->removeEdge(InnerExitingBlock, FI.InnerLoop->getHeader());
747 
748   // Replace all uses of the polynomial calculated from the two induction
749   // variables with the one new one.
750   IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator());
751   for (Value *V : FI.LinearIVUses) {
752     Value *OuterValue = FI.OuterInductionPHI;
753     if (FI.Widened)
754       OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(),
755                                        "flatten.trunciv");
756 
757     LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); dbgs() << "with:      ";
758                OuterValue->dump());
759     V->replaceAllUsesWith(OuterValue);
760   }
761 
762   // Tell LoopInfo, SCEV and the pass manager that the inner loop has been
763   // deleted, and any information that have about the outer loop invalidated.
764   SE->forgetLoop(FI.OuterLoop);
765   SE->forgetLoop(FI.InnerLoop);
766   SE->forgetBlockAndLoopDispositions();
767   if (U)
768     U->markLoopAsDeleted(*FI.InnerLoop, FI.InnerLoop->getName());
769   LI->erase(FI.InnerLoop);
770 
771   // Increment statistic value.
772   NumFlattened++;
773 
774   return true;
775 }
776 
777 static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
778                        ScalarEvolution *SE, AssumptionCache *AC,
779                        const TargetTransformInfo *TTI) {
780   if (!WidenIV) {
781     LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n");
782     return false;
783   }
784 
785   LLVM_DEBUG(dbgs() << "Try widening the IVs\n");
786   Module *M = FI.InnerLoop->getHeader()->getParent()->getParent();
787   auto &DL = M->getDataLayout();
788   auto *InnerType = FI.InnerInductionPHI->getType();
789   auto *OuterType = FI.OuterInductionPHI->getType();
790   unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits();
791   auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext());
792 
793   // If both induction types are less than the maximum legal integer width,
794   // promote both to the widest type available so we know calculating
795   // (OuterTripCount * InnerTripCount) as the new trip count is safe.
796   if (InnerType != OuterType ||
797       InnerType->getScalarSizeInBits() >= MaxLegalSize ||
798       MaxLegalType->getScalarSizeInBits() <
799           InnerType->getScalarSizeInBits() * 2) {
800     LLVM_DEBUG(dbgs() << "Can't widen the IV\n");
801     return false;
802   }
803 
804   SCEVExpander Rewriter(*SE, DL, "loopflatten");
805   SmallVector<WeakTrackingVH, 4> DeadInsts;
806   unsigned ElimExt = 0;
807   unsigned Widened = 0;
808 
809   auto CreateWideIV = [&](WideIVInfo WideIV, bool &Deleted) -> bool {
810     PHINode *WidePhi =
811         createWideIV(WideIV, LI, SE, Rewriter, DT, DeadInsts, ElimExt, Widened,
812                      true /* HasGuards */, true /* UsePostIncrementRanges */);
813     if (!WidePhi)
814       return false;
815     LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump());
816     LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIV.NarrowIV->dump());
817     Deleted = RecursivelyDeleteDeadPHINode(WideIV.NarrowIV);
818     return true;
819   };
820 
821   bool Deleted;
822   if (!CreateWideIV({FI.InnerInductionPHI, MaxLegalType, false}, Deleted))
823     return false;
824   // Add the narrow phi to list, so that it will be adjusted later when the
825   // the transformation is performed.
826   if (!Deleted)
827     FI.InnerPHIsToTransform.insert(FI.InnerInductionPHI);
828 
829   if (!CreateWideIV({FI.OuterInductionPHI, MaxLegalType, false}, Deleted))
830     return false;
831 
832   assert(Widened && "Widened IV expected");
833   FI.Widened = true;
834 
835   // Save the old/narrow induction phis, which we need to ignore in CheckPHIs.
836   FI.NarrowInnerInductionPHI = FI.InnerInductionPHI;
837   FI.NarrowOuterInductionPHI = FI.OuterInductionPHI;
838 
839   // After widening, rediscover all the loop components.
840   return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI);
841 }
842 
843 static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI,
844                             ScalarEvolution *SE, AssumptionCache *AC,
845                             const TargetTransformInfo *TTI, LPMUpdater *U,
846                             MemorySSAUpdater *MSSAU) {
847   LLVM_DEBUG(
848       dbgs() << "Loop flattening running on outer loop "
849              << FI.OuterLoop->getHeader()->getName() << " and inner loop "
850              << FI.InnerLoop->getHeader()->getName() << " in "
851              << FI.OuterLoop->getHeader()->getParent()->getName() << "\n");
852 
853   if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI))
854     return false;
855 
856   // Check if we can widen the induction variables to avoid overflow checks.
857   bool CanFlatten = CanWidenIV(FI, DT, LI, SE, AC, TTI);
858 
859   // It can happen that after widening of the IV, flattening may not be
860   // possible/happening, e.g. when it is deemed unprofitable. So bail here if
861   // that is the case.
862   // TODO: IV widening without performing the actual flattening transformation
863   // is not ideal. While this codegen change should not matter much, it is an
864   // unnecessary change which is better to avoid. It's unlikely this happens
865   // often, because if it's unprofitibale after widening, it should be
866   // unprofitabe before widening as checked in the first round of checks. But
867   // 'RepeatedInstructionThreshold' is set to only 2, which can probably be
868   // relaxed. Because this is making a code change (the IV widening, but not
869   // the flattening), we return true here.
870   if (FI.Widened && !CanFlatten)
871     return true;
872 
873   // If we have widened and can perform the transformation, do that here.
874   if (CanFlatten)
875     return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
876 
877   // Otherwise, if we haven't widened the IV, check if the new iteration
878   // variable might overflow. In this case, we need to version the loop, and
879   // select the original version at runtime if the iteration space is too
880   // large.
881   // TODO: We currently don't version the loop.
882   OverflowResult OR = checkOverflow(FI, DT, AC);
883   if (OR == OverflowResult::AlwaysOverflowsHigh ||
884       OR == OverflowResult::AlwaysOverflowsLow) {
885     LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n");
886     return false;
887   } else if (OR == OverflowResult::MayOverflow) {
888     LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n");
889     return false;
890   }
891 
892   LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n");
893   return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
894 }
895 
896 bool Flatten(LoopNest &LN, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE,
897              AssumptionCache *AC, TargetTransformInfo *TTI, LPMUpdater *U,
898              MemorySSAUpdater *MSSAU) {
899   bool Changed = false;
900   for (Loop *InnerLoop : LN.getLoops()) {
901     auto *OuterLoop = InnerLoop->getParentLoop();
902     if (!OuterLoop)
903       continue;
904     FlattenInfo FI(OuterLoop, InnerLoop);
905     Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI, U, MSSAU);
906   }
907   return Changed;
908 }
909 
910 PreservedAnalyses LoopFlattenPass::run(LoopNest &LN, LoopAnalysisManager &LAM,
911                                        LoopStandardAnalysisResults &AR,
912                                        LPMUpdater &U) {
913 
914   bool Changed = false;
915 
916   Optional<MemorySSAUpdater> MSSAU;
917   if (AR.MSSA) {
918     MSSAU = MemorySSAUpdater(AR.MSSA);
919     if (VerifyMemorySSA)
920       AR.MSSA->verifyMemorySSA();
921   }
922 
923   // The loop flattening pass requires loops to be
924   // in simplified form, and also needs LCSSA. Running
925   // this pass will simplify all loops that contain inner loops,
926   // regardless of whether anything ends up being flattened.
927   Changed |= Flatten(LN, &AR.DT, &AR.LI, &AR.SE, &AR.AC, &AR.TTI, &U,
928                      MSSAU ? &*MSSAU : nullptr);
929 
930   if (!Changed)
931     return PreservedAnalyses::all();
932 
933   if (AR.MSSA && VerifyMemorySSA)
934     AR.MSSA->verifyMemorySSA();
935 
936   auto PA = getLoopPassPreservedAnalyses();
937   if (AR.MSSA)
938     PA.preserve<MemorySSAAnalysis>();
939   return PA;
940 }
941 
942 namespace {
943 class LoopFlattenLegacyPass : public FunctionPass {
944 public:
945   static char ID; // Pass ID, replacement for typeid
946   LoopFlattenLegacyPass() : FunctionPass(ID) {
947     initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry());
948   }
949 
950   // Possibly flatten loop L into its child.
951   bool runOnFunction(Function &F) override;
952 
953   void getAnalysisUsage(AnalysisUsage &AU) const override {
954     getLoopAnalysisUsage(AU);
955     AU.addRequired<TargetTransformInfoWrapperPass>();
956     AU.addPreserved<TargetTransformInfoWrapperPass>();
957     AU.addRequired<AssumptionCacheTracker>();
958     AU.addPreserved<AssumptionCacheTracker>();
959     AU.addPreserved<MemorySSAWrapperPass>();
960   }
961 };
962 } // namespace
963 
964 char LoopFlattenLegacyPass::ID = 0;
965 INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
966                       false, false)
967 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
968 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
969 INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops",
970                     false, false)
971 
972 FunctionPass *llvm::createLoopFlattenPass() {
973   return new LoopFlattenLegacyPass();
974 }
975 
976 bool LoopFlattenLegacyPass::runOnFunction(Function &F) {
977   ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
978   LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
979   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
980   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
981   auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>();
982   auto *TTI = &TTIP.getTTI(F);
983   auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
984   auto *MSSA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
985 
986   Optional<MemorySSAUpdater> MSSAU;
987   if (MSSA)
988     MSSAU = MemorySSAUpdater(&MSSA->getMSSA());
989 
990   bool Changed = false;
991   for (Loop *L : *LI) {
992     auto LN = LoopNest::getLoopNest(*L, *SE);
993     Changed |=
994         Flatten(*LN, DT, LI, SE, AC, TTI, nullptr, MSSAU ? &*MSSAU : nullptr);
995   }
996   return Changed;
997 }
998