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