1 //===- LoopFuse.cpp - Loop Fusion 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 /// \file
10 /// This file implements the loop fusion pass.
11 /// The implementation is largely based on the following document:
12 ///
13 ///       Code Transformations to Augment the Scope of Loop Fusion in a
14 ///         Production Compiler
15 ///       Christopher Mark Barton
16 ///       MSc Thesis
17 ///       https://webdocs.cs.ualberta.ca/~amaral/thesis/ChristopherBartonMSc.pdf
18 ///
19 /// The general approach taken is to collect sets of control flow equivalent
20 /// loops and test whether they can be fused. The necessary conditions for
21 /// fusion are:
22 ///    1. The loops must be adjacent (there cannot be any statements between
23 ///       the two loops).
24 ///    2. The loops must be conforming (they must execute the same number of
25 ///       iterations).
26 ///    3. The loops must be control flow equivalent (if one loop executes, the
27 ///       other is guaranteed to execute).
28 ///    4. There cannot be any negative distance dependencies between the loops.
29 /// If all of these conditions are satisfied, it is safe to fuse the loops.
30 ///
31 /// This implementation creates FusionCandidates that represent the loop and the
32 /// necessary information needed by fusion. It then operates on the fusion
33 /// candidates, first confirming that the candidate is eligible for fusion. The
34 /// candidates are then collected into control flow equivalent sets, sorted in
35 /// dominance order. Each set of control flow equivalent candidates is then
36 /// traversed, attempting to fuse pairs of candidates in the set. If all
37 /// requirements for fusion are met, the two candidates are fused, creating a
38 /// new (fused) candidate which is then added back into the set to consider for
39 /// additional fusion.
40 ///
41 /// This implementation currently does not make any modifications to remove
42 /// conditions for fusion. Code transformations to make loops conform to each of
43 /// the conditions for fusion are discussed in more detail in the document
44 /// above. These can be added to the current implementation in the future.
45 //===----------------------------------------------------------------------===//
46 
47 #include "llvm/Transforms/Scalar/LoopFuse.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/Analysis/DependenceAnalysis.h"
50 #include "llvm/Analysis/DomTreeUpdater.h"
51 #include "llvm/Analysis/LoopInfo.h"
52 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
53 #include "llvm/Analysis/PostDominators.h"
54 #include "llvm/Analysis/ScalarEvolution.h"
55 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/Verifier.h"
58 #include "llvm/InitializePasses.h"
59 #include "llvm/Pass.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/raw_ostream.h"
63 #include "llvm/Transforms/Scalar.h"
64 #include "llvm/Transforms/Utils.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "loop-fusion"
70 
71 STATISTIC(FuseCounter, "Loops fused");
72 STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
73 STATISTIC(InvalidPreheader, "Loop has invalid preheader");
74 STATISTIC(InvalidHeader, "Loop has invalid header");
75 STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks");
76 STATISTIC(InvalidExitBlock, "Loop has invalid exit block");
77 STATISTIC(InvalidLatch, "Loop has invalid latch");
78 STATISTIC(InvalidLoop, "Loop is invalid");
79 STATISTIC(AddressTakenBB, "Basic block has address taken");
80 STATISTIC(MayThrowException, "Loop may throw an exception");
81 STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
82 STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
83 STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
84 STATISTIC(UnknownTripCount, "Loop has unknown trip count");
85 STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
86 STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
87 STATISTIC(NonAdjacent, "Loops are not adjacent");
88 STATISTIC(NonEmptyPreheader, "Loop has a non-empty preheader");
89 STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
90 STATISTIC(NonIdenticalGuards, "Candidates have different guards");
91 STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block");
92 STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block");
93 
94 enum FusionDependenceAnalysisChoice {
95   FUSION_DEPENDENCE_ANALYSIS_SCEV,
96   FUSION_DEPENDENCE_ANALYSIS_DA,
97   FUSION_DEPENDENCE_ANALYSIS_ALL,
98 };
99 
100 static cl::opt<FusionDependenceAnalysisChoice> FusionDependenceAnalysis(
101     "loop-fusion-dependence-analysis",
102     cl::desc("Which dependence analysis should loop fusion use?"),
103     cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev",
104                           "Use the scalar evolution interface"),
105                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da",
106                           "Use the dependence analysis interface"),
107                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all",
108                           "Use all available analyses")),
109     cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL), cl::ZeroOrMore);
110 
111 #ifndef NDEBUG
112 static cl::opt<bool>
113     VerboseFusionDebugging("loop-fusion-verbose-debug",
114                            cl::desc("Enable verbose debugging for Loop Fusion"),
115                            cl::Hidden, cl::init(false), cl::ZeroOrMore);
116 #endif
117 
118 namespace {
119 /// This class is used to represent a candidate for loop fusion. When it is
120 /// constructed, it checks the conditions for loop fusion to ensure that it
121 /// represents a valid candidate. It caches several parts of a loop that are
122 /// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
123 /// of continually querying the underlying Loop to retrieve these values. It is
124 /// assumed these will not change throughout loop fusion.
125 ///
126 /// The invalidate method should be used to indicate that the FusionCandidate is
127 /// no longer a valid candidate for fusion. Similarly, the isValid() method can
128 /// be used to ensure that the FusionCandidate is still valid for fusion.
129 struct FusionCandidate {
130   /// Cache of parts of the loop used throughout loop fusion. These should not
131   /// need to change throughout the analysis and transformation.
132   /// These parts are cached to avoid repeatedly looking up in the Loop class.
133 
134   /// Preheader of the loop this candidate represents
135   BasicBlock *Preheader;
136   /// Header of the loop this candidate represents
137   BasicBlock *Header;
138   /// Blocks in the loop that exit the loop
139   BasicBlock *ExitingBlock;
140   /// The successor block of this loop (where the exiting blocks go to)
141   BasicBlock *ExitBlock;
142   /// Latch of the loop
143   BasicBlock *Latch;
144   /// The loop that this fusion candidate represents
145   Loop *L;
146   /// Vector of instructions in this loop that read from memory
147   SmallVector<Instruction *, 16> MemReads;
148   /// Vector of instructions in this loop that write to memory
149   SmallVector<Instruction *, 16> MemWrites;
150   /// Are all of the members of this fusion candidate still valid
151   bool Valid;
152   /// Guard branch of the loop, if it exists
153   BranchInst *GuardBranch;
154 
155   /// Dominator and PostDominator trees are needed for the
156   /// FusionCandidateCompare function, required by FusionCandidateSet to
157   /// determine where the FusionCandidate should be inserted into the set. These
158   /// are used to establish ordering of the FusionCandidates based on dominance.
159   const DominatorTree *DT;
160   const PostDominatorTree *PDT;
161 
162   OptimizationRemarkEmitter &ORE;
163 
164   FusionCandidate(Loop *L, const DominatorTree *DT,
165                   const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE)
166       : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
167         ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
168         Latch(L->getLoopLatch()), L(L), Valid(true), GuardBranch(nullptr),
169         DT(DT), PDT(PDT), ORE(ORE) {
170 
171     // TODO: This is temporary while we fuse both rotated and non-rotated
172     // loops. Once we switch to only fusing rotated loops, the initialization of
173     // GuardBranch can be moved into the initialization list above.
174     if (isRotated())
175       GuardBranch = L->getLoopGuardBranch();
176 
177     // Walk over all blocks in the loop and check for conditions that may
178     // prevent fusion. For each block, walk over all instructions and collect
179     // the memory reads and writes If any instructions that prevent fusion are
180     // found, invalidate this object and return.
181     for (BasicBlock *BB : L->blocks()) {
182       if (BB->hasAddressTaken()) {
183         invalidate();
184         reportInvalidCandidate(AddressTakenBB);
185         return;
186       }
187 
188       for (Instruction &I : *BB) {
189         if (I.mayThrow()) {
190           invalidate();
191           reportInvalidCandidate(MayThrowException);
192           return;
193         }
194         if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
195           if (SI->isVolatile()) {
196             invalidate();
197             reportInvalidCandidate(ContainsVolatileAccess);
198             return;
199           }
200         }
201         if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
202           if (LI->isVolatile()) {
203             invalidate();
204             reportInvalidCandidate(ContainsVolatileAccess);
205             return;
206           }
207         }
208         if (I.mayWriteToMemory())
209           MemWrites.push_back(&I);
210         if (I.mayReadFromMemory())
211           MemReads.push_back(&I);
212       }
213     }
214   }
215 
216   /// Check if all members of the class are valid.
217   bool isValid() const {
218     return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
219            !L->isInvalid() && Valid;
220   }
221 
222   /// Verify that all members are in sync with the Loop object.
223   void verify() const {
224     assert(isValid() && "Candidate is not valid!!");
225     assert(!L->isInvalid() && "Loop is invalid!");
226     assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
227     assert(Header == L->getHeader() && "Header is out of sync");
228     assert(ExitingBlock == L->getExitingBlock() &&
229            "Exiting Blocks is out of sync");
230     assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
231     assert(Latch == L->getLoopLatch() && "Latch is out of sync");
232   }
233 
234   /// Get the entry block for this fusion candidate.
235   ///
236   /// If this fusion candidate represents a guarded loop, the entry block is the
237   /// loop guard block. If it represents an unguarded loop, the entry block is
238   /// the preheader of the loop.
239   BasicBlock *getEntryBlock() const {
240     if (GuardBranch)
241       return GuardBranch->getParent();
242     else
243       return Preheader;
244   }
245 
246   /// Given a guarded loop, get the successor of the guard that is not in the
247   /// loop.
248   ///
249   /// This method returns the successor of the loop guard that is not located
250   /// within the loop (i.e., the successor of the guard that is not the
251   /// preheader).
252   /// This method is only valid for guarded loops.
253   BasicBlock *getNonLoopBlock() const {
254     assert(GuardBranch && "Only valid on guarded loops.");
255     assert(GuardBranch->isConditional() &&
256            "Expecting guard to be a conditional branch.");
257     return (GuardBranch->getSuccessor(0) == Preheader)
258                ? GuardBranch->getSuccessor(1)
259                : GuardBranch->getSuccessor(0);
260   }
261 
262   bool isRotated() const {
263     assert(L && "Expecting loop to be valid.");
264     assert(Latch && "Expecting latch to be valid.");
265     return L->isLoopExiting(Latch);
266   }
267 
268 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
269   LLVM_DUMP_METHOD void dump() const {
270     dbgs() << "\tGuardBranch: "
271            << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
272            << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
273            << "\n"
274            << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
275            << "\tExitingBB: "
276            << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
277            << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
278            << "\n"
279            << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
280            << "\tEntryBlock: "
281            << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
282            << "\n";
283   }
284 #endif
285 
286   /// Determine if a fusion candidate (representing a loop) is eligible for
287   /// fusion. Note that this only checks whether a single loop can be fused - it
288   /// does not check whether it is *legal* to fuse two loops together.
289   bool isEligibleForFusion(ScalarEvolution &SE) const {
290     if (!isValid()) {
291       LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
292       if (!Preheader)
293         ++InvalidPreheader;
294       if (!Header)
295         ++InvalidHeader;
296       if (!ExitingBlock)
297         ++InvalidExitingBlock;
298       if (!ExitBlock)
299         ++InvalidExitBlock;
300       if (!Latch)
301         ++InvalidLatch;
302       if (L->isInvalid())
303         ++InvalidLoop;
304 
305       return false;
306     }
307 
308     // Require ScalarEvolution to be able to determine a trip count.
309     if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
310       LLVM_DEBUG(dbgs() << "Loop " << L->getName()
311                         << " trip count not computable!\n");
312       return reportInvalidCandidate(UnknownTripCount);
313     }
314 
315     if (!L->isLoopSimplifyForm()) {
316       LLVM_DEBUG(dbgs() << "Loop " << L->getName()
317                         << " is not in simplified form!\n");
318       return reportInvalidCandidate(NotSimplifiedForm);
319     }
320 
321     return true;
322   }
323 
324 private:
325   // This is only used internally for now, to clear the MemWrites and MemReads
326   // list and setting Valid to false. I can't envision other uses of this right
327   // now, since once FusionCandidates are put into the FusionCandidateSet they
328   // are immutable. Thus, any time we need to change/update a FusionCandidate,
329   // we must create a new one and insert it into the FusionCandidateSet to
330   // ensure the FusionCandidateSet remains ordered correctly.
331   void invalidate() {
332     MemWrites.clear();
333     MemReads.clear();
334     Valid = false;
335   }
336 
337   bool reportInvalidCandidate(llvm::Statistic &Stat) const {
338     using namespace ore;
339     assert(L && Preheader && "Fusion candidate not initialized properly!");
340     ++Stat;
341     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
342                                         L->getStartLoc(), Preheader)
343              << "[" << Preheader->getParent()->getName() << "]: "
344              << "Loop is not a candidate for fusion: " << Stat.getDesc());
345     return false;
346   }
347 };
348 
349 struct FusionCandidateCompare {
350   /// Comparison functor to sort two Control Flow Equivalent fusion candidates
351   /// into dominance order.
352   /// If LHS dominates RHS and RHS post-dominates LHS, return true;
353   /// IF RHS dominates LHS and LHS post-dominates RHS, return false;
354   bool operator()(const FusionCandidate &LHS,
355                   const FusionCandidate &RHS) const {
356     const DominatorTree *DT = LHS.DT;
357 
358     BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
359     BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
360 
361     // Do not save PDT to local variable as it is only used in asserts and thus
362     // will trigger an unused variable warning if building without asserts.
363     assert(DT && LHS.PDT && "Expecting valid dominator tree");
364 
365     // Do this compare first so if LHS == RHS, function returns false.
366     if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) {
367       // RHS dominates LHS
368       // Verify LHS post-dominates RHS
369       assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
370       return false;
371     }
372 
373     if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) {
374       // Verify RHS Postdominates LHS
375       assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
376       return true;
377     }
378 
379     // If LHS does not dominate RHS and RHS does not dominate LHS then there is
380     // no dominance relationship between the two FusionCandidates. Thus, they
381     // should not be in the same set together.
382     llvm_unreachable(
383         "No dominance relationship between these fusion candidates!");
384   }
385 };
386 
387 using LoopVector = SmallVector<Loop *, 4>;
388 
389 // Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance
390 // order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0
391 // dominates FC1 and FC1 post-dominates FC0.
392 // std::set was chosen because we want a sorted data structure with stable
393 // iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent
394 // loops by moving intervening code around. When this intervening code contains
395 // loops, those loops will be moved also. The corresponding FusionCandidates
396 // will also need to be moved accordingly. As this is done, having stable
397 // iterators will simplify the logic. Similarly, having an efficient insert that
398 // keeps the FusionCandidateSet sorted will also simplify the implementation.
399 using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
400 using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
401 
402 #if !defined(NDEBUG)
403 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
404                                      const FusionCandidate &FC) {
405   if (FC.isValid())
406     OS << FC.Preheader->getName();
407   else
408     OS << "<Invalid>";
409 
410   return OS;
411 }
412 
413 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
414                                      const FusionCandidateSet &CandSet) {
415   for (const FusionCandidate &FC : CandSet)
416     OS << FC << '\n';
417 
418   return OS;
419 }
420 
421 static void
422 printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
423   dbgs() << "Fusion Candidates: \n";
424   for (const auto &CandidateSet : FusionCandidates) {
425     dbgs() << "*** Fusion Candidate Set ***\n";
426     dbgs() << CandidateSet;
427     dbgs() << "****************************\n";
428   }
429 }
430 #endif
431 
432 /// Collect all loops in function at the same nest level, starting at the
433 /// outermost level.
434 ///
435 /// This data structure collects all loops at the same nest level for a
436 /// given function (specified by the LoopInfo object). It starts at the
437 /// outermost level.
438 struct LoopDepthTree {
439   using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
440   using iterator = LoopsOnLevelTy::iterator;
441   using const_iterator = LoopsOnLevelTy::const_iterator;
442 
443   LoopDepthTree(LoopInfo &LI) : Depth(1) {
444     if (!LI.empty())
445       LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
446   }
447 
448   /// Test whether a given loop has been removed from the function, and thus is
449   /// no longer valid.
450   bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
451 
452   /// Record that a given loop has been removed from the function and is no
453   /// longer valid.
454   void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
455 
456   /// Descend the tree to the next (inner) nesting level
457   void descend() {
458     LoopsOnLevelTy LoopsOnNextLevel;
459 
460     for (const LoopVector &LV : *this)
461       for (Loop *L : LV)
462         if (!isRemovedLoop(L) && L->begin() != L->end())
463           LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
464 
465     LoopsOnLevel = LoopsOnNextLevel;
466     RemovedLoops.clear();
467     Depth++;
468   }
469 
470   bool empty() const { return size() == 0; }
471   size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
472   unsigned getDepth() const { return Depth; }
473 
474   iterator begin() { return LoopsOnLevel.begin(); }
475   iterator end() { return LoopsOnLevel.end(); }
476   const_iterator begin() const { return LoopsOnLevel.begin(); }
477   const_iterator end() const { return LoopsOnLevel.end(); }
478 
479 private:
480   /// Set of loops that have been removed from the function and are no longer
481   /// valid.
482   SmallPtrSet<const Loop *, 8> RemovedLoops;
483 
484   /// Depth of the current level, starting at 1 (outermost loops).
485   unsigned Depth;
486 
487   /// Vector of loops at the current depth level that have the same parent loop
488   LoopsOnLevelTy LoopsOnLevel;
489 };
490 
491 #ifndef NDEBUG
492 static void printLoopVector(const LoopVector &LV) {
493   dbgs() << "****************************\n";
494   for (auto L : LV)
495     printLoop(*L, dbgs());
496   dbgs() << "****************************\n";
497 }
498 #endif
499 
500 struct LoopFuser {
501 private:
502   // Sets of control flow equivalent fusion candidates for a given nest level.
503   FusionCandidateCollection FusionCandidates;
504 
505   LoopDepthTree LDT;
506   DomTreeUpdater DTU;
507 
508   LoopInfo &LI;
509   DominatorTree &DT;
510   DependenceInfo &DI;
511   ScalarEvolution &SE;
512   PostDominatorTree &PDT;
513   OptimizationRemarkEmitter &ORE;
514 
515 public:
516   LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
517             ScalarEvolution &SE, PostDominatorTree &PDT,
518             OptimizationRemarkEmitter &ORE, const DataLayout &DL)
519       : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
520         DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE) {}
521 
522   /// This is the main entry point for loop fusion. It will traverse the
523   /// specified function and collect candidate loops to fuse, starting at the
524   /// outermost nesting level and working inwards.
525   bool fuseLoops(Function &F) {
526 #ifndef NDEBUG
527     if (VerboseFusionDebugging) {
528       LI.print(dbgs());
529     }
530 #endif
531 
532     LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
533                       << "\n");
534     bool Changed = false;
535 
536     while (!LDT.empty()) {
537       LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
538                         << LDT.getDepth() << "\n";);
539 
540       for (const LoopVector &LV : LDT) {
541         assert(LV.size() > 0 && "Empty loop set was build!");
542 
543         // Skip singleton loop sets as they do not offer fusion opportunities on
544         // this level.
545         if (LV.size() == 1)
546           continue;
547 #ifndef NDEBUG
548         if (VerboseFusionDebugging) {
549           LLVM_DEBUG({
550             dbgs() << "  Visit loop set (#" << LV.size() << "):\n";
551             printLoopVector(LV);
552           });
553         }
554 #endif
555 
556         collectFusionCandidates(LV);
557         Changed |= fuseCandidates();
558       }
559 
560       // Finished analyzing candidates at this level.
561       // Descend to the next level and clear all of the candidates currently
562       // collected. Note that it will not be possible to fuse any of the
563       // existing candidates with new candidates because the new candidates will
564       // be at a different nest level and thus not be control flow equivalent
565       // with all of the candidates collected so far.
566       LLVM_DEBUG(dbgs() << "Descend one level!\n");
567       LDT.descend();
568       FusionCandidates.clear();
569     }
570 
571     if (Changed)
572       LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
573 
574 #ifndef NDEBUG
575     assert(DT.verify());
576     assert(PDT.verify());
577     LI.verify(DT);
578     SE.verify();
579 #endif
580 
581     LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
582     return Changed;
583   }
584 
585 private:
586   /// Determine if two fusion candidates are control flow equivalent.
587   ///
588   /// Two fusion candidates are control flow equivalent if when one executes,
589   /// the other is guaranteed to execute. This is determined using dominators
590   /// and post-dominators: if A dominates B and B post-dominates A then A and B
591   /// are control-flow equivalent.
592   bool isControlFlowEquivalent(const FusionCandidate &FC0,
593                                const FusionCandidate &FC1) const {
594     assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
595 
596     BasicBlock *FC0EntryBlock = FC0.getEntryBlock();
597     BasicBlock *FC1EntryBlock = FC1.getEntryBlock();
598 
599     if (DT.dominates(FC0EntryBlock, FC1EntryBlock))
600       return PDT.dominates(FC1EntryBlock, FC0EntryBlock);
601 
602     if (DT.dominates(FC1EntryBlock, FC0EntryBlock))
603       return PDT.dominates(FC0EntryBlock, FC1EntryBlock);
604 
605     return false;
606   }
607 
608   /// Iterate over all loops in the given loop set and identify the loops that
609   /// are eligible for fusion. Place all eligible fusion candidates into Control
610   /// Flow Equivalent sets, sorted by dominance.
611   void collectFusionCandidates(const LoopVector &LV) {
612     for (Loop *L : LV) {
613       FusionCandidate CurrCand(L, &DT, &PDT, ORE);
614       if (!CurrCand.isEligibleForFusion(SE))
615         continue;
616 
617       // Go through each list in FusionCandidates and determine if L is control
618       // flow equivalent with the first loop in that list. If it is, append LV.
619       // If not, go to the next list.
620       // If no suitable list is found, start another list and add it to
621       // FusionCandidates.
622       bool FoundSet = false;
623 
624       for (auto &CurrCandSet : FusionCandidates) {
625         if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
626           CurrCandSet.insert(CurrCand);
627           FoundSet = true;
628 #ifndef NDEBUG
629           if (VerboseFusionDebugging)
630             LLVM_DEBUG(dbgs() << "Adding " << CurrCand
631                               << " to existing candidate set\n");
632 #endif
633           break;
634         }
635       }
636       if (!FoundSet) {
637         // No set was found. Create a new set and add to FusionCandidates
638 #ifndef NDEBUG
639         if (VerboseFusionDebugging)
640           LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
641 #endif
642         FusionCandidateSet NewCandSet;
643         NewCandSet.insert(CurrCand);
644         FusionCandidates.push_back(NewCandSet);
645       }
646       NumFusionCandidates++;
647     }
648   }
649 
650   /// Determine if it is beneficial to fuse two loops.
651   ///
652   /// For now, this method simply returns true because we want to fuse as much
653   /// as possible (primarily to test the pass). This method will evolve, over
654   /// time, to add heuristics for profitability of fusion.
655   bool isBeneficialFusion(const FusionCandidate &FC0,
656                           const FusionCandidate &FC1) {
657     return true;
658   }
659 
660   /// Determine if two fusion candidates have the same trip count (i.e., they
661   /// execute the same number of iterations).
662   ///
663   /// Note that for now this method simply returns a boolean value because there
664   /// are no mechanisms in loop fusion to handle different trip counts. In the
665   /// future, this behaviour can be extended to adjust one of the loops to make
666   /// the trip counts equal (e.g., loop peeling). When this is added, this
667   /// interface may need to change to return more information than just a
668   /// boolean value.
669   bool identicalTripCounts(const FusionCandidate &FC0,
670                            const FusionCandidate &FC1) const {
671     const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
672     if (isa<SCEVCouldNotCompute>(TripCount0)) {
673       UncomputableTripCount++;
674       LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
675       return false;
676     }
677 
678     const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
679     if (isa<SCEVCouldNotCompute>(TripCount1)) {
680       UncomputableTripCount++;
681       LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
682       return false;
683     }
684     LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
685                       << *TripCount1 << " are "
686                       << (TripCount0 == TripCount1 ? "identical" : "different")
687                       << "\n");
688 
689     return (TripCount0 == TripCount1);
690   }
691 
692   /// Walk each set of control flow equivalent fusion candidates and attempt to
693   /// fuse them. This does a single linear traversal of all candidates in the
694   /// set. The conditions for legal fusion are checked at this point. If a pair
695   /// of fusion candidates passes all legality checks, they are fused together
696   /// and a new fusion candidate is created and added to the FusionCandidateSet.
697   /// The original fusion candidates are then removed, as they are no longer
698   /// valid.
699   bool fuseCandidates() {
700     bool Fused = false;
701     LLVM_DEBUG(printFusionCandidates(FusionCandidates));
702     for (auto &CandidateSet : FusionCandidates) {
703       if (CandidateSet.size() < 2)
704         continue;
705 
706       LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
707                         << CandidateSet << "\n");
708 
709       for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
710         assert(!LDT.isRemovedLoop(FC0->L) &&
711                "Should not have removed loops in CandidateSet!");
712         auto FC1 = FC0;
713         for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
714           assert(!LDT.isRemovedLoop(FC1->L) &&
715                  "Should not have removed loops in CandidateSet!");
716 
717           LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
718                      dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
719 
720           FC0->verify();
721           FC1->verify();
722 
723           if (!identicalTripCounts(*FC0, *FC1)) {
724             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
725                                  "counts. Not fusing.\n");
726             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
727                                                        NonEqualTripCount);
728             continue;
729           }
730 
731           if (!isAdjacent(*FC0, *FC1)) {
732             LLVM_DEBUG(dbgs()
733                        << "Fusion candidates are not adjacent. Not fusing.\n");
734             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
735             continue;
736           }
737 
738           // Ensure that FC0 and FC1 have identical guards.
739           // If one (or both) are not guarded, this check is not necessary.
740           if (FC0->GuardBranch && FC1->GuardBranch &&
741               !haveIdenticalGuards(*FC0, *FC1)) {
742             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
743                                  "guards. Not Fusing.\n");
744             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
745                                                        NonIdenticalGuards);
746             continue;
747           }
748 
749           // The following three checks look for empty blocks in FC0 and FC1. If
750           // any of these blocks are non-empty, we do not fuse. This is done
751           // because we currently do not have the safety checks to determine if
752           // it is safe to move the blocks past other blocks in the loop. Once
753           // these checks are added, these conditions can be relaxed.
754           if (!isEmptyPreheader(*FC1)) {
755             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty "
756                                  "preheader. Not fusing.\n");
757             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
758                                                        NonEmptyPreheader);
759             continue;
760           }
761 
762           if (FC0->GuardBranch && !isEmptyExitBlock(*FC0)) {
763             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty exit "
764                                  "block. Not fusing.\n");
765             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
766                                                        NonEmptyExitBlock);
767             continue;
768           }
769 
770           if (FC1->GuardBranch && !isEmptyGuardBlock(*FC1)) {
771             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty guard "
772                                  "block. Not fusing.\n");
773             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
774                                                        NonEmptyGuardBlock);
775             continue;
776           }
777 
778           // Check the dependencies across the loops and do not fuse if it would
779           // violate them.
780           if (!dependencesAllowFusion(*FC0, *FC1)) {
781             LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
782             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
783                                                        InvalidDependencies);
784             continue;
785           }
786 
787           bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
788           LLVM_DEBUG(dbgs()
789                      << "\tFusion appears to be "
790                      << (BeneficialToFuse ? "" : "un") << "profitable!\n");
791           if (!BeneficialToFuse) {
792             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
793                                                        FusionNotBeneficial);
794             continue;
795           }
796           // All analysis has completed and has determined that fusion is legal
797           // and profitable. At this point, start transforming the code and
798           // perform fusion.
799 
800           LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
801                             << *FC1 << "\n");
802 
803           // Report fusion to the Optimization Remarks.
804           // Note this needs to be done *before* performFusion because
805           // performFusion will change the original loops, making it not
806           // possible to identify them after fusion is complete.
807           reportLoopFusion<OptimizationRemark>(*FC0, *FC1, FuseCounter);
808 
809           FusionCandidate FusedCand(performFusion(*FC0, *FC1), &DT, &PDT, ORE);
810           FusedCand.verify();
811           assert(FusedCand.isEligibleForFusion(SE) &&
812                  "Fused candidate should be eligible for fusion!");
813 
814           // Notify the loop-depth-tree that these loops are not valid objects
815           LDT.removeLoop(FC1->L);
816 
817           CandidateSet.erase(FC0);
818           CandidateSet.erase(FC1);
819 
820           auto InsertPos = CandidateSet.insert(FusedCand);
821 
822           assert(InsertPos.second &&
823                  "Unable to insert TargetCandidate in CandidateSet!");
824 
825           // Reset FC0 and FC1 the new (fused) candidate. Subsequent iterations
826           // of the FC1 loop will attempt to fuse the new (fused) loop with the
827           // remaining candidates in the current candidate set.
828           FC0 = FC1 = InsertPos.first;
829 
830           LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet
831                             << "\n");
832 
833           Fused = true;
834         }
835       }
836     }
837     return Fused;
838   }
839 
840   /// Rewrite all additive recurrences in a SCEV to use a new loop.
841   class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> {
842   public:
843     AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL,
844                        bool UseMax = true)
845         : SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL),
846           NewL(NewL) {}
847 
848     const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
849       const Loop *ExprL = Expr->getLoop();
850       SmallVector<const SCEV *, 2> Operands;
851       if (ExprL == &OldL) {
852         Operands.append(Expr->op_begin(), Expr->op_end());
853         return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags());
854       }
855 
856       if (OldL.contains(ExprL)) {
857         bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE));
858         if (!UseMax || !Pos || !Expr->isAffine()) {
859           Valid = false;
860           return Expr;
861         }
862         return visit(Expr->getStart());
863       }
864 
865       for (const SCEV *Op : Expr->operands())
866         Operands.push_back(visit(Op));
867       return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags());
868     }
869 
870     bool wasValidSCEV() const { return Valid; }
871 
872   private:
873     bool Valid, UseMax;
874     const Loop &OldL, &NewL;
875   };
876 
877   /// Return false if the access functions of \p I0 and \p I1 could cause
878   /// a negative dependence.
879   bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0,
880                             Instruction &I1, bool EqualIsInvalid) {
881     Value *Ptr0 = getLoadStorePointerOperand(&I0);
882     Value *Ptr1 = getLoadStorePointerOperand(&I1);
883     if (!Ptr0 || !Ptr1)
884       return false;
885 
886     const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
887     const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
888 #ifndef NDEBUG
889     if (VerboseFusionDebugging)
890       LLVM_DEBUG(dbgs() << "    Access function check: " << *SCEVPtr0 << " vs "
891                         << *SCEVPtr1 << "\n");
892 #endif
893     AddRecLoopReplacer Rewriter(SE, L0, L1);
894     SCEVPtr0 = Rewriter.visit(SCEVPtr0);
895 #ifndef NDEBUG
896     if (VerboseFusionDebugging)
897       LLVM_DEBUG(dbgs() << "    Access function after rewrite: " << *SCEVPtr0
898                         << " [Valid: " << Rewriter.wasValidSCEV() << "]\n");
899 #endif
900     if (!Rewriter.wasValidSCEV())
901       return false;
902 
903     // TODO: isKnownPredicate doesnt work well when one SCEV is loop carried (by
904     //       L0) and the other is not. We could check if it is monotone and test
905     //       the beginning and end value instead.
906 
907     BasicBlock *L0Header = L0.getHeader();
908     auto HasNonLinearDominanceRelation = [&](const SCEV *S) {
909       const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S);
910       if (!AddRec)
911         return false;
912       return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) &&
913              !DT.dominates(AddRec->getLoop()->getHeader(), L0Header);
914     };
915     if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation))
916       return false;
917 
918     ICmpInst::Predicate Pred =
919         EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
920     bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
921 #ifndef NDEBUG
922     if (VerboseFusionDebugging)
923       LLVM_DEBUG(dbgs() << "    Relation: " << *SCEVPtr0
924                         << (IsAlwaysGE ? "  >=  " : "  may <  ") << *SCEVPtr1
925                         << "\n");
926 #endif
927     return IsAlwaysGE;
928   }
929 
930   /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
931   /// @p L1) allow loop fusion of @p L0 and @p L1. The dependence analyses
932   /// specified by @p DepChoice are used to determine this.
933   bool dependencesAllowFusion(const FusionCandidate &FC0,
934                               const FusionCandidate &FC1, Instruction &I0,
935                               Instruction &I1, bool AnyDep,
936                               FusionDependenceAnalysisChoice DepChoice) {
937 #ifndef NDEBUG
938     if (VerboseFusionDebugging) {
939       LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : "
940                         << DepChoice << "\n");
941     }
942 #endif
943     switch (DepChoice) {
944     case FUSION_DEPENDENCE_ANALYSIS_SCEV:
945       return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
946     case FUSION_DEPENDENCE_ANALYSIS_DA: {
947       auto DepResult = DI.depends(&I0, &I1, true);
948       if (!DepResult)
949         return true;
950 #ifndef NDEBUG
951       if (VerboseFusionDebugging) {
952         LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
953                    dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
954                           << (DepResult->isOrdered() ? "true" : "false")
955                           << "]\n");
956         LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
957                           << "\n");
958       }
959 #endif
960 
961       if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
962         LLVM_DEBUG(
963             dbgs() << "TODO: Implement pred/succ dependence handling!\n");
964 
965       // TODO: Can we actually use the dependence info analysis here?
966       return false;
967     }
968 
969     case FUSION_DEPENDENCE_ANALYSIS_ALL:
970       return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
971                                     FUSION_DEPENDENCE_ANALYSIS_SCEV) ||
972              dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
973                                     FUSION_DEPENDENCE_ANALYSIS_DA);
974     }
975 
976     llvm_unreachable("Unknown fusion dependence analysis choice!");
977   }
978 
979   /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
980   bool dependencesAllowFusion(const FusionCandidate &FC0,
981                               const FusionCandidate &FC1) {
982     LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
983                       << "\n");
984     assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
985     assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
986 
987     for (Instruction *WriteL0 : FC0.MemWrites) {
988       for (Instruction *WriteL1 : FC1.MemWrites)
989         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
990                                     /* AnyDep */ false,
991                                     FusionDependenceAnalysis)) {
992           InvalidDependencies++;
993           return false;
994         }
995       for (Instruction *ReadL1 : FC1.MemReads)
996         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
997                                     /* AnyDep */ false,
998                                     FusionDependenceAnalysis)) {
999           InvalidDependencies++;
1000           return false;
1001         }
1002     }
1003 
1004     for (Instruction *WriteL1 : FC1.MemWrites) {
1005       for (Instruction *WriteL0 : FC0.MemWrites)
1006         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
1007                                     /* AnyDep */ false,
1008                                     FusionDependenceAnalysis)) {
1009           InvalidDependencies++;
1010           return false;
1011         }
1012       for (Instruction *ReadL0 : FC0.MemReads)
1013         if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
1014                                     /* AnyDep */ false,
1015                                     FusionDependenceAnalysis)) {
1016           InvalidDependencies++;
1017           return false;
1018         }
1019     }
1020 
1021     // Walk through all uses in FC1. For each use, find the reaching def. If the
1022     // def is located in FC0 then it is is not safe to fuse.
1023     for (BasicBlock *BB : FC1.L->blocks())
1024       for (Instruction &I : *BB)
1025         for (auto &Op : I.operands())
1026           if (Instruction *Def = dyn_cast<Instruction>(Op))
1027             if (FC0.L->contains(Def->getParent())) {
1028               InvalidDependencies++;
1029               return false;
1030             }
1031 
1032     return true;
1033   }
1034 
1035   /// Determine if two fusion candidates are adjacent in the CFG.
1036   ///
1037   /// This method will determine if there are additional basic blocks in the CFG
1038   /// between the exit of \p FC0 and the entry of \p FC1.
1039   /// If the two candidates are guarded loops, then it checks whether the
1040   /// non-loop successor of the \p FC0 guard branch is the entry block of \p
1041   /// FC1. If not, then the loops are not adjacent. If the two candidates are
1042   /// not guarded loops, then it checks whether the exit block of \p FC0 is the
1043   /// preheader of \p FC1.
1044   bool isAdjacent(const FusionCandidate &FC0,
1045                   const FusionCandidate &FC1) const {
1046     // If the successor of the guard branch is FC1, then the loops are adjacent
1047     if (FC0.GuardBranch)
1048       return FC0.getNonLoopBlock() == FC1.getEntryBlock();
1049     else
1050       return FC0.ExitBlock == FC1.getEntryBlock();
1051   }
1052 
1053   /// Determine if two fusion candidates have identical guards
1054   ///
1055   /// This method will determine if two fusion candidates have the same guards.
1056   /// The guards are considered the same if:
1057   ///   1. The instructions to compute the condition used in the compare are
1058   ///      identical.
1059   ///   2. The successors of the guard have the same flow into/around the loop.
1060   /// If the compare instructions are identical, then the first successor of the
1061   /// guard must go to the same place (either the preheader of the loop or the
1062   /// NonLoopBlock). In other words, the the first successor of both loops must
1063   /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
1064   /// the NonLoopBlock). The same must be true for the second successor.
1065   bool haveIdenticalGuards(const FusionCandidate &FC0,
1066                            const FusionCandidate &FC1) const {
1067     assert(FC0.GuardBranch && FC1.GuardBranch &&
1068            "Expecting FC0 and FC1 to be guarded loops.");
1069 
1070     if (auto FC0CmpInst =
1071             dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
1072       if (auto FC1CmpInst =
1073               dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
1074         if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
1075           return false;
1076 
1077     // The compare instructions are identical.
1078     // Now make sure the successor of the guards have the same flow into/around
1079     // the loop
1080     if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1081       return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1082     else
1083       return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1084   }
1085 
1086   /// Check that the guard for \p FC *only* contains the cmp/branch for the
1087   /// guard.
1088   /// Once we are able to handle intervening code, any code in the guard block
1089   /// for FC1 will need to be treated as intervening code and checked whether
1090   /// it can safely move around the loops.
1091   bool isEmptyGuardBlock(const FusionCandidate &FC) const {
1092     assert(FC.GuardBranch && "Expecting a fusion candidate with guard branch.");
1093     if (auto *CmpInst = dyn_cast<Instruction>(FC.GuardBranch->getCondition())) {
1094       auto *GuardBlock = FC.GuardBranch->getParent();
1095       // If the generation of the cmp value is in GuardBlock, then the size of
1096       // the guard block should be 2 (cmp + branch). If the generation of the
1097       // cmp value is in a different block, then the size of the guard block
1098       // should only be 1.
1099       if (CmpInst->getParent() == GuardBlock)
1100         return GuardBlock->size() == 2;
1101       else
1102         return GuardBlock->size() == 1;
1103     }
1104 
1105     return false;
1106   }
1107 
1108   bool isEmptyPreheader(const FusionCandidate &FC) const {
1109     assert(FC.Preheader && "Expecting a valid preheader");
1110     return FC.Preheader->size() == 1;
1111   }
1112 
1113   bool isEmptyExitBlock(const FusionCandidate &FC) const {
1114     assert(FC.ExitBlock && "Expecting a valid exit block");
1115     return FC.ExitBlock->size() == 1;
1116   }
1117 
1118   /// Fuse two fusion candidates, creating a new fused loop.
1119   ///
1120   /// This method contains the mechanics of fusing two loops, represented by \p
1121   /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
1122   /// postdominates \p FC0 (making them control flow equivalent). It also
1123   /// assumes that the other conditions for fusion have been met: adjacent,
1124   /// identical trip counts, and no negative distance dependencies exist that
1125   /// would prevent fusion. Thus, there is no checking for these conditions in
1126   /// this method.
1127   ///
1128   /// Fusion is performed by rewiring the CFG to update successor blocks of the
1129   /// components of tho loop. Specifically, the following changes are done:
1130   ///
1131   ///   1. The preheader of \p FC1 is removed as it is no longer necessary
1132   ///   (because it is currently only a single statement block).
1133   ///   2. The latch of \p FC0 is modified to jump to the header of \p FC1.
1134   ///   3. The latch of \p FC1 i modified to jump to the header of \p FC0.
1135   ///   4. All blocks from \p FC1 are removed from FC1 and added to FC0.
1136   ///
1137   /// All of these modifications are done with dominator tree updates, thus
1138   /// keeping the dominator (and post dominator) information up-to-date.
1139   ///
1140   /// This can be improved in the future by actually merging blocks during
1141   /// fusion. For example, the preheader of \p FC1 can be merged with the
1142   /// preheader of \p FC0. This would allow loops with more than a single
1143   /// statement in the preheader to be fused. Similarly, the latch blocks of the
1144   /// two loops could also be fused into a single block. This will require
1145   /// analysis to prove it is safe to move the contents of the block past
1146   /// existing code, which currently has not been implemented.
1147   Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1148     assert(FC0.isValid() && FC1.isValid() &&
1149            "Expecting valid fusion candidates");
1150 
1151     LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
1152                dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
1153 
1154     // Fusing guarded loops is handled slightly differently than non-guarded
1155     // loops and has been broken out into a separate method instead of trying to
1156     // intersperse the logic within a single method.
1157     if (FC0.GuardBranch)
1158       return fuseGuardedLoops(FC0, FC1);
1159 
1160     assert(FC1.Preheader == FC0.ExitBlock);
1161     assert(FC1.Preheader->size() == 1 &&
1162            FC1.Preheader->getSingleSuccessor() == FC1.Header);
1163 
1164     // Remember the phi nodes originally in the header of FC0 in order to rewire
1165     // them later. However, this is only necessary if the new loop carried
1166     // values might not dominate the exiting branch. While we do not generally
1167     // test if this is the case but simply insert intermediate phi nodes, we
1168     // need to make sure these intermediate phi nodes have different
1169     // predecessors. To this end, we filter the special case where the exiting
1170     // block is the latch block of the first loop. Nothing needs to be done
1171     // anyway as all loop carried values dominate the latch and thereby also the
1172     // exiting branch.
1173     SmallVector<PHINode *, 8> OriginalFC0PHIs;
1174     if (FC0.ExitingBlock != FC0.Latch)
1175       for (PHINode &PHI : FC0.Header->phis())
1176         OriginalFC0PHIs.push_back(&PHI);
1177 
1178     // Replace incoming blocks for header PHIs first.
1179     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1180     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1181 
1182     // Then modify the control flow and update DT and PDT.
1183     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
1184 
1185     // The old exiting block of the first loop (FC0) has to jump to the header
1186     // of the second as we need to execute the code in the second header block
1187     // regardless of the trip count. That is, if the trip count is 0, so the
1188     // back edge is never taken, we still have to execute both loop headers,
1189     // especially (but not only!) if the second is a do-while style loop.
1190     // However, doing so might invalidate the phi nodes of the first loop as
1191     // the new values do only need to dominate their latch and not the exiting
1192     // predicate. To remedy this potential problem we always introduce phi
1193     // nodes in the header of the second loop later that select the loop carried
1194     // value, if the second header was reached through an old latch of the
1195     // first, or undef otherwise. This is sound as exiting the first implies the
1196     // second will exit too, __without__ taking the back-edge. [Their
1197     // trip-counts are equal after all.
1198     // KB: Would this sequence be simpler to just just make FC0.ExitingBlock go
1199     // to FC1.Header? I think this is basically what the three sequences are
1200     // trying to accomplish; however, doing this directly in the CFG may mean
1201     // the DT/PDT becomes invalid
1202     FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1203                                                          FC1.Header);
1204     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1205         DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1206     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1207         DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1208 
1209     // The pre-header of L1 is not necessary anymore.
1210     assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader));
1211     FC1.Preheader->getTerminator()->eraseFromParent();
1212     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1213     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1214         DominatorTree::Delete, FC1.Preheader, FC1.Header));
1215 
1216     // Moves the phi nodes from the second to the first loops header block.
1217     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1218       if (SE.isSCEVable(PHI->getType()))
1219         SE.forgetValue(PHI);
1220       if (PHI->hasNUsesOrMore(1))
1221         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1222       else
1223         PHI->eraseFromParent();
1224     }
1225 
1226     // Introduce new phi nodes in the second loop header to ensure
1227     // exiting the first and jumping to the header of the second does not break
1228     // the SSA property of the phis originally in the first loop. See also the
1229     // comment above.
1230     Instruction *L1HeaderIP = &FC1.Header->front();
1231     for (PHINode *LCPHI : OriginalFC0PHIs) {
1232       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1233       assert(L1LatchBBIdx >= 0 &&
1234              "Expected loop carried value to be rewired at this point!");
1235 
1236       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1237 
1238       PHINode *L1HeaderPHI = PHINode::Create(
1239           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
1240       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1241       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
1242                                FC0.ExitingBlock);
1243 
1244       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1245     }
1246 
1247     // Replace latch terminator destinations.
1248     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1249     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1250 
1251     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1252     // performed the updates above.
1253     if (FC0.Latch != FC0.ExitingBlock)
1254       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1255           DominatorTree::Insert, FC0.Latch, FC1.Header));
1256 
1257     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1258                                                        FC0.Latch, FC0.Header));
1259     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1260                                                        FC1.Latch, FC0.Header));
1261     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1262                                                        FC1.Latch, FC1.Header));
1263 
1264     // Update DT/PDT
1265     DTU.applyUpdates(TreeUpdates);
1266 
1267     LI.removeBlock(FC1.Preheader);
1268     DTU.deleteBB(FC1.Preheader);
1269     DTU.flush();
1270 
1271     // Is there a way to keep SE up-to-date so we don't need to forget the loops
1272     // and rebuild the information in subsequent passes of fusion?
1273     SE.forgetLoop(FC1.L);
1274     SE.forgetLoop(FC0.L);
1275 
1276     // Merge the loops.
1277     SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(),
1278                                         FC1.L->block_end());
1279     for (BasicBlock *BB : Blocks) {
1280       FC0.L->addBlockEntry(BB);
1281       FC1.L->removeBlockFromLoop(BB);
1282       if (LI.getLoopFor(BB) != FC1.L)
1283         continue;
1284       LI.changeLoopFor(BB, FC0.L);
1285     }
1286     while (!FC1.L->empty()) {
1287       const auto &ChildLoopIt = FC1.L->begin();
1288       Loop *ChildLoop = *ChildLoopIt;
1289       FC1.L->removeChildLoop(ChildLoopIt);
1290       FC0.L->addChildLoop(ChildLoop);
1291     }
1292 
1293     // Delete the now empty loop L1.
1294     LI.erase(FC1.L);
1295 
1296 #ifndef NDEBUG
1297     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1298     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1299     assert(PDT.verify());
1300     LI.verify(DT);
1301     SE.verify();
1302 #endif
1303 
1304     LLVM_DEBUG(dbgs() << "Fusion done:\n");
1305 
1306     return FC0.L;
1307   }
1308 
1309   /// Report details on loop fusion opportunities.
1310   ///
1311   /// This template function can be used to report both successful and missed
1312   /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
1313   /// be one of:
1314   ///   - OptimizationRemarkMissed to report when loop fusion is unsuccessful
1315   ///     given two valid fusion candidates.
1316   ///   - OptimizationRemark to report successful fusion of two fusion
1317   ///     candidates.
1318   /// The remarks will be printed using the form:
1319   ///    <path/filename>:<line number>:<column number>: [<function name>]:
1320   ///       <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
1321   template <typename RemarkKind>
1322   void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
1323                         llvm::Statistic &Stat) {
1324     assert(FC0.Preheader && FC1.Preheader &&
1325            "Expecting valid fusion candidates");
1326     using namespace ore;
1327     ++Stat;
1328     ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
1329                         FC0.Preheader)
1330              << "[" << FC0.Preheader->getParent()->getName()
1331              << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
1332              << " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
1333              << ": " << Stat.getDesc());
1334   }
1335 
1336   /// Fuse two guarded fusion candidates, creating a new fused loop.
1337   ///
1338   /// Fusing guarded loops is handled much the same way as fusing non-guarded
1339   /// loops. The rewiring of the CFG is slightly different though, because of
1340   /// the presence of the guards around the loops and the exit blocks after the
1341   /// loop body. As such, the new loop is rewired as follows:
1342   ///    1. Keep the guard branch from FC0 and use the non-loop block target
1343   /// from the FC1 guard branch.
1344   ///    2. Remove the exit block from FC0 (this exit block should be empty
1345   /// right now).
1346   ///    3. Remove the guard branch for FC1
1347   ///    4. Remove the preheader for FC1.
1348   /// The exit block successor for the latch of FC0 is updated to be the header
1349   /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
1350   /// be the header of FC0, thus creating the fused loop.
1351   Loop *fuseGuardedLoops(const FusionCandidate &FC0,
1352                          const FusionCandidate &FC1) {
1353     assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
1354 
1355     BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1356     BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1357     BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1358     BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1359 
1360     assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
1361 
1362     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
1363 
1364     ////////////////////////////////////////////////////////////////////////////
1365     // Update the Loop Guard
1366     ////////////////////////////////////////////////////////////////////////////
1367     // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
1368     // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
1369     // Thus, one path from the guard goes to the preheader for FC0 (and thus
1370     // executes the new fused loop) and the other path goes to the NonLoopBlock
1371     // for FC1 (where FC1 guard would have gone if FC1 was not executed).
1372     FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1373     FC0.ExitBlock->getTerminator()->replaceUsesOfWith(FC1GuardBlock,
1374                                                       FC1.Header);
1375 
1376     // The guard of FC1 is not necessary anymore.
1377     FC1.GuardBranch->eraseFromParent();
1378     new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
1379 
1380     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1381         DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1382     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1383         DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1384     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1385         DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1386     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1387         DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1388 
1389     assert(pred_begin(FC1GuardBlock) == pred_end(FC1GuardBlock) &&
1390            "Expecting guard block to have no predecessors");
1391     assert(succ_begin(FC1GuardBlock) == succ_end(FC1GuardBlock) &&
1392            "Expecting guard block to have no successors");
1393 
1394     // Remember the phi nodes originally in the header of FC0 in order to rewire
1395     // them later. However, this is only necessary if the new loop carried
1396     // values might not dominate the exiting branch. While we do not generally
1397     // test if this is the case but simply insert intermediate phi nodes, we
1398     // need to make sure these intermediate phi nodes have different
1399     // predecessors. To this end, we filter the special case where the exiting
1400     // block is the latch block of the first loop. Nothing needs to be done
1401     // anyway as all loop carried values dominate the latch and thereby also the
1402     // exiting branch.
1403     // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
1404     // (because the loops are rotated. Thus, nothing will ever be added to
1405     // OriginalFC0PHIs.
1406     SmallVector<PHINode *, 8> OriginalFC0PHIs;
1407     if (FC0.ExitingBlock != FC0.Latch)
1408       for (PHINode &PHI : FC0.Header->phis())
1409         OriginalFC0PHIs.push_back(&PHI);
1410 
1411     assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
1412 
1413     // Replace incoming blocks for header PHIs first.
1414     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1415     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1416 
1417     // The old exiting block of the first loop (FC0) has to jump to the header
1418     // of the second as we need to execute the code in the second header block
1419     // regardless of the trip count. That is, if the trip count is 0, so the
1420     // back edge is never taken, we still have to execute both loop headers,
1421     // especially (but not only!) if the second is a do-while style loop.
1422     // However, doing so might invalidate the phi nodes of the first loop as
1423     // the new values do only need to dominate their latch and not the exiting
1424     // predicate. To remedy this potential problem we always introduce phi
1425     // nodes in the header of the second loop later that select the loop carried
1426     // value, if the second header was reached through an old latch of the
1427     // first, or undef otherwise. This is sound as exiting the first implies the
1428     // second will exit too, __without__ taking the back-edge (their
1429     // trip-counts are equal after all).
1430     FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1431                                                          FC1.Header);
1432 
1433     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1434         DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1435     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1436         DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1437 
1438     // Remove FC0 Exit Block
1439     // The exit block for FC0 is no longer needed since control will flow
1440     // directly to the header of FC1. Since it is an empty block, it can be
1441     // removed at this point.
1442     // TODO: In the future, we can handle non-empty exit blocks my merging any
1443     // instructions from FC0 exit block into FC1 exit block prior to removing
1444     // the block.
1445     assert(pred_begin(FC0.ExitBlock) == pred_end(FC0.ExitBlock) &&
1446            "Expecting exit block to be empty");
1447     FC0.ExitBlock->getTerminator()->eraseFromParent();
1448     new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1449 
1450     // Remove FC1 Preheader
1451     // The pre-header of L1 is not necessary anymore.
1452     assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader));
1453     FC1.Preheader->getTerminator()->eraseFromParent();
1454     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1455     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1456         DominatorTree::Delete, FC1.Preheader, FC1.Header));
1457 
1458     // Moves the phi nodes from the second to the first loops header block.
1459     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1460       if (SE.isSCEVable(PHI->getType()))
1461         SE.forgetValue(PHI);
1462       if (PHI->hasNUsesOrMore(1))
1463         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1464       else
1465         PHI->eraseFromParent();
1466     }
1467 
1468     // Introduce new phi nodes in the second loop header to ensure
1469     // exiting the first and jumping to the header of the second does not break
1470     // the SSA property of the phis originally in the first loop. See also the
1471     // comment above.
1472     Instruction *L1HeaderIP = &FC1.Header->front();
1473     for (PHINode *LCPHI : OriginalFC0PHIs) {
1474       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1475       assert(L1LatchBBIdx >= 0 &&
1476              "Expected loop carried value to be rewired at this point!");
1477 
1478       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1479 
1480       PHINode *L1HeaderPHI = PHINode::Create(
1481           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
1482       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1483       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
1484                                FC0.ExitingBlock);
1485 
1486       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1487     }
1488 
1489     // Update the latches
1490 
1491     // Replace latch terminator destinations.
1492     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1493     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1494 
1495     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1496     // performed the updates above.
1497     if (FC0.Latch != FC0.ExitingBlock)
1498       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1499           DominatorTree::Insert, FC0.Latch, FC1.Header));
1500 
1501     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1502                                                        FC0.Latch, FC0.Header));
1503     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1504                                                        FC1.Latch, FC0.Header));
1505     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1506                                                        FC1.Latch, FC1.Header));
1507 
1508     // All done
1509     // Apply the updates to the Dominator Tree and cleanup.
1510 
1511     assert(succ_begin(FC1GuardBlock) == succ_end(FC1GuardBlock) &&
1512            "FC1GuardBlock has successors!!");
1513     assert(pred_begin(FC1GuardBlock) == pred_end(FC1GuardBlock) &&
1514            "FC1GuardBlock has predecessors!!");
1515 
1516     // Update DT/PDT
1517     DTU.applyUpdates(TreeUpdates);
1518 
1519     LI.removeBlock(FC1.Preheader);
1520     DTU.deleteBB(FC1.Preheader);
1521     DTU.deleteBB(FC0.ExitBlock);
1522     DTU.flush();
1523 
1524     // Is there a way to keep SE up-to-date so we don't need to forget the loops
1525     // and rebuild the information in subsequent passes of fusion?
1526     SE.forgetLoop(FC1.L);
1527     SE.forgetLoop(FC0.L);
1528 
1529     // Merge the loops.
1530     SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(),
1531                                         FC1.L->block_end());
1532     for (BasicBlock *BB : Blocks) {
1533       FC0.L->addBlockEntry(BB);
1534       FC1.L->removeBlockFromLoop(BB);
1535       if (LI.getLoopFor(BB) != FC1.L)
1536         continue;
1537       LI.changeLoopFor(BB, FC0.L);
1538     }
1539     while (!FC1.L->empty()) {
1540       const auto &ChildLoopIt = FC1.L->begin();
1541       Loop *ChildLoop = *ChildLoopIt;
1542       FC1.L->removeChildLoop(ChildLoopIt);
1543       FC0.L->addChildLoop(ChildLoop);
1544     }
1545 
1546     // Delete the now empty loop L1.
1547     LI.erase(FC1.L);
1548 
1549 #ifndef NDEBUG
1550     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1551     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1552     assert(PDT.verify());
1553     LI.verify(DT);
1554     SE.verify();
1555 #endif
1556 
1557     LLVM_DEBUG(dbgs() << "Fusion done:\n");
1558 
1559     return FC0.L;
1560   }
1561 };
1562 
1563 struct LoopFuseLegacy : public FunctionPass {
1564 
1565   static char ID;
1566 
1567   LoopFuseLegacy() : FunctionPass(ID) {
1568     initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry());
1569   }
1570 
1571   void getAnalysisUsage(AnalysisUsage &AU) const override {
1572     AU.addRequiredID(LoopSimplifyID);
1573     AU.addRequired<ScalarEvolutionWrapperPass>();
1574     AU.addRequired<LoopInfoWrapperPass>();
1575     AU.addRequired<DominatorTreeWrapperPass>();
1576     AU.addRequired<PostDominatorTreeWrapperPass>();
1577     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1578     AU.addRequired<DependenceAnalysisWrapperPass>();
1579 
1580     AU.addPreserved<ScalarEvolutionWrapperPass>();
1581     AU.addPreserved<LoopInfoWrapperPass>();
1582     AU.addPreserved<DominatorTreeWrapperPass>();
1583     AU.addPreserved<PostDominatorTreeWrapperPass>();
1584   }
1585 
1586   bool runOnFunction(Function &F) override {
1587     if (skipFunction(F))
1588       return false;
1589     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1590     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1591     auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1592     auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1593     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1594     auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1595 
1596     const DataLayout &DL = F.getParent()->getDataLayout();
1597     LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1598     return LF.fuseLoops(F);
1599   }
1600 };
1601 } // namespace
1602 
1603 PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) {
1604   auto &LI = AM.getResult<LoopAnalysis>(F);
1605   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1606   auto &DI = AM.getResult<DependenceAnalysis>(F);
1607   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1608   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1609   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1610 
1611   const DataLayout &DL = F.getParent()->getDataLayout();
1612   LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1613   bool Changed = LF.fuseLoops(F);
1614   if (!Changed)
1615     return PreservedAnalyses::all();
1616 
1617   PreservedAnalyses PA;
1618   PA.preserve<DominatorTreeAnalysis>();
1619   PA.preserve<PostDominatorTreeAnalysis>();
1620   PA.preserve<ScalarEvolutionAnalysis>();
1621   PA.preserve<LoopAnalysis>();
1622   return PA;
1623 }
1624 
1625 char LoopFuseLegacy::ID = 0;
1626 
1627 INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false,
1628                       false)
1629 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1630 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1631 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1632 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
1633 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1634 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1635 INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false)
1636 
1637 FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); }
1638