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/Pass.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/Transforms/Scalar.h"
62 #include "llvm/Transforms/Utils.h"
63 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "loop-fusion"
68 
69 STATISTIC(FuseCounter, "Count number of loop fusions performed");
70 STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
71 STATISTIC(InvalidPreheader, "Loop has invalid preheader");
72 STATISTIC(InvalidHeader, "Loop has invalid header");
73 STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks");
74 STATISTIC(InvalidExitBlock, "Loop has invalid exit block");
75 STATISTIC(InvalidLatch, "Loop has invalid latch");
76 STATISTIC(InvalidLoop, "Loop is invalid");
77 STATISTIC(AddressTakenBB, "Basic block has address taken");
78 STATISTIC(MayThrowException, "Loop may throw an exception");
79 STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
80 STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
81 STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
82 STATISTIC(InvalidTripCount,
83           "Loop does not have invariant backedge taken count");
84 STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
85 STATISTIC(NonEqualTripCount, "Candidate trip counts are not the same");
86 STATISTIC(NonAdjacent, "Candidates are not adjacent");
87 STATISTIC(NonEmptyPreheader, "Candidate has a non-empty preheader");
88 
89 enum FusionDependenceAnalysisChoice {
90   FUSION_DEPENDENCE_ANALYSIS_SCEV,
91   FUSION_DEPENDENCE_ANALYSIS_DA,
92   FUSION_DEPENDENCE_ANALYSIS_ALL,
93 };
94 
95 static cl::opt<FusionDependenceAnalysisChoice> FusionDependenceAnalysis(
96     "loop-fusion-dependence-analysis",
97     cl::desc("Which dependence analysis should loop fusion use?"),
98     cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev",
99                           "Use the scalar evolution interface"),
100                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da",
101                           "Use the dependence analysis interface"),
102                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all",
103                           "Use all available analyses")),
104     cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL), cl::ZeroOrMore);
105 
106 #ifndef NDEBUG
107 static cl::opt<bool>
108     VerboseFusionDebugging("loop-fusion-verbose-debug",
109                            cl::desc("Enable verbose debugging for Loop Fusion"),
110                            cl::Hidden, cl::init(false), cl::ZeroOrMore);
111 #endif
112 
113 /// This class is used to represent a candidate for loop fusion. When it is
114 /// constructed, it checks the conditions for loop fusion to ensure that it
115 /// represents a valid candidate. It caches several parts of a loop that are
116 /// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
117 /// of continually querying the underlying Loop to retrieve these values. It is
118 /// assumed these will not change throughout loop fusion.
119 ///
120 /// The invalidate method should be used to indicate that the FusionCandidate is
121 /// no longer a valid candidate for fusion. Similarly, the isValid() method can
122 /// be used to ensure that the FusionCandidate is still valid for fusion.
123 struct FusionCandidate {
124   /// Cache of parts of the loop used throughout loop fusion. These should not
125   /// need to change throughout the analysis and transformation.
126   /// These parts are cached to avoid repeatedly looking up in the Loop class.
127 
128   /// Preheader of the loop this candidate represents
129   BasicBlock *Preheader;
130   /// Header of the loop this candidate represents
131   BasicBlock *Header;
132   /// Blocks in the loop that exit the loop
133   BasicBlock *ExitingBlock;
134   /// The successor block of this loop (where the exiting blocks go to)
135   BasicBlock *ExitBlock;
136   /// Latch of the loop
137   BasicBlock *Latch;
138   /// The loop that this fusion candidate represents
139   Loop *L;
140   /// Vector of instructions in this loop that read from memory
141   SmallVector<Instruction *, 16> MemReads;
142   /// Vector of instructions in this loop that write to memory
143   SmallVector<Instruction *, 16> MemWrites;
144   /// Are all of the members of this fusion candidate still valid
145   bool Valid;
146 
147   /// Dominator and PostDominator trees are needed for the
148   /// FusionCandidateCompare function, required by FusionCandidateSet to
149   /// determine where the FusionCandidate should be inserted into the set. These
150   /// are used to establish ordering of the FusionCandidates based on dominance.
151   const DominatorTree *DT;
152   const PostDominatorTree *PDT;
153 
154   FusionCandidate(Loop *L, const DominatorTree *DT,
155                   const PostDominatorTree *PDT)
156       : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
157         ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
158         Latch(L->getLoopLatch()), L(L), Valid(true), DT(DT), PDT(PDT) {
159 
160     // Walk over all blocks in the loop and check for conditions that may
161     // prevent fusion. For each block, walk over all instructions and collect
162     // the memory reads and writes If any instructions that prevent fusion are
163     // found, invalidate this object and return.
164     for (BasicBlock *BB : L->blocks()) {
165       if (BB->hasAddressTaken()) {
166         AddressTakenBB++;
167         invalidate();
168         return;
169       }
170 
171       for (Instruction &I : *BB) {
172         if (I.mayThrow()) {
173           MayThrowException++;
174           invalidate();
175           return;
176         }
177         if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
178           if (SI->isVolatile()) {
179             ContainsVolatileAccess++;
180             invalidate();
181             return;
182           }
183         }
184         if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
185           if (LI->isVolatile()) {
186             ContainsVolatileAccess++;
187             invalidate();
188             return;
189           }
190         }
191         if (I.mayWriteToMemory())
192           MemWrites.push_back(&I);
193         if (I.mayReadFromMemory())
194           MemReads.push_back(&I);
195       }
196     }
197   }
198 
199   /// Check if all members of the class are valid.
200   bool isValid() const {
201     return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
202            !L->isInvalid() && Valid;
203   }
204 
205   /// Verify that all members are in sync with the Loop object.
206   void verify() const {
207     assert(isValid() && "Candidate is not valid!!");
208     assert(!L->isInvalid() && "Loop is invalid!");
209     assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
210     assert(Header == L->getHeader() && "Header is out of sync");
211     assert(ExitingBlock == L->getExitingBlock() &&
212            "Exiting Blocks is out of sync");
213     assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
214     assert(Latch == L->getLoopLatch() && "Latch is out of sync");
215   }
216 
217 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
218   LLVM_DUMP_METHOD void dump() const {
219     dbgs() << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
220            << "\n"
221            << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
222            << "\tExitingBB: "
223            << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
224            << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
225            << "\n"
226            << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n";
227   }
228 #endif
229 
230 private:
231   // This is only used internally for now, to clear the MemWrites and MemReads
232   // list and setting Valid to false. I can't envision other uses of this right
233   // now, since once FusionCandidates are put into the FusionCandidateSet they
234   // are immutable. Thus, any time we need to change/update a FusionCandidate,
235   // we must create a new one and insert it into the FusionCandidateSet to
236   // ensure the FusionCandidateSet remains ordered correctly.
237   void invalidate() {
238     MemWrites.clear();
239     MemReads.clear();
240     Valid = false;
241   }
242 };
243 
244 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
245                                      const FusionCandidate &FC) {
246   if (FC.isValid())
247     OS << FC.Preheader->getName();
248   else
249     OS << "<Invalid>";
250 
251   return OS;
252 }
253 
254 struct FusionCandidateCompare {
255   /// Comparison functor to sort two Control Flow Equivalent fusion candidates
256   /// into dominance order.
257   /// If LHS dominates RHS and RHS post-dominates LHS, return true;
258   /// IF RHS dominates LHS and LHS post-dominates RHS, return false;
259   bool operator()(const FusionCandidate &LHS,
260                   const FusionCandidate &RHS) const {
261     const DominatorTree *DT = LHS.DT;
262 
263     // Do not save PDT to local variable as it is only used in asserts and thus
264     // will trigger an unused variable warning if building without asserts.
265     assert(DT && LHS.PDT && "Expecting valid dominator tree");
266 
267     // Do this compare first so if LHS == RHS, function returns false.
268     if (DT->dominates(RHS.Preheader, LHS.Preheader)) {
269       // RHS dominates LHS
270       // Verify LHS post-dominates RHS
271       assert(LHS.PDT->dominates(LHS.Preheader, RHS.Preheader));
272       return false;
273     }
274 
275     if (DT->dominates(LHS.Preheader, RHS.Preheader)) {
276       // Verify RHS Postdominates LHS
277       assert(LHS.PDT->dominates(RHS.Preheader, LHS.Preheader));
278       return true;
279     }
280 
281     // If LHS does not dominate RHS and RHS does not dominate LHS then there is
282     // no dominance relationship between the two FusionCandidates. Thus, they
283     // should not be in the same set together.
284     llvm_unreachable(
285         "No dominance relationship between these fusion candidates!");
286   }
287 };
288 
289 namespace {
290 using LoopVector = SmallVector<Loop *, 4>;
291 
292 // Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance
293 // order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0
294 // dominates FC1 and FC1 post-dominates FC0.
295 // std::set was chosen because we want a sorted data structure with stable
296 // iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent
297 // loops by moving intervening code around. When this intervening code contains
298 // loops, those loops will be moved also. The corresponding FusionCandidates
299 // will also need to be moved accordingly. As this is done, having stable
300 // iterators will simplify the logic. Similarly, having an efficient insert that
301 // keeps the FusionCandidateSet sorted will also simplify the implementation.
302 using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
303 using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
304 } // namespace
305 
306 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
307                                      const FusionCandidateSet &CandSet) {
308   for (auto IT : CandSet)
309     OS << IT << "\n";
310 
311   return OS;
312 }
313 
314 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
315 static void
316 printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
317   LLVM_DEBUG(dbgs() << "Fusion Candidates: \n");
318   for (const auto &CandidateSet : FusionCandidates) {
319     LLVM_DEBUG({
320       dbgs() << "*** Fusion Candidate Set ***\n";
321       dbgs() << CandidateSet;
322       dbgs() << "****************************\n";
323     });
324   }
325 }
326 #endif
327 
328 /// Collect all loops in function at the same nest level, starting at the
329 /// outermost level.
330 ///
331 /// This data structure collects all loops at the same nest level for a
332 /// given function (specified by the LoopInfo object). It starts at the
333 /// outermost level.
334 struct LoopDepthTree {
335   using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
336   using iterator = LoopsOnLevelTy::iterator;
337   using const_iterator = LoopsOnLevelTy::const_iterator;
338 
339   LoopDepthTree(LoopInfo &LI) : Depth(1) {
340     if (!LI.empty())
341       LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
342   }
343 
344   /// Test whether a given loop has been removed from the function, and thus is
345   /// no longer valid.
346   bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
347 
348   /// Record that a given loop has been removed from the function and is no
349   /// longer valid.
350   void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
351 
352   /// Descend the tree to the next (inner) nesting level
353   void descend() {
354     LoopsOnLevelTy LoopsOnNextLevel;
355 
356     for (const LoopVector &LV : *this)
357       for (Loop *L : LV)
358         if (!isRemovedLoop(L) && L->begin() != L->end())
359           LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
360 
361     LoopsOnLevel = LoopsOnNextLevel;
362     RemovedLoops.clear();
363     Depth++;
364   }
365 
366   bool empty() const { return size() == 0; }
367   size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
368   unsigned getDepth() const { return Depth; }
369 
370   iterator begin() { return LoopsOnLevel.begin(); }
371   iterator end() { return LoopsOnLevel.end(); }
372   const_iterator begin() const { return LoopsOnLevel.begin(); }
373   const_iterator end() const { return LoopsOnLevel.end(); }
374 
375 private:
376   /// Set of loops that have been removed from the function and are no longer
377   /// valid.
378   SmallPtrSet<const Loop *, 8> RemovedLoops;
379 
380   /// Depth of the current level, starting at 1 (outermost loops).
381   unsigned Depth;
382 
383   /// Vector of loops at the current depth level that have the same parent loop
384   LoopsOnLevelTy LoopsOnLevel;
385 };
386 
387 #ifndef NDEBUG
388 static void printLoopVector(const LoopVector &LV) {
389   dbgs() << "****************************\n";
390   for (auto L : LV)
391     printLoop(*L, dbgs());
392   dbgs() << "****************************\n";
393 }
394 #endif
395 
396 static void reportLoopFusion(const FusionCandidate &FC0,
397                              const FusionCandidate &FC1,
398                              OptimizationRemarkEmitter &ORE) {
399   using namespace ore;
400   ORE.emit(
401       OptimizationRemark(DEBUG_TYPE, "LoopFusion", FC0.Preheader->getParent())
402       << "Fused " << NV("Cand1", StringRef(FC0.Preheader->getName()))
403       << " with " << NV("Cand2", StringRef(FC1.Preheader->getName())));
404 }
405 
406 struct LoopFuser {
407 private:
408   // Sets of control flow equivalent fusion candidates for a given nest level.
409   FusionCandidateCollection FusionCandidates;
410 
411   LoopDepthTree LDT;
412   DomTreeUpdater DTU;
413 
414   LoopInfo &LI;
415   DominatorTree &DT;
416   DependenceInfo &DI;
417   ScalarEvolution &SE;
418   PostDominatorTree &PDT;
419   OptimizationRemarkEmitter &ORE;
420 
421 public:
422   LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
423             ScalarEvolution &SE, PostDominatorTree &PDT,
424             OptimizationRemarkEmitter &ORE, const DataLayout &DL)
425       : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
426         DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE) {}
427 
428   /// This is the main entry point for loop fusion. It will traverse the
429   /// specified function and collect candidate loops to fuse, starting at the
430   /// outermost nesting level and working inwards.
431   bool fuseLoops(Function &F) {
432 #ifndef NDEBUG
433     if (VerboseFusionDebugging) {
434       LI.print(dbgs());
435     }
436 #endif
437 
438     LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
439                       << "\n");
440     bool Changed = false;
441 
442     while (!LDT.empty()) {
443       LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
444                         << LDT.getDepth() << "\n";);
445 
446       for (const LoopVector &LV : LDT) {
447         assert(LV.size() > 0 && "Empty loop set was build!");
448 
449         // Skip singleton loop sets as they do not offer fusion opportunities on
450         // this level.
451         if (LV.size() == 1)
452           continue;
453 #ifndef NDEBUG
454         if (VerboseFusionDebugging) {
455           LLVM_DEBUG({
456             dbgs() << "  Visit loop set (#" << LV.size() << "):\n";
457             printLoopVector(LV);
458           });
459         }
460 #endif
461 
462         collectFusionCandidates(LV);
463         Changed |= fuseCandidates();
464       }
465 
466       // Finished analyzing candidates at this level.
467       // Descend to the next level and clear all of the candidates currently
468       // collected. Note that it will not be possible to fuse any of the
469       // existing candidates with new candidates because the new candidates will
470       // be at a different nest level and thus not be control flow equivalent
471       // with all of the candidates collected so far.
472       LLVM_DEBUG(dbgs() << "Descend one level!\n");
473       LDT.descend();
474       FusionCandidates.clear();
475     }
476 
477     if (Changed)
478       LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
479 
480 #ifndef NDEBUG
481     assert(DT.verify());
482     assert(PDT.verify());
483     LI.verify(DT);
484     SE.verify();
485 #endif
486 
487     LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
488     return Changed;
489   }
490 
491 private:
492   /// Determine if two fusion candidates are control flow equivalent.
493   ///
494   /// Two fusion candidates are control flow equivalent if when one executes,
495   /// the other is guaranteed to execute. This is determined using dominators
496   /// and post-dominators: if A dominates B and B post-dominates A then A and B
497   /// are control-flow equivalent.
498   bool isControlFlowEquivalent(const FusionCandidate &FC0,
499                                const FusionCandidate &FC1) const {
500     assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
501 
502     if (DT.dominates(FC0.Preheader, FC1.Preheader))
503       return PDT.dominates(FC1.Preheader, FC0.Preheader);
504 
505     if (DT.dominates(FC1.Preheader, FC0.Preheader))
506       return PDT.dominates(FC0.Preheader, FC1.Preheader);
507 
508     return false;
509   }
510 
511   /// Determine if a fusion candidate (representing a loop) is eligible for
512   /// fusion. Note that this only checks whether a single loop can be fused - it
513   /// does not check whether it is *legal* to fuse two loops together.
514   bool eligibleForFusion(const FusionCandidate &FC) const {
515     if (!FC.isValid()) {
516       LLVM_DEBUG(dbgs() << "FC " << FC << " has invalid CFG requirements!\n");
517       if (!FC.Preheader)
518         InvalidPreheader++;
519       if (!FC.Header)
520         InvalidHeader++;
521       if (!FC.ExitingBlock)
522         InvalidExitingBlock++;
523       if (!FC.ExitBlock)
524         InvalidExitBlock++;
525       if (!FC.Latch)
526         InvalidLatch++;
527       if (FC.L->isInvalid())
528         InvalidLoop++;
529 
530       return false;
531     }
532 
533     // Require ScalarEvolution to be able to determine a trip count.
534     if (!SE.hasLoopInvariantBackedgeTakenCount(FC.L)) {
535       LLVM_DEBUG(dbgs() << "Loop " << FC.L->getName()
536                         << " trip count not computable!\n");
537       InvalidTripCount++;
538       return false;
539     }
540 
541     if (!FC.L->isLoopSimplifyForm()) {
542       LLVM_DEBUG(dbgs() << "Loop " << FC.L->getName()
543                         << " is not in simplified form!\n");
544       NotSimplifiedForm++;
545       return false;
546     }
547 
548     return true;
549   }
550 
551   /// Iterate over all loops in the given loop set and identify the loops that
552   /// are eligible for fusion. Place all eligible fusion candidates into Control
553   /// Flow Equivalent sets, sorted by dominance.
554   void collectFusionCandidates(const LoopVector &LV) {
555     for (Loop *L : LV) {
556       FusionCandidate CurrCand(L, &DT, &PDT);
557       if (!eligibleForFusion(CurrCand))
558         continue;
559 
560       // Go through each list in FusionCandidates and determine if L is control
561       // flow equivalent with the first loop in that list. If it is, append LV.
562       // If not, go to the next list.
563       // If no suitable list is found, start another list and add it to
564       // FusionCandidates.
565       bool FoundSet = false;
566 
567       for (auto &CurrCandSet : FusionCandidates) {
568         if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
569           CurrCandSet.insert(CurrCand);
570           FoundSet = true;
571 #ifndef NDEBUG
572           if (VerboseFusionDebugging)
573             LLVM_DEBUG(dbgs() << "Adding " << CurrCand
574                               << " to existing candidate set\n");
575 #endif
576           break;
577         }
578       }
579       if (!FoundSet) {
580         // No set was found. Create a new set and add to FusionCandidates
581 #ifndef NDEBUG
582         if (VerboseFusionDebugging)
583           LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
584 #endif
585         FusionCandidateSet NewCandSet;
586         NewCandSet.insert(CurrCand);
587         FusionCandidates.push_back(NewCandSet);
588       }
589       NumFusionCandidates++;
590     }
591   }
592 
593   /// Determine if it is beneficial to fuse two loops.
594   ///
595   /// For now, this method simply returns true because we want to fuse as much
596   /// as possible (primarily to test the pass). This method will evolve, over
597   /// time, to add heuristics for profitability of fusion.
598   bool isBeneficialFusion(const FusionCandidate &FC0,
599                           const FusionCandidate &FC1) {
600     return true;
601   }
602 
603   /// Determine if two fusion candidates have the same trip count (i.e., they
604   /// execute the same number of iterations).
605   ///
606   /// Note that for now this method simply returns a boolean value because there
607   /// are no mechanisms in loop fusion to handle different trip counts. In the
608   /// future, this behaviour can be extended to adjust one of the loops to make
609   /// the trip counts equal (e.g., loop peeling). When this is added, this
610   /// interface may need to change to return more information than just a
611   /// boolean value.
612   bool identicalTripCounts(const FusionCandidate &FC0,
613                            const FusionCandidate &FC1) const {
614     const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
615     if (isa<SCEVCouldNotCompute>(TripCount0)) {
616       UncomputableTripCount++;
617       LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
618       return false;
619     }
620 
621     const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
622     if (isa<SCEVCouldNotCompute>(TripCount1)) {
623       UncomputableTripCount++;
624       LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
625       return false;
626     }
627     LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
628                       << *TripCount1 << " are "
629                       << (TripCount0 == TripCount1 ? "identical" : "different")
630                       << "\n");
631 
632     return (TripCount0 == TripCount1);
633   }
634 
635   /// Walk each set of control flow equivalent fusion candidates and attempt to
636   /// fuse them. This does a single linear traversal of all candidates in the
637   /// set. The conditions for legal fusion are checked at this point. If a pair
638   /// of fusion candidates passes all legality checks, they are fused together
639   /// and a new fusion candidate is created and added to the FusionCandidateSet.
640   /// The original fusion candidates are then removed, as they are no longer
641   /// valid.
642   bool fuseCandidates() {
643     bool Fused = false;
644     LLVM_DEBUG(printFusionCandidates(FusionCandidates));
645     for (auto &CandidateSet : FusionCandidates) {
646       if (CandidateSet.size() < 2)
647         continue;
648 
649       LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
650                         << CandidateSet << "\n");
651 
652       for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
653         assert(!LDT.isRemovedLoop(FC0->L) &&
654                "Should not have removed loops in CandidateSet!");
655         auto FC1 = FC0;
656         for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
657           assert(!LDT.isRemovedLoop(FC1->L) &&
658                  "Should not have removed loops in CandidateSet!");
659 
660           LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
661                      dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
662 
663           FC0->verify();
664           FC1->verify();
665 
666           if (!identicalTripCounts(*FC0, *FC1)) {
667             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
668                                  "counts. Not fusing.\n");
669             NonEqualTripCount++;
670             continue;
671           }
672 
673           if (!isAdjacent(*FC0, *FC1)) {
674             LLVM_DEBUG(dbgs()
675                        << "Fusion candidates are not adjacent. Not fusing.\n");
676             NonAdjacent++;
677             continue;
678           }
679 
680           // For now we skip fusing if the second candidate has any instructions
681           // in the preheader. This is done because we currently do not have the
682           // safety checks to determine if it is save to move the preheader of
683           // the second candidate past the body of the first candidate. Once
684           // these checks are added, this condition can be removed.
685           if (!isEmptyPreheader(*FC1)) {
686             LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty "
687                                  "preheader. Not fusing.\n");
688             NonEmptyPreheader++;
689             continue;
690           }
691 
692           if (!dependencesAllowFusion(*FC0, *FC1)) {
693             LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
694             continue;
695           }
696 
697           bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
698           LLVM_DEBUG(dbgs()
699                      << "\tFusion appears to be "
700                      << (BeneficialToFuse ? "" : "un") << "profitable!\n");
701           if (!BeneficialToFuse)
702             continue;
703 
704           // All analysis has completed and has determined that fusion is legal
705           // and profitable. At this point, start transforming the code and
706           // perform fusion.
707 
708           LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
709                             << *FC1 << "\n");
710 
711           // Report fusion to the Optimization Remarks.
712           // Note this needs to be done *before* performFusion because
713           // performFusion will change the original loops, making it not
714           // possible to identify them after fusion is complete.
715           reportLoopFusion(*FC0, *FC1, ORE);
716 
717           FusionCandidate FusedCand(performFusion(*FC0, *FC1), &DT, &PDT);
718           FusedCand.verify();
719           assert(eligibleForFusion(FusedCand) &&
720                  "Fused candidate should be eligible for fusion!");
721 
722           // Notify the loop-depth-tree that these loops are not valid objects
723           // anymore.
724           LDT.removeLoop(FC1->L);
725 
726           CandidateSet.erase(FC0);
727           CandidateSet.erase(FC1);
728 
729           auto InsertPos = CandidateSet.insert(FusedCand);
730 
731           assert(InsertPos.second &&
732                  "Unable to insert TargetCandidate in CandidateSet!");
733 
734           // Reset FC0 and FC1 the new (fused) candidate. Subsequent iterations
735           // of the FC1 loop will attempt to fuse the new (fused) loop with the
736           // remaining candidates in the current candidate set.
737           FC0 = FC1 = InsertPos.first;
738 
739           LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet
740                             << "\n");
741 
742           Fused = true;
743         }
744       }
745     }
746     return Fused;
747   }
748 
749   /// Rewrite all additive recurrences in a SCEV to use a new loop.
750   class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> {
751   public:
752     AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL,
753                        bool UseMax = true)
754         : SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL),
755           NewL(NewL) {}
756 
757     const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
758       const Loop *ExprL = Expr->getLoop();
759       SmallVector<const SCEV *, 2> Operands;
760       if (ExprL == &OldL) {
761         Operands.append(Expr->op_begin(), Expr->op_end());
762         return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags());
763       }
764 
765       if (OldL.contains(ExprL)) {
766         bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE));
767         if (!UseMax || !Pos || !Expr->isAffine()) {
768           Valid = false;
769           return Expr;
770         }
771         return visit(Expr->getStart());
772       }
773 
774       for (const SCEV *Op : Expr->operands())
775         Operands.push_back(visit(Op));
776       return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags());
777     }
778 
779     bool wasValidSCEV() const { return Valid; }
780 
781   private:
782     bool Valid, UseMax;
783     const Loop &OldL, &NewL;
784   };
785 
786   /// Return false if the access functions of \p I0 and \p I1 could cause
787   /// a negative dependence.
788   bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0,
789                             Instruction &I1, bool EqualIsInvalid) {
790     Value *Ptr0 = getLoadStorePointerOperand(&I0);
791     Value *Ptr1 = getLoadStorePointerOperand(&I1);
792     if (!Ptr0 || !Ptr1)
793       return false;
794 
795     const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
796     const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
797 #ifndef NDEBUG
798     if (VerboseFusionDebugging)
799       LLVM_DEBUG(dbgs() << "    Access function check: " << *SCEVPtr0 << " vs "
800                         << *SCEVPtr1 << "\n");
801 #endif
802     AddRecLoopReplacer Rewriter(SE, L0, L1);
803     SCEVPtr0 = Rewriter.visit(SCEVPtr0);
804 #ifndef NDEBUG
805     if (VerboseFusionDebugging)
806       LLVM_DEBUG(dbgs() << "    Access function after rewrite: " << *SCEVPtr0
807                         << " [Valid: " << Rewriter.wasValidSCEV() << "]\n");
808 #endif
809     if (!Rewriter.wasValidSCEV())
810       return false;
811 
812     // TODO: isKnownPredicate doesnt work well when one SCEV is loop carried (by
813     //       L0) and the other is not. We could check if it is monotone and test
814     //       the beginning and end value instead.
815 
816     BasicBlock *L0Header = L0.getHeader();
817     auto HasNonLinearDominanceRelation = [&](const SCEV *S) {
818       const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S);
819       if (!AddRec)
820         return false;
821       return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) &&
822              !DT.dominates(AddRec->getLoop()->getHeader(), L0Header);
823     };
824     if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation))
825       return false;
826 
827     ICmpInst::Predicate Pred =
828         EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
829     bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
830 #ifndef NDEBUG
831     if (VerboseFusionDebugging)
832       LLVM_DEBUG(dbgs() << "    Relation: " << *SCEVPtr0
833                         << (IsAlwaysGE ? "  >=  " : "  may <  ") << *SCEVPtr1
834                         << "\n");
835 #endif
836     return IsAlwaysGE;
837   }
838 
839   /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
840   /// @p L1) allow loop fusion of @p L0 and @p L1. The dependence analyses
841   /// specified by @p DepChoice are used to determine this.
842   bool dependencesAllowFusion(const FusionCandidate &FC0,
843                               const FusionCandidate &FC1, Instruction &I0,
844                               Instruction &I1, bool AnyDep,
845                               FusionDependenceAnalysisChoice DepChoice) {
846 #ifndef NDEBUG
847     if (VerboseFusionDebugging) {
848       LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : "
849                         << DepChoice << "\n");
850     }
851 #endif
852     switch (DepChoice) {
853     case FUSION_DEPENDENCE_ANALYSIS_SCEV:
854       return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
855     case FUSION_DEPENDENCE_ANALYSIS_DA: {
856       auto DepResult = DI.depends(&I0, &I1, true);
857       if (!DepResult)
858         return true;
859 #ifndef NDEBUG
860       if (VerboseFusionDebugging) {
861         LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
862                    dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
863                           << (DepResult->isOrdered() ? "true" : "false")
864                           << "]\n");
865         LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
866                           << "\n");
867       }
868 #endif
869 
870       if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
871         LLVM_DEBUG(
872             dbgs() << "TODO: Implement pred/succ dependence handling!\n");
873 
874       // TODO: Can we actually use the dependence info analysis here?
875       return false;
876     }
877 
878     case FUSION_DEPENDENCE_ANALYSIS_ALL:
879       return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
880                                     FUSION_DEPENDENCE_ANALYSIS_SCEV) ||
881              dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
882                                     FUSION_DEPENDENCE_ANALYSIS_DA);
883     }
884 
885     llvm_unreachable("Unknown fusion dependence analysis choice!");
886   }
887 
888   /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
889   bool dependencesAllowFusion(const FusionCandidate &FC0,
890                               const FusionCandidate &FC1) {
891     LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
892                       << "\n");
893     assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
894     assert(DT.dominates(FC0.Preheader, FC1.Preheader));
895 
896     for (Instruction *WriteL0 : FC0.MemWrites) {
897       for (Instruction *WriteL1 : FC1.MemWrites)
898         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
899                                     /* AnyDep */ false,
900                                     FusionDependenceAnalysis)) {
901           InvalidDependencies++;
902           return false;
903         }
904       for (Instruction *ReadL1 : FC1.MemReads)
905         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
906                                     /* AnyDep */ false,
907                                     FusionDependenceAnalysis)) {
908           InvalidDependencies++;
909           return false;
910         }
911     }
912 
913     for (Instruction *WriteL1 : FC1.MemWrites) {
914       for (Instruction *WriteL0 : FC0.MemWrites)
915         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
916                                     /* AnyDep */ false,
917                                     FusionDependenceAnalysis)) {
918           InvalidDependencies++;
919           return false;
920         }
921       for (Instruction *ReadL0 : FC0.MemReads)
922         if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
923                                     /* AnyDep */ false,
924                                     FusionDependenceAnalysis)) {
925           InvalidDependencies++;
926           return false;
927         }
928     }
929 
930     // Walk through all uses in FC1. For each use, find the reaching def. If the
931     // def is located in FC0 then it is is not safe to fuse.
932     for (BasicBlock *BB : FC1.L->blocks())
933       for (Instruction &I : *BB)
934         for (auto &Op : I.operands())
935           if (Instruction *Def = dyn_cast<Instruction>(Op))
936             if (FC0.L->contains(Def->getParent())) {
937               InvalidDependencies++;
938               return false;
939             }
940 
941     return true;
942   }
943 
944   /// Determine if the exit block of \p FC0 is the preheader of \p FC1. In this
945   /// case, there is no code in between the two fusion candidates, thus making
946   /// them adjacent.
947   bool isAdjacent(const FusionCandidate &FC0,
948                   const FusionCandidate &FC1) const {
949     return FC0.ExitBlock == FC1.Preheader;
950   }
951 
952   bool isEmptyPreheader(const FusionCandidate &FC) const {
953     return FC.Preheader->size() == 1;
954   }
955 
956   /// Fuse two fusion candidates, creating a new fused loop.
957   ///
958   /// This method contains the mechanics of fusing two loops, represented by \p
959   /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
960   /// postdominates \p FC0 (making them control flow equivalent). It also
961   /// assumes that the other conditions for fusion have been met: adjacent,
962   /// identical trip counts, and no negative distance dependencies exist that
963   /// would prevent fusion. Thus, there is no checking for these conditions in
964   /// this method.
965   ///
966   /// Fusion is performed by rewiring the CFG to update successor blocks of the
967   /// components of tho loop. Specifically, the following changes are done:
968   ///
969   ///   1. The preheader of \p FC1 is removed as it is no longer necessary
970   ///   (because it is currently only a single statement block).
971   ///   2. The latch of \p FC0 is modified to jump to the header of \p FC1.
972   ///   3. The latch of \p FC1 i modified to jump to the header of \p FC0.
973   ///   4. All blocks from \p FC1 are removed from FC1 and added to FC0.
974   ///
975   /// All of these modifications are done with dominator tree updates, thus
976   /// keeping the dominator (and post dominator) information up-to-date.
977   ///
978   /// This can be improved in the future by actually merging blocks during
979   /// fusion. For example, the preheader of \p FC1 can be merged with the
980   /// preheader of \p FC0. This would allow loops with more than a single
981   /// statement in the preheader to be fused. Similarly, the latch blocks of the
982   /// two loops could also be fused into a single block. This will require
983   /// analysis to prove it is safe to move the contents of the block past
984   /// existing code, which currently has not been implemented.
985   Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
986     assert(FC0.isValid() && FC1.isValid() &&
987            "Expecting valid fusion candidates");
988 
989     LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
990                dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
991 
992     assert(FC1.Preheader == FC0.ExitBlock);
993     assert(FC1.Preheader->size() == 1 &&
994            FC1.Preheader->getSingleSuccessor() == FC1.Header);
995 
996     // Remember the phi nodes originally in the header of FC0 in order to rewire
997     // them later. However, this is only necessary if the new loop carried
998     // values might not dominate the exiting branch. While we do not generally
999     // test if this is the case but simply insert intermediate phi nodes, we
1000     // need to make sure these intermediate phi nodes have different
1001     // predecessors. To this end, we filter the special case where the exiting
1002     // block is the latch block of the first loop. Nothing needs to be done
1003     // anyway as all loop carried values dominate the latch and thereby also the
1004     // exiting branch.
1005     SmallVector<PHINode *, 8> OriginalFC0PHIs;
1006     if (FC0.ExitingBlock != FC0.Latch)
1007       for (PHINode &PHI : FC0.Header->phis())
1008         OriginalFC0PHIs.push_back(&PHI);
1009 
1010     // Replace incoming blocks for header PHIs first.
1011     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1012     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1013 
1014     // Then modify the control flow and update DT and PDT.
1015     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
1016 
1017     // The old exiting block of the first loop (FC0) has to jump to the header
1018     // of the second as we need to execute the code in the second header block
1019     // regardless of the trip count. That is, if the trip count is 0, so the
1020     // back edge is never taken, we still have to execute both loop headers,
1021     // especially (but not only!) if the second is a do-while style loop.
1022     // However, doing so might invalidate the phi nodes of the first loop as
1023     // the new values do only need to dominate their latch and not the exiting
1024     // predicate. To remedy this potential problem we always introduce phi
1025     // nodes in the header of the second loop later that select the loop carried
1026     // value, if the second header was reached through an old latch of the
1027     // first, or undef otherwise. This is sound as exiting the first implies the
1028     // second will exit too, __without__ taking the back-edge. [Their
1029     // trip-counts are equal after all.
1030     // KB: Would this sequence be simpler to just just make FC0.ExitingBlock go
1031     // to FC1.Header? I think this is basically what the three sequences are
1032     // trying to accomplish; however, doing this directly in the CFG may mean
1033     // the DT/PDT becomes invalid
1034     FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1035                                                          FC1.Header);
1036     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1037         DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1038     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1039         DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1040 
1041     // The pre-header of L1 is not necessary anymore.
1042     assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader));
1043     FC1.Preheader->getTerminator()->eraseFromParent();
1044     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1045     TreeUpdates.emplace_back(DominatorTree::UpdateType(
1046         DominatorTree::Delete, FC1.Preheader, FC1.Header));
1047 
1048     // Moves the phi nodes from the second to the first loops header block.
1049     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1050       if (SE.isSCEVable(PHI->getType()))
1051         SE.forgetValue(PHI);
1052       if (PHI->hasNUsesOrMore(1))
1053         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
1054       else
1055         PHI->eraseFromParent();
1056     }
1057 
1058     // Introduce new phi nodes in the second loop header to ensure
1059     // exiting the first and jumping to the header of the second does not break
1060     // the SSA property of the phis originally in the first loop. See also the
1061     // comment above.
1062     Instruction *L1HeaderIP = &FC1.Header->front();
1063     for (PHINode *LCPHI : OriginalFC0PHIs) {
1064       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1065       assert(L1LatchBBIdx >= 0 &&
1066              "Expected loop carried value to be rewired at this point!");
1067 
1068       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1069 
1070       PHINode *L1HeaderPHI = PHINode::Create(
1071           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
1072       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1073       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
1074                                FC0.ExitingBlock);
1075 
1076       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1077     }
1078 
1079     // Replace latch terminator destinations.
1080     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1081     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1082 
1083     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1084     // performed the updates above.
1085     if (FC0.Latch != FC0.ExitingBlock)
1086       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1087           DominatorTree::Insert, FC0.Latch, FC1.Header));
1088 
1089     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1090                                                        FC0.Latch, FC0.Header));
1091     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1092                                                        FC1.Latch, FC0.Header));
1093     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1094                                                        FC1.Latch, FC1.Header));
1095 
1096     // Update DT/PDT
1097     DTU.applyUpdates(TreeUpdates);
1098 
1099     LI.removeBlock(FC1.Preheader);
1100     DTU.deleteBB(FC1.Preheader);
1101     DTU.flush();
1102 
1103     // Is there a way to keep SE up-to-date so we don't need to forget the loops
1104     // and rebuild the information in subsequent passes of fusion?
1105     SE.forgetLoop(FC1.L);
1106     SE.forgetLoop(FC0.L);
1107 
1108     // Merge the loops.
1109     SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(),
1110                                         FC1.L->block_end());
1111     for (BasicBlock *BB : Blocks) {
1112       FC0.L->addBlockEntry(BB);
1113       FC1.L->removeBlockFromLoop(BB);
1114       if (LI.getLoopFor(BB) != FC1.L)
1115         continue;
1116       LI.changeLoopFor(BB, FC0.L);
1117     }
1118     while (!FC1.L->empty()) {
1119       const auto &ChildLoopIt = FC1.L->begin();
1120       Loop *ChildLoop = *ChildLoopIt;
1121       FC1.L->removeChildLoop(ChildLoopIt);
1122       FC0.L->addChildLoop(ChildLoop);
1123     }
1124 
1125     // Delete the now empty loop L1.
1126     LI.erase(FC1.L);
1127 
1128 #ifndef NDEBUG
1129     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1130     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1131     assert(PDT.verify());
1132     LI.verify(DT);
1133     SE.verify();
1134 #endif
1135 
1136     FuseCounter++;
1137 
1138     LLVM_DEBUG(dbgs() << "Fusion done:\n");
1139 
1140     return FC0.L;
1141   }
1142 };
1143 
1144 struct LoopFuseLegacy : public FunctionPass {
1145 
1146   static char ID;
1147 
1148   LoopFuseLegacy() : FunctionPass(ID) {
1149     initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry());
1150   }
1151 
1152   void getAnalysisUsage(AnalysisUsage &AU) const override {
1153     AU.addRequiredID(LoopSimplifyID);
1154     AU.addRequired<ScalarEvolutionWrapperPass>();
1155     AU.addRequired<LoopInfoWrapperPass>();
1156     AU.addRequired<DominatorTreeWrapperPass>();
1157     AU.addRequired<PostDominatorTreeWrapperPass>();
1158     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1159     AU.addRequired<DependenceAnalysisWrapperPass>();
1160 
1161     AU.addPreserved<ScalarEvolutionWrapperPass>();
1162     AU.addPreserved<LoopInfoWrapperPass>();
1163     AU.addPreserved<DominatorTreeWrapperPass>();
1164     AU.addPreserved<PostDominatorTreeWrapperPass>();
1165   }
1166 
1167   bool runOnFunction(Function &F) override {
1168     if (skipFunction(F))
1169       return false;
1170     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1171     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1172     auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
1173     auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1174     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1175     auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1176 
1177     const DataLayout &DL = F.getParent()->getDataLayout();
1178     LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1179     return LF.fuseLoops(F);
1180   }
1181 };
1182 
1183 PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) {
1184   auto &LI = AM.getResult<LoopAnalysis>(F);
1185   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1186   auto &DI = AM.getResult<DependenceAnalysis>(F);
1187   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1188   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1189   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1190 
1191   const DataLayout &DL = F.getParent()->getDataLayout();
1192   LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL);
1193   bool Changed = LF.fuseLoops(F);
1194   if (!Changed)
1195     return PreservedAnalyses::all();
1196 
1197   PreservedAnalyses PA;
1198   PA.preserve<DominatorTreeAnalysis>();
1199   PA.preserve<PostDominatorTreeAnalysis>();
1200   PA.preserve<ScalarEvolutionAnalysis>();
1201   PA.preserve<LoopAnalysis>();
1202   return PA;
1203 }
1204 
1205 char LoopFuseLegacy::ID = 0;
1206 
1207 INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false,
1208                       false)
1209 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
1210 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
1211 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1212 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
1213 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1214 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1215 INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false)
1216 
1217 FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); }
1218