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