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