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