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