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