xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Transforms/Scalar/LoopFuse.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
17330f729Sjoerg //===- LoopFuse.cpp - Loop Fusion Pass ------------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg ///
97330f729Sjoerg /// \file
107330f729Sjoerg /// This file implements the loop fusion pass.
117330f729Sjoerg /// The implementation is largely based on the following document:
127330f729Sjoerg ///
137330f729Sjoerg ///       Code Transformations to Augment the Scope of Loop Fusion in a
147330f729Sjoerg ///         Production Compiler
157330f729Sjoerg ///       Christopher Mark Barton
167330f729Sjoerg ///       MSc Thesis
177330f729Sjoerg ///       https://webdocs.cs.ualberta.ca/~amaral/thesis/ChristopherBartonMSc.pdf
187330f729Sjoerg ///
197330f729Sjoerg /// The general approach taken is to collect sets of control flow equivalent
207330f729Sjoerg /// loops and test whether they can be fused. The necessary conditions for
217330f729Sjoerg /// fusion are:
227330f729Sjoerg ///    1. The loops must be adjacent (there cannot be any statements between
237330f729Sjoerg ///       the two loops).
247330f729Sjoerg ///    2. The loops must be conforming (they must execute the same number of
257330f729Sjoerg ///       iterations).
267330f729Sjoerg ///    3. The loops must be control flow equivalent (if one loop executes, the
277330f729Sjoerg ///       other is guaranteed to execute).
287330f729Sjoerg ///    4. There cannot be any negative distance dependencies between the loops.
297330f729Sjoerg /// If all of these conditions are satisfied, it is safe to fuse the loops.
307330f729Sjoerg ///
317330f729Sjoerg /// This implementation creates FusionCandidates that represent the loop and the
327330f729Sjoerg /// necessary information needed by fusion. It then operates on the fusion
337330f729Sjoerg /// candidates, first confirming that the candidate is eligible for fusion. The
347330f729Sjoerg /// candidates are then collected into control flow equivalent sets, sorted in
357330f729Sjoerg /// dominance order. Each set of control flow equivalent candidates is then
367330f729Sjoerg /// traversed, attempting to fuse pairs of candidates in the set. If all
377330f729Sjoerg /// requirements for fusion are met, the two candidates are fused, creating a
387330f729Sjoerg /// new (fused) candidate which is then added back into the set to consider for
397330f729Sjoerg /// additional fusion.
407330f729Sjoerg ///
417330f729Sjoerg /// This implementation currently does not make any modifications to remove
427330f729Sjoerg /// conditions for fusion. Code transformations to make loops conform to each of
437330f729Sjoerg /// the conditions for fusion are discussed in more detail in the document
447330f729Sjoerg /// above. These can be added to the current implementation in the future.
457330f729Sjoerg //===----------------------------------------------------------------------===//
467330f729Sjoerg 
477330f729Sjoerg #include "llvm/Transforms/Scalar/LoopFuse.h"
487330f729Sjoerg #include "llvm/ADT/Statistic.h"
49*82d56013Sjoerg #include "llvm/Analysis/AssumptionCache.h"
507330f729Sjoerg #include "llvm/Analysis/DependenceAnalysis.h"
517330f729Sjoerg #include "llvm/Analysis/DomTreeUpdater.h"
527330f729Sjoerg #include "llvm/Analysis/LoopInfo.h"
537330f729Sjoerg #include "llvm/Analysis/OptimizationRemarkEmitter.h"
547330f729Sjoerg #include "llvm/Analysis/PostDominators.h"
557330f729Sjoerg #include "llvm/Analysis/ScalarEvolution.h"
567330f729Sjoerg #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57*82d56013Sjoerg #include "llvm/Analysis/TargetTransformInfo.h"
587330f729Sjoerg #include "llvm/IR/Function.h"
597330f729Sjoerg #include "llvm/IR/Verifier.h"
60*82d56013Sjoerg #include "llvm/InitializePasses.h"
617330f729Sjoerg #include "llvm/Pass.h"
62*82d56013Sjoerg #include "llvm/Support/CommandLine.h"
637330f729Sjoerg #include "llvm/Support/Debug.h"
647330f729Sjoerg #include "llvm/Support/raw_ostream.h"
657330f729Sjoerg #include "llvm/Transforms/Scalar.h"
667330f729Sjoerg #include "llvm/Transforms/Utils.h"
677330f729Sjoerg #include "llvm/Transforms/Utils/BasicBlockUtils.h"
68*82d56013Sjoerg #include "llvm/Transforms/Utils/CodeMoverUtils.h"
69*82d56013Sjoerg #include "llvm/Transforms/Utils/LoopPeel.h"
707330f729Sjoerg 
717330f729Sjoerg using namespace llvm;
727330f729Sjoerg 
737330f729Sjoerg #define DEBUG_TYPE "loop-fusion"
747330f729Sjoerg 
757330f729Sjoerg STATISTIC(FuseCounter, "Loops fused");
767330f729Sjoerg STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
777330f729Sjoerg STATISTIC(InvalidPreheader, "Loop has invalid preheader");
787330f729Sjoerg STATISTIC(InvalidHeader, "Loop has invalid header");
797330f729Sjoerg STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks");
807330f729Sjoerg STATISTIC(InvalidExitBlock, "Loop has invalid exit block");
817330f729Sjoerg STATISTIC(InvalidLatch, "Loop has invalid latch");
827330f729Sjoerg STATISTIC(InvalidLoop, "Loop is invalid");
837330f729Sjoerg STATISTIC(AddressTakenBB, "Basic block has address taken");
847330f729Sjoerg STATISTIC(MayThrowException, "Loop may throw an exception");
857330f729Sjoerg STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
867330f729Sjoerg STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
877330f729Sjoerg STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
887330f729Sjoerg STATISTIC(UnknownTripCount, "Loop has unknown trip count");
897330f729Sjoerg STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
907330f729Sjoerg STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
917330f729Sjoerg STATISTIC(NonAdjacent, "Loops are not adjacent");
92*82d56013Sjoerg STATISTIC(
93*82d56013Sjoerg     NonEmptyPreheader,
94*82d56013Sjoerg     "Loop has a non-empty preheader with instructions that cannot be moved");
957330f729Sjoerg STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
967330f729Sjoerg STATISTIC(NonIdenticalGuards, "Candidates have different guards");
97*82d56013Sjoerg STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
98*82d56013Sjoerg                              "instructions that cannot be moved");
99*82d56013Sjoerg STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
100*82d56013Sjoerg                               "instructions that cannot be moved");
101*82d56013Sjoerg STATISTIC(NotRotated, "Candidate is not rotated");
102*82d56013Sjoerg STATISTIC(OnlySecondCandidateIsGuarded,
103*82d56013Sjoerg           "The second candidate is guarded while the first one is not");
1047330f729Sjoerg 
1057330f729Sjoerg enum FusionDependenceAnalysisChoice {
1067330f729Sjoerg   FUSION_DEPENDENCE_ANALYSIS_SCEV,
1077330f729Sjoerg   FUSION_DEPENDENCE_ANALYSIS_DA,
1087330f729Sjoerg   FUSION_DEPENDENCE_ANALYSIS_ALL,
1097330f729Sjoerg };
1107330f729Sjoerg 
1117330f729Sjoerg static cl::opt<FusionDependenceAnalysisChoice> FusionDependenceAnalysis(
1127330f729Sjoerg     "loop-fusion-dependence-analysis",
1137330f729Sjoerg     cl::desc("Which dependence analysis should loop fusion use?"),
1147330f729Sjoerg     cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev",
1157330f729Sjoerg                           "Use the scalar evolution interface"),
1167330f729Sjoerg                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da",
1177330f729Sjoerg                           "Use the dependence analysis interface"),
1187330f729Sjoerg                clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all",
1197330f729Sjoerg                           "Use all available analyses")),
1207330f729Sjoerg     cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL), cl::ZeroOrMore);
1217330f729Sjoerg 
122*82d56013Sjoerg static cl::opt<unsigned> FusionPeelMaxCount(
123*82d56013Sjoerg     "loop-fusion-peel-max-count", cl::init(0), cl::Hidden,
124*82d56013Sjoerg     cl::desc("Max number of iterations to be peeled from a loop, such that "
125*82d56013Sjoerg              "fusion can take place"));
126*82d56013Sjoerg 
1277330f729Sjoerg #ifndef NDEBUG
1287330f729Sjoerg static cl::opt<bool>
1297330f729Sjoerg     VerboseFusionDebugging("loop-fusion-verbose-debug",
1307330f729Sjoerg                            cl::desc("Enable verbose debugging for Loop Fusion"),
1317330f729Sjoerg                            cl::Hidden, cl::init(false), cl::ZeroOrMore);
1327330f729Sjoerg #endif
1337330f729Sjoerg 
1347330f729Sjoerg namespace {
1357330f729Sjoerg /// This class is used to represent a candidate for loop fusion. When it is
1367330f729Sjoerg /// constructed, it checks the conditions for loop fusion to ensure that it
1377330f729Sjoerg /// represents a valid candidate. It caches several parts of a loop that are
1387330f729Sjoerg /// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
1397330f729Sjoerg /// of continually querying the underlying Loop to retrieve these values. It is
1407330f729Sjoerg /// assumed these will not change throughout loop fusion.
1417330f729Sjoerg ///
1427330f729Sjoerg /// The invalidate method should be used to indicate that the FusionCandidate is
1437330f729Sjoerg /// no longer a valid candidate for fusion. Similarly, the isValid() method can
1447330f729Sjoerg /// be used to ensure that the FusionCandidate is still valid for fusion.
1457330f729Sjoerg struct FusionCandidate {
1467330f729Sjoerg   /// Cache of parts of the loop used throughout loop fusion. These should not
1477330f729Sjoerg   /// need to change throughout the analysis and transformation.
1487330f729Sjoerg   /// These parts are cached to avoid repeatedly looking up in the Loop class.
1497330f729Sjoerg 
1507330f729Sjoerg   /// Preheader of the loop this candidate represents
1517330f729Sjoerg   BasicBlock *Preheader;
1527330f729Sjoerg   /// Header of the loop this candidate represents
1537330f729Sjoerg   BasicBlock *Header;
1547330f729Sjoerg   /// Blocks in the loop that exit the loop
1557330f729Sjoerg   BasicBlock *ExitingBlock;
1567330f729Sjoerg   /// The successor block of this loop (where the exiting blocks go to)
1577330f729Sjoerg   BasicBlock *ExitBlock;
1587330f729Sjoerg   /// Latch of the loop
1597330f729Sjoerg   BasicBlock *Latch;
1607330f729Sjoerg   /// The loop that this fusion candidate represents
1617330f729Sjoerg   Loop *L;
1627330f729Sjoerg   /// Vector of instructions in this loop that read from memory
1637330f729Sjoerg   SmallVector<Instruction *, 16> MemReads;
1647330f729Sjoerg   /// Vector of instructions in this loop that write to memory
1657330f729Sjoerg   SmallVector<Instruction *, 16> MemWrites;
1667330f729Sjoerg   /// Are all of the members of this fusion candidate still valid
1677330f729Sjoerg   bool Valid;
1687330f729Sjoerg   /// Guard branch of the loop, if it exists
1697330f729Sjoerg   BranchInst *GuardBranch;
170*82d56013Sjoerg   /// Peeling Paramaters of the Loop.
171*82d56013Sjoerg   TTI::PeelingPreferences PP;
172*82d56013Sjoerg   /// Can you Peel this Loop?
173*82d56013Sjoerg   bool AbleToPeel;
174*82d56013Sjoerg   /// Has this loop been Peeled
175*82d56013Sjoerg   bool Peeled;
1767330f729Sjoerg 
1777330f729Sjoerg   /// Dominator and PostDominator trees are needed for the
1787330f729Sjoerg   /// FusionCandidateCompare function, required by FusionCandidateSet to
1797330f729Sjoerg   /// determine where the FusionCandidate should be inserted into the set. These
1807330f729Sjoerg   /// are used to establish ordering of the FusionCandidates based on dominance.
1817330f729Sjoerg   const DominatorTree *DT;
1827330f729Sjoerg   const PostDominatorTree *PDT;
1837330f729Sjoerg 
1847330f729Sjoerg   OptimizationRemarkEmitter &ORE;
1857330f729Sjoerg 
FusionCandidate__anonc3322b0b0111::FusionCandidate1867330f729Sjoerg   FusionCandidate(Loop *L, const DominatorTree *DT,
187*82d56013Sjoerg                   const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE,
188*82d56013Sjoerg                   TTI::PeelingPreferences PP)
1897330f729Sjoerg       : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
1907330f729Sjoerg         ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
191*82d56013Sjoerg         Latch(L->getLoopLatch()), L(L), Valid(true),
192*82d56013Sjoerg         GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
193*82d56013Sjoerg         Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
1947330f729Sjoerg 
1957330f729Sjoerg     // Walk over all blocks in the loop and check for conditions that may
1967330f729Sjoerg     // prevent fusion. For each block, walk over all instructions and collect
1977330f729Sjoerg     // the memory reads and writes If any instructions that prevent fusion are
1987330f729Sjoerg     // found, invalidate this object and return.
1997330f729Sjoerg     for (BasicBlock *BB : L->blocks()) {
2007330f729Sjoerg       if (BB->hasAddressTaken()) {
2017330f729Sjoerg         invalidate();
2027330f729Sjoerg         reportInvalidCandidate(AddressTakenBB);
2037330f729Sjoerg         return;
2047330f729Sjoerg       }
2057330f729Sjoerg 
2067330f729Sjoerg       for (Instruction &I : *BB) {
2077330f729Sjoerg         if (I.mayThrow()) {
2087330f729Sjoerg           invalidate();
2097330f729Sjoerg           reportInvalidCandidate(MayThrowException);
2107330f729Sjoerg           return;
2117330f729Sjoerg         }
2127330f729Sjoerg         if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
2137330f729Sjoerg           if (SI->isVolatile()) {
2147330f729Sjoerg             invalidate();
2157330f729Sjoerg             reportInvalidCandidate(ContainsVolatileAccess);
2167330f729Sjoerg             return;
2177330f729Sjoerg           }
2187330f729Sjoerg         }
2197330f729Sjoerg         if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
2207330f729Sjoerg           if (LI->isVolatile()) {
2217330f729Sjoerg             invalidate();
2227330f729Sjoerg             reportInvalidCandidate(ContainsVolatileAccess);
2237330f729Sjoerg             return;
2247330f729Sjoerg           }
2257330f729Sjoerg         }
2267330f729Sjoerg         if (I.mayWriteToMemory())
2277330f729Sjoerg           MemWrites.push_back(&I);
2287330f729Sjoerg         if (I.mayReadFromMemory())
2297330f729Sjoerg           MemReads.push_back(&I);
2307330f729Sjoerg       }
2317330f729Sjoerg     }
2327330f729Sjoerg   }
2337330f729Sjoerg 
2347330f729Sjoerg   /// Check if all members of the class are valid.
isValid__anonc3322b0b0111::FusionCandidate2357330f729Sjoerg   bool isValid() const {
2367330f729Sjoerg     return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
2377330f729Sjoerg            !L->isInvalid() && Valid;
2387330f729Sjoerg   }
2397330f729Sjoerg 
2407330f729Sjoerg   /// Verify that all members are in sync with the Loop object.
verify__anonc3322b0b0111::FusionCandidate2417330f729Sjoerg   void verify() const {
2427330f729Sjoerg     assert(isValid() && "Candidate is not valid!!");
2437330f729Sjoerg     assert(!L->isInvalid() && "Loop is invalid!");
2447330f729Sjoerg     assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
2457330f729Sjoerg     assert(Header == L->getHeader() && "Header is out of sync");
2467330f729Sjoerg     assert(ExitingBlock == L->getExitingBlock() &&
2477330f729Sjoerg            "Exiting Blocks is out of sync");
2487330f729Sjoerg     assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
2497330f729Sjoerg     assert(Latch == L->getLoopLatch() && "Latch is out of sync");
2507330f729Sjoerg   }
2517330f729Sjoerg 
2527330f729Sjoerg   /// Get the entry block for this fusion candidate.
2537330f729Sjoerg   ///
2547330f729Sjoerg   /// If this fusion candidate represents a guarded loop, the entry block is the
2557330f729Sjoerg   /// loop guard block. If it represents an unguarded loop, the entry block is
2567330f729Sjoerg   /// the preheader of the loop.
getEntryBlock__anonc3322b0b0111::FusionCandidate2577330f729Sjoerg   BasicBlock *getEntryBlock() const {
2587330f729Sjoerg     if (GuardBranch)
2597330f729Sjoerg       return GuardBranch->getParent();
2607330f729Sjoerg     else
2617330f729Sjoerg       return Preheader;
2627330f729Sjoerg   }
2637330f729Sjoerg 
264*82d56013Sjoerg   /// After Peeling the loop is modified quite a bit, hence all of the Blocks
265*82d56013Sjoerg   /// need to be updated accordingly.
updateAfterPeeling__anonc3322b0b0111::FusionCandidate266*82d56013Sjoerg   void updateAfterPeeling() {
267*82d56013Sjoerg     Preheader = L->getLoopPreheader();
268*82d56013Sjoerg     Header = L->getHeader();
269*82d56013Sjoerg     ExitingBlock = L->getExitingBlock();
270*82d56013Sjoerg     ExitBlock = L->getExitBlock();
271*82d56013Sjoerg     Latch = L->getLoopLatch();
272*82d56013Sjoerg     verify();
273*82d56013Sjoerg   }
274*82d56013Sjoerg 
2757330f729Sjoerg   /// Given a guarded loop, get the successor of the guard that is not in the
2767330f729Sjoerg   /// loop.
2777330f729Sjoerg   ///
2787330f729Sjoerg   /// This method returns the successor of the loop guard that is not located
2797330f729Sjoerg   /// within the loop (i.e., the successor of the guard that is not the
2807330f729Sjoerg   /// preheader).
2817330f729Sjoerg   /// This method is only valid for guarded loops.
getNonLoopBlock__anonc3322b0b0111::FusionCandidate2827330f729Sjoerg   BasicBlock *getNonLoopBlock() const {
2837330f729Sjoerg     assert(GuardBranch && "Only valid on guarded loops.");
2847330f729Sjoerg     assert(GuardBranch->isConditional() &&
2857330f729Sjoerg            "Expecting guard to be a conditional branch.");
286*82d56013Sjoerg     if (Peeled)
287*82d56013Sjoerg       return GuardBranch->getSuccessor(1);
2887330f729Sjoerg     return (GuardBranch->getSuccessor(0) == Preheader)
2897330f729Sjoerg                ? GuardBranch->getSuccessor(1)
2907330f729Sjoerg                : GuardBranch->getSuccessor(0);
2917330f729Sjoerg   }
2927330f729Sjoerg 
2937330f729Sjoerg #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump__anonc3322b0b0111::FusionCandidate2947330f729Sjoerg   LLVM_DUMP_METHOD void dump() const {
295*82d56013Sjoerg     dbgs() << "\tGuardBranch: ";
296*82d56013Sjoerg     if (GuardBranch)
297*82d56013Sjoerg       dbgs() << *GuardBranch;
298*82d56013Sjoerg     else
299*82d56013Sjoerg       dbgs() << "nullptr";
300*82d56013Sjoerg     dbgs() << "\n"
3017330f729Sjoerg            << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
3027330f729Sjoerg            << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
3037330f729Sjoerg            << "\n"
3047330f729Sjoerg            << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
3057330f729Sjoerg            << "\tExitingBB: "
3067330f729Sjoerg            << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
3077330f729Sjoerg            << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
3087330f729Sjoerg            << "\n"
3097330f729Sjoerg            << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
3107330f729Sjoerg            << "\tEntryBlock: "
3117330f729Sjoerg            << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
3127330f729Sjoerg            << "\n";
3137330f729Sjoerg   }
3147330f729Sjoerg #endif
3157330f729Sjoerg 
3167330f729Sjoerg   /// Determine if a fusion candidate (representing a loop) is eligible for
3177330f729Sjoerg   /// fusion. Note that this only checks whether a single loop can be fused - it
3187330f729Sjoerg   /// does not check whether it is *legal* to fuse two loops together.
isEligibleForFusion__anonc3322b0b0111::FusionCandidate3197330f729Sjoerg   bool isEligibleForFusion(ScalarEvolution &SE) const {
3207330f729Sjoerg     if (!isValid()) {
3217330f729Sjoerg       LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
3227330f729Sjoerg       if (!Preheader)
3237330f729Sjoerg         ++InvalidPreheader;
3247330f729Sjoerg       if (!Header)
3257330f729Sjoerg         ++InvalidHeader;
3267330f729Sjoerg       if (!ExitingBlock)
3277330f729Sjoerg         ++InvalidExitingBlock;
3287330f729Sjoerg       if (!ExitBlock)
3297330f729Sjoerg         ++InvalidExitBlock;
3307330f729Sjoerg       if (!Latch)
3317330f729Sjoerg         ++InvalidLatch;
3327330f729Sjoerg       if (L->isInvalid())
3337330f729Sjoerg         ++InvalidLoop;
3347330f729Sjoerg 
3357330f729Sjoerg       return false;
3367330f729Sjoerg     }
3377330f729Sjoerg 
3387330f729Sjoerg     // Require ScalarEvolution to be able to determine a trip count.
3397330f729Sjoerg     if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
3407330f729Sjoerg       LLVM_DEBUG(dbgs() << "Loop " << L->getName()
3417330f729Sjoerg                         << " trip count not computable!\n");
3427330f729Sjoerg       return reportInvalidCandidate(UnknownTripCount);
3437330f729Sjoerg     }
3447330f729Sjoerg 
3457330f729Sjoerg     if (!L->isLoopSimplifyForm()) {
3467330f729Sjoerg       LLVM_DEBUG(dbgs() << "Loop " << L->getName()
3477330f729Sjoerg                         << " is not in simplified form!\n");
3487330f729Sjoerg       return reportInvalidCandidate(NotSimplifiedForm);
3497330f729Sjoerg     }
3507330f729Sjoerg 
351*82d56013Sjoerg     if (!L->isRotatedForm()) {
352*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
353*82d56013Sjoerg       return reportInvalidCandidate(NotRotated);
354*82d56013Sjoerg     }
355*82d56013Sjoerg 
3567330f729Sjoerg     return true;
3577330f729Sjoerg   }
3587330f729Sjoerg 
3597330f729Sjoerg private:
3607330f729Sjoerg   // This is only used internally for now, to clear the MemWrites and MemReads
3617330f729Sjoerg   // list and setting Valid to false. I can't envision other uses of this right
3627330f729Sjoerg   // now, since once FusionCandidates are put into the FusionCandidateSet they
3637330f729Sjoerg   // are immutable. Thus, any time we need to change/update a FusionCandidate,
3647330f729Sjoerg   // we must create a new one and insert it into the FusionCandidateSet to
3657330f729Sjoerg   // ensure the FusionCandidateSet remains ordered correctly.
invalidate__anonc3322b0b0111::FusionCandidate3667330f729Sjoerg   void invalidate() {
3677330f729Sjoerg     MemWrites.clear();
3687330f729Sjoerg     MemReads.clear();
3697330f729Sjoerg     Valid = false;
3707330f729Sjoerg   }
3717330f729Sjoerg 
reportInvalidCandidate__anonc3322b0b0111::FusionCandidate3727330f729Sjoerg   bool reportInvalidCandidate(llvm::Statistic &Stat) const {
3737330f729Sjoerg     using namespace ore;
3747330f729Sjoerg     assert(L && Preheader && "Fusion candidate not initialized properly!");
375*82d56013Sjoerg #if LLVM_ENABLE_STATS
3767330f729Sjoerg     ++Stat;
3777330f729Sjoerg     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
3787330f729Sjoerg                                         L->getStartLoc(), Preheader)
3797330f729Sjoerg              << "[" << Preheader->getParent()->getName() << "]: "
3807330f729Sjoerg              << "Loop is not a candidate for fusion: " << Stat.getDesc());
381*82d56013Sjoerg #endif
3827330f729Sjoerg     return false;
3837330f729Sjoerg   }
3847330f729Sjoerg };
3857330f729Sjoerg 
3867330f729Sjoerg struct FusionCandidateCompare {
3877330f729Sjoerg   /// Comparison functor to sort two Control Flow Equivalent fusion candidates
3887330f729Sjoerg   /// into dominance order.
3897330f729Sjoerg   /// If LHS dominates RHS and RHS post-dominates LHS, return true;
3907330f729Sjoerg   /// IF RHS dominates LHS and LHS post-dominates RHS, return false;
operator ()__anonc3322b0b0111::FusionCandidateCompare3917330f729Sjoerg   bool operator()(const FusionCandidate &LHS,
3927330f729Sjoerg                   const FusionCandidate &RHS) const {
3937330f729Sjoerg     const DominatorTree *DT = LHS.DT;
3947330f729Sjoerg 
3957330f729Sjoerg     BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
3967330f729Sjoerg     BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
3977330f729Sjoerg 
3987330f729Sjoerg     // Do not save PDT to local variable as it is only used in asserts and thus
3997330f729Sjoerg     // will trigger an unused variable warning if building without asserts.
4007330f729Sjoerg     assert(DT && LHS.PDT && "Expecting valid dominator tree");
4017330f729Sjoerg 
4027330f729Sjoerg     // Do this compare first so if LHS == RHS, function returns false.
4037330f729Sjoerg     if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) {
4047330f729Sjoerg       // RHS dominates LHS
4057330f729Sjoerg       // Verify LHS post-dominates RHS
4067330f729Sjoerg       assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
4077330f729Sjoerg       return false;
4087330f729Sjoerg     }
4097330f729Sjoerg 
4107330f729Sjoerg     if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) {
4117330f729Sjoerg       // Verify RHS Postdominates LHS
4127330f729Sjoerg       assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
4137330f729Sjoerg       return true;
4147330f729Sjoerg     }
4157330f729Sjoerg 
4167330f729Sjoerg     // If LHS does not dominate RHS and RHS does not dominate LHS then there is
4177330f729Sjoerg     // no dominance relationship between the two FusionCandidates. Thus, they
4187330f729Sjoerg     // should not be in the same set together.
4197330f729Sjoerg     llvm_unreachable(
4207330f729Sjoerg         "No dominance relationship between these fusion candidates!");
4217330f729Sjoerg   }
4227330f729Sjoerg };
4237330f729Sjoerg 
4247330f729Sjoerg using LoopVector = SmallVector<Loop *, 4>;
4257330f729Sjoerg 
4267330f729Sjoerg // Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance
4277330f729Sjoerg // order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0
4287330f729Sjoerg // dominates FC1 and FC1 post-dominates FC0.
4297330f729Sjoerg // std::set was chosen because we want a sorted data structure with stable
4307330f729Sjoerg // iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent
4317330f729Sjoerg // loops by moving intervening code around. When this intervening code contains
4327330f729Sjoerg // loops, those loops will be moved also. The corresponding FusionCandidates
4337330f729Sjoerg // will also need to be moved accordingly. As this is done, having stable
4347330f729Sjoerg // iterators will simplify the logic. Similarly, having an efficient insert that
4357330f729Sjoerg // keeps the FusionCandidateSet sorted will also simplify the implementation.
4367330f729Sjoerg using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
4377330f729Sjoerg using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
4387330f729Sjoerg 
4397330f729Sjoerg #if !defined(NDEBUG)
operator <<(llvm::raw_ostream & OS,const FusionCandidate & FC)4407330f729Sjoerg static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
4417330f729Sjoerg                                      const FusionCandidate &FC) {
4427330f729Sjoerg   if (FC.isValid())
4437330f729Sjoerg     OS << FC.Preheader->getName();
4447330f729Sjoerg   else
4457330f729Sjoerg     OS << "<Invalid>";
4467330f729Sjoerg 
4477330f729Sjoerg   return OS;
4487330f729Sjoerg }
4497330f729Sjoerg 
operator <<(llvm::raw_ostream & OS,const FusionCandidateSet & CandSet)4507330f729Sjoerg static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
4517330f729Sjoerg                                      const FusionCandidateSet &CandSet) {
4527330f729Sjoerg   for (const FusionCandidate &FC : CandSet)
4537330f729Sjoerg     OS << FC << '\n';
4547330f729Sjoerg 
4557330f729Sjoerg   return OS;
4567330f729Sjoerg }
4577330f729Sjoerg 
4587330f729Sjoerg static void
printFusionCandidates(const FusionCandidateCollection & FusionCandidates)4597330f729Sjoerg printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
4607330f729Sjoerg   dbgs() << "Fusion Candidates: \n";
4617330f729Sjoerg   for (const auto &CandidateSet : FusionCandidates) {
4627330f729Sjoerg     dbgs() << "*** Fusion Candidate Set ***\n";
4637330f729Sjoerg     dbgs() << CandidateSet;
4647330f729Sjoerg     dbgs() << "****************************\n";
4657330f729Sjoerg   }
4667330f729Sjoerg }
4677330f729Sjoerg #endif
4687330f729Sjoerg 
4697330f729Sjoerg /// Collect all loops in function at the same nest level, starting at the
4707330f729Sjoerg /// outermost level.
4717330f729Sjoerg ///
4727330f729Sjoerg /// This data structure collects all loops at the same nest level for a
4737330f729Sjoerg /// given function (specified by the LoopInfo object). It starts at the
4747330f729Sjoerg /// outermost level.
4757330f729Sjoerg struct LoopDepthTree {
4767330f729Sjoerg   using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
4777330f729Sjoerg   using iterator = LoopsOnLevelTy::iterator;
4787330f729Sjoerg   using const_iterator = LoopsOnLevelTy::const_iterator;
4797330f729Sjoerg 
LoopDepthTree__anonc3322b0b0111::LoopDepthTree4807330f729Sjoerg   LoopDepthTree(LoopInfo &LI) : Depth(1) {
4817330f729Sjoerg     if (!LI.empty())
4827330f729Sjoerg       LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
4837330f729Sjoerg   }
4847330f729Sjoerg 
4857330f729Sjoerg   /// Test whether a given loop has been removed from the function, and thus is
4867330f729Sjoerg   /// no longer valid.
isRemovedLoop__anonc3322b0b0111::LoopDepthTree4877330f729Sjoerg   bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
4887330f729Sjoerg 
4897330f729Sjoerg   /// Record that a given loop has been removed from the function and is no
4907330f729Sjoerg   /// longer valid.
removeLoop__anonc3322b0b0111::LoopDepthTree4917330f729Sjoerg   void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
4927330f729Sjoerg 
4937330f729Sjoerg   /// Descend the tree to the next (inner) nesting level
descend__anonc3322b0b0111::LoopDepthTree4947330f729Sjoerg   void descend() {
4957330f729Sjoerg     LoopsOnLevelTy LoopsOnNextLevel;
4967330f729Sjoerg 
4977330f729Sjoerg     for (const LoopVector &LV : *this)
4987330f729Sjoerg       for (Loop *L : LV)
4997330f729Sjoerg         if (!isRemovedLoop(L) && L->begin() != L->end())
5007330f729Sjoerg           LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
5017330f729Sjoerg 
5027330f729Sjoerg     LoopsOnLevel = LoopsOnNextLevel;
5037330f729Sjoerg     RemovedLoops.clear();
5047330f729Sjoerg     Depth++;
5057330f729Sjoerg   }
5067330f729Sjoerg 
empty__anonc3322b0b0111::LoopDepthTree5077330f729Sjoerg   bool empty() const { return size() == 0; }
size__anonc3322b0b0111::LoopDepthTree5087330f729Sjoerg   size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
getDepth__anonc3322b0b0111::LoopDepthTree5097330f729Sjoerg   unsigned getDepth() const { return Depth; }
5107330f729Sjoerg 
begin__anonc3322b0b0111::LoopDepthTree5117330f729Sjoerg   iterator begin() { return LoopsOnLevel.begin(); }
end__anonc3322b0b0111::LoopDepthTree5127330f729Sjoerg   iterator end() { return LoopsOnLevel.end(); }
begin__anonc3322b0b0111::LoopDepthTree5137330f729Sjoerg   const_iterator begin() const { return LoopsOnLevel.begin(); }
end__anonc3322b0b0111::LoopDepthTree5147330f729Sjoerg   const_iterator end() const { return LoopsOnLevel.end(); }
5157330f729Sjoerg 
5167330f729Sjoerg private:
5177330f729Sjoerg   /// Set of loops that have been removed from the function and are no longer
5187330f729Sjoerg   /// valid.
5197330f729Sjoerg   SmallPtrSet<const Loop *, 8> RemovedLoops;
5207330f729Sjoerg 
5217330f729Sjoerg   /// Depth of the current level, starting at 1 (outermost loops).
5227330f729Sjoerg   unsigned Depth;
5237330f729Sjoerg 
5247330f729Sjoerg   /// Vector of loops at the current depth level that have the same parent loop
5257330f729Sjoerg   LoopsOnLevelTy LoopsOnLevel;
5267330f729Sjoerg };
5277330f729Sjoerg 
5287330f729Sjoerg #ifndef NDEBUG
printLoopVector(const LoopVector & LV)5297330f729Sjoerg static void printLoopVector(const LoopVector &LV) {
5307330f729Sjoerg   dbgs() << "****************************\n";
5317330f729Sjoerg   for (auto L : LV)
5327330f729Sjoerg     printLoop(*L, dbgs());
5337330f729Sjoerg   dbgs() << "****************************\n";
5347330f729Sjoerg }
5357330f729Sjoerg #endif
5367330f729Sjoerg 
5377330f729Sjoerg struct LoopFuser {
5387330f729Sjoerg private:
5397330f729Sjoerg   // Sets of control flow equivalent fusion candidates for a given nest level.
5407330f729Sjoerg   FusionCandidateCollection FusionCandidates;
5417330f729Sjoerg 
5427330f729Sjoerg   LoopDepthTree LDT;
5437330f729Sjoerg   DomTreeUpdater DTU;
5447330f729Sjoerg 
5457330f729Sjoerg   LoopInfo &LI;
5467330f729Sjoerg   DominatorTree &DT;
5477330f729Sjoerg   DependenceInfo &DI;
5487330f729Sjoerg   ScalarEvolution &SE;
5497330f729Sjoerg   PostDominatorTree &PDT;
5507330f729Sjoerg   OptimizationRemarkEmitter &ORE;
551*82d56013Sjoerg   AssumptionCache &AC;
552*82d56013Sjoerg 
553*82d56013Sjoerg   const TargetTransformInfo &TTI;
5547330f729Sjoerg 
5557330f729Sjoerg public:
LoopFuser__anonc3322b0b0111::LoopFuser5567330f729Sjoerg   LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
5577330f729Sjoerg             ScalarEvolution &SE, PostDominatorTree &PDT,
558*82d56013Sjoerg             OptimizationRemarkEmitter &ORE, const DataLayout &DL,
559*82d56013Sjoerg             AssumptionCache &AC, const TargetTransformInfo &TTI)
5607330f729Sjoerg       : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
561*82d56013Sjoerg         DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
5627330f729Sjoerg 
5637330f729Sjoerg   /// This is the main entry point for loop fusion. It will traverse the
5647330f729Sjoerg   /// specified function and collect candidate loops to fuse, starting at the
5657330f729Sjoerg   /// outermost nesting level and working inwards.
fuseLoops__anonc3322b0b0111::LoopFuser5667330f729Sjoerg   bool fuseLoops(Function &F) {
5677330f729Sjoerg #ifndef NDEBUG
5687330f729Sjoerg     if (VerboseFusionDebugging) {
5697330f729Sjoerg       LI.print(dbgs());
5707330f729Sjoerg     }
5717330f729Sjoerg #endif
5727330f729Sjoerg 
5737330f729Sjoerg     LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
5747330f729Sjoerg                       << "\n");
5757330f729Sjoerg     bool Changed = false;
5767330f729Sjoerg 
5777330f729Sjoerg     while (!LDT.empty()) {
5787330f729Sjoerg       LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
5797330f729Sjoerg                         << LDT.getDepth() << "\n";);
5807330f729Sjoerg 
5817330f729Sjoerg       for (const LoopVector &LV : LDT) {
5827330f729Sjoerg         assert(LV.size() > 0 && "Empty loop set was build!");
5837330f729Sjoerg 
5847330f729Sjoerg         // Skip singleton loop sets as they do not offer fusion opportunities on
5857330f729Sjoerg         // this level.
5867330f729Sjoerg         if (LV.size() == 1)
5877330f729Sjoerg           continue;
5887330f729Sjoerg #ifndef NDEBUG
5897330f729Sjoerg         if (VerboseFusionDebugging) {
5907330f729Sjoerg           LLVM_DEBUG({
5917330f729Sjoerg             dbgs() << "  Visit loop set (#" << LV.size() << "):\n";
5927330f729Sjoerg             printLoopVector(LV);
5937330f729Sjoerg           });
5947330f729Sjoerg         }
5957330f729Sjoerg #endif
5967330f729Sjoerg 
5977330f729Sjoerg         collectFusionCandidates(LV);
5987330f729Sjoerg         Changed |= fuseCandidates();
5997330f729Sjoerg       }
6007330f729Sjoerg 
6017330f729Sjoerg       // Finished analyzing candidates at this level.
6027330f729Sjoerg       // Descend to the next level and clear all of the candidates currently
6037330f729Sjoerg       // collected. Note that it will not be possible to fuse any of the
6047330f729Sjoerg       // existing candidates with new candidates because the new candidates will
6057330f729Sjoerg       // be at a different nest level and thus not be control flow equivalent
6067330f729Sjoerg       // with all of the candidates collected so far.
6077330f729Sjoerg       LLVM_DEBUG(dbgs() << "Descend one level!\n");
6087330f729Sjoerg       LDT.descend();
6097330f729Sjoerg       FusionCandidates.clear();
6107330f729Sjoerg     }
6117330f729Sjoerg 
6127330f729Sjoerg     if (Changed)
6137330f729Sjoerg       LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
6147330f729Sjoerg 
6157330f729Sjoerg #ifndef NDEBUG
6167330f729Sjoerg     assert(DT.verify());
6177330f729Sjoerg     assert(PDT.verify());
6187330f729Sjoerg     LI.verify(DT);
6197330f729Sjoerg     SE.verify();
6207330f729Sjoerg #endif
6217330f729Sjoerg 
6227330f729Sjoerg     LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
6237330f729Sjoerg     return Changed;
6247330f729Sjoerg   }
6257330f729Sjoerg 
6267330f729Sjoerg private:
6277330f729Sjoerg   /// Determine if two fusion candidates are control flow equivalent.
6287330f729Sjoerg   ///
6297330f729Sjoerg   /// Two fusion candidates are control flow equivalent if when one executes,
6307330f729Sjoerg   /// the other is guaranteed to execute. This is determined using dominators
6317330f729Sjoerg   /// and post-dominators: if A dominates B and B post-dominates A then A and B
6327330f729Sjoerg   /// are control-flow equivalent.
isControlFlowEquivalent__anonc3322b0b0111::LoopFuser6337330f729Sjoerg   bool isControlFlowEquivalent(const FusionCandidate &FC0,
6347330f729Sjoerg                                const FusionCandidate &FC1) const {
6357330f729Sjoerg     assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
6367330f729Sjoerg 
637*82d56013Sjoerg     return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
638*82d56013Sjoerg                                      DT, PDT);
6397330f729Sjoerg   }
6407330f729Sjoerg 
6417330f729Sjoerg   /// Iterate over all loops in the given loop set and identify the loops that
6427330f729Sjoerg   /// are eligible for fusion. Place all eligible fusion candidates into Control
6437330f729Sjoerg   /// Flow Equivalent sets, sorted by dominance.
collectFusionCandidates__anonc3322b0b0111::LoopFuser6447330f729Sjoerg   void collectFusionCandidates(const LoopVector &LV) {
6457330f729Sjoerg     for (Loop *L : LV) {
646*82d56013Sjoerg       TTI::PeelingPreferences PP =
647*82d56013Sjoerg           gatherPeelingPreferences(L, SE, TTI, None, None);
648*82d56013Sjoerg       FusionCandidate CurrCand(L, &DT, &PDT, ORE, PP);
6497330f729Sjoerg       if (!CurrCand.isEligibleForFusion(SE))
6507330f729Sjoerg         continue;
6517330f729Sjoerg 
6527330f729Sjoerg       // Go through each list in FusionCandidates and determine if L is control
6537330f729Sjoerg       // flow equivalent with the first loop in that list. If it is, append LV.
6547330f729Sjoerg       // If not, go to the next list.
6557330f729Sjoerg       // If no suitable list is found, start another list and add it to
6567330f729Sjoerg       // FusionCandidates.
6577330f729Sjoerg       bool FoundSet = false;
6587330f729Sjoerg 
6597330f729Sjoerg       for (auto &CurrCandSet : FusionCandidates) {
6607330f729Sjoerg         if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
6617330f729Sjoerg           CurrCandSet.insert(CurrCand);
6627330f729Sjoerg           FoundSet = true;
6637330f729Sjoerg #ifndef NDEBUG
6647330f729Sjoerg           if (VerboseFusionDebugging)
6657330f729Sjoerg             LLVM_DEBUG(dbgs() << "Adding " << CurrCand
6667330f729Sjoerg                               << " to existing candidate set\n");
6677330f729Sjoerg #endif
6687330f729Sjoerg           break;
6697330f729Sjoerg         }
6707330f729Sjoerg       }
6717330f729Sjoerg       if (!FoundSet) {
6727330f729Sjoerg         // No set was found. Create a new set and add to FusionCandidates
6737330f729Sjoerg #ifndef NDEBUG
6747330f729Sjoerg         if (VerboseFusionDebugging)
6757330f729Sjoerg           LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
6767330f729Sjoerg #endif
6777330f729Sjoerg         FusionCandidateSet NewCandSet;
6787330f729Sjoerg         NewCandSet.insert(CurrCand);
6797330f729Sjoerg         FusionCandidates.push_back(NewCandSet);
6807330f729Sjoerg       }
6817330f729Sjoerg       NumFusionCandidates++;
6827330f729Sjoerg     }
6837330f729Sjoerg   }
6847330f729Sjoerg 
6857330f729Sjoerg   /// Determine if it is beneficial to fuse two loops.
6867330f729Sjoerg   ///
6877330f729Sjoerg   /// For now, this method simply returns true because we want to fuse as much
6887330f729Sjoerg   /// as possible (primarily to test the pass). This method will evolve, over
6897330f729Sjoerg   /// time, to add heuristics for profitability of fusion.
isBeneficialFusion__anonc3322b0b0111::LoopFuser6907330f729Sjoerg   bool isBeneficialFusion(const FusionCandidate &FC0,
6917330f729Sjoerg                           const FusionCandidate &FC1) {
6927330f729Sjoerg     return true;
6937330f729Sjoerg   }
6947330f729Sjoerg 
6957330f729Sjoerg   /// Determine if two fusion candidates have the same trip count (i.e., they
6967330f729Sjoerg   /// execute the same number of iterations).
6977330f729Sjoerg   ///
698*82d56013Sjoerg   /// This function will return a pair of values. The first is a boolean,
699*82d56013Sjoerg   /// stating whether or not the two candidates are known at compile time to
700*82d56013Sjoerg   /// have the same TripCount. The second is the difference in the two
701*82d56013Sjoerg   /// TripCounts. This information can be used later to determine whether or not
702*82d56013Sjoerg   /// peeling can be performed on either one of the candiates.
703*82d56013Sjoerg   std::pair<bool, Optional<unsigned>>
haveIdenticalTripCounts__anonc3322b0b0111::LoopFuser704*82d56013Sjoerg   haveIdenticalTripCounts(const FusionCandidate &FC0,
7057330f729Sjoerg                           const FusionCandidate &FC1) const {
706*82d56013Sjoerg 
7077330f729Sjoerg     const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
7087330f729Sjoerg     if (isa<SCEVCouldNotCompute>(TripCount0)) {
7097330f729Sjoerg       UncomputableTripCount++;
7107330f729Sjoerg       LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
711*82d56013Sjoerg       return {false, None};
7127330f729Sjoerg     }
7137330f729Sjoerg 
7147330f729Sjoerg     const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
7157330f729Sjoerg     if (isa<SCEVCouldNotCompute>(TripCount1)) {
7167330f729Sjoerg       UncomputableTripCount++;
7177330f729Sjoerg       LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
718*82d56013Sjoerg       return {false, None};
7197330f729Sjoerg     }
720*82d56013Sjoerg 
7217330f729Sjoerg     LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
7227330f729Sjoerg                       << *TripCount1 << " are "
7237330f729Sjoerg                       << (TripCount0 == TripCount1 ? "identical" : "different")
7247330f729Sjoerg                       << "\n");
7257330f729Sjoerg 
726*82d56013Sjoerg     if (TripCount0 == TripCount1)
727*82d56013Sjoerg       return {true, 0};
728*82d56013Sjoerg 
729*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
730*82d56013Sjoerg                          "determining the difference between trip counts\n");
731*82d56013Sjoerg 
732*82d56013Sjoerg     // Currently only considering loops with a single exit point
733*82d56013Sjoerg     // and a non-constant trip count.
734*82d56013Sjoerg     const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
735*82d56013Sjoerg     const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
736*82d56013Sjoerg 
737*82d56013Sjoerg     // If any of the tripcounts are zero that means that loop(s) do not have
738*82d56013Sjoerg     // a single exit or a constant tripcount.
739*82d56013Sjoerg     if (TC0 == 0 || TC1 == 0) {
740*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
741*82d56013Sjoerg                            "have a constant number of iterations. Peeling "
742*82d56013Sjoerg                            "is not benefical\n");
743*82d56013Sjoerg       return {false, None};
744*82d56013Sjoerg     }
745*82d56013Sjoerg 
746*82d56013Sjoerg     Optional<unsigned> Difference = None;
747*82d56013Sjoerg     int Diff = TC0 - TC1;
748*82d56013Sjoerg 
749*82d56013Sjoerg     if (Diff > 0)
750*82d56013Sjoerg       Difference = Diff;
751*82d56013Sjoerg     else {
752*82d56013Sjoerg       LLVM_DEBUG(
753*82d56013Sjoerg           dbgs() << "Difference is less than 0. FC1 (second loop) has more "
754*82d56013Sjoerg                     "iterations than the first one. Currently not supported\n");
755*82d56013Sjoerg     }
756*82d56013Sjoerg 
757*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Difference in loop trip count is: " << Difference
758*82d56013Sjoerg                       << "\n");
759*82d56013Sjoerg 
760*82d56013Sjoerg     return {false, Difference};
761*82d56013Sjoerg   }
762*82d56013Sjoerg 
peelFusionCandidate__anonc3322b0b0111::LoopFuser763*82d56013Sjoerg   void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
764*82d56013Sjoerg                            unsigned PeelCount) {
765*82d56013Sjoerg     assert(FC0.AbleToPeel && "Should be able to peel loop");
766*82d56013Sjoerg 
767*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
768*82d56013Sjoerg                       << " iterations of the first loop. \n");
769*82d56013Sjoerg 
770*82d56013Sjoerg     FC0.Peeled = peelLoop(FC0.L, PeelCount, &LI, &SE, &DT, &AC, true);
771*82d56013Sjoerg     if (FC0.Peeled) {
772*82d56013Sjoerg       LLVM_DEBUG(dbgs() << "Done Peeling\n");
773*82d56013Sjoerg 
774*82d56013Sjoerg #ifndef NDEBUG
775*82d56013Sjoerg       auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
776*82d56013Sjoerg 
777*82d56013Sjoerg       assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
778*82d56013Sjoerg              "Loops should have identical trip counts after peeling");
779*82d56013Sjoerg #endif
780*82d56013Sjoerg 
781*82d56013Sjoerg       FC0.PP.PeelCount += PeelCount;
782*82d56013Sjoerg 
783*82d56013Sjoerg       // Peeling does not update the PDT
784*82d56013Sjoerg       PDT.recalculate(*FC0.Preheader->getParent());
785*82d56013Sjoerg 
786*82d56013Sjoerg       FC0.updateAfterPeeling();
787*82d56013Sjoerg 
788*82d56013Sjoerg       // In this case the iterations of the loop are constant, so the first
789*82d56013Sjoerg       // loop will execute completely (will not jump from one of
790*82d56013Sjoerg       // the peeled blocks to the second loop). Here we are updating the
791*82d56013Sjoerg       // branch conditions of each of the peeled blocks, such that it will
792*82d56013Sjoerg       // branch to its successor which is not the preheader of the second loop
793*82d56013Sjoerg       // in the case of unguarded loops, or the succesors of the exit block of
794*82d56013Sjoerg       // the first loop otherwise. Doing this update will ensure that the entry
795*82d56013Sjoerg       // block of the first loop dominates the entry block of the second loop.
796*82d56013Sjoerg       BasicBlock *BB =
797*82d56013Sjoerg           FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
798*82d56013Sjoerg       if (BB) {
799*82d56013Sjoerg         SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
800*82d56013Sjoerg         SmallVector<Instruction *, 8> WorkList;
801*82d56013Sjoerg         for (BasicBlock *Pred : predecessors(BB)) {
802*82d56013Sjoerg           if (Pred != FC0.ExitBlock) {
803*82d56013Sjoerg             WorkList.emplace_back(Pred->getTerminator());
804*82d56013Sjoerg             TreeUpdates.emplace_back(
805*82d56013Sjoerg                 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
806*82d56013Sjoerg           }
807*82d56013Sjoerg         }
808*82d56013Sjoerg         // Cannot modify the predecessors inside the above loop as it will cause
809*82d56013Sjoerg         // the iterators to be nullptrs, causing memory errors.
810*82d56013Sjoerg         for (Instruction *CurrentBranch: WorkList) {
811*82d56013Sjoerg           BasicBlock *Succ = CurrentBranch->getSuccessor(0);
812*82d56013Sjoerg           if (Succ == BB)
813*82d56013Sjoerg             Succ = CurrentBranch->getSuccessor(1);
814*82d56013Sjoerg           ReplaceInstWithInst(CurrentBranch, BranchInst::Create(Succ));
815*82d56013Sjoerg         }
816*82d56013Sjoerg 
817*82d56013Sjoerg         DTU.applyUpdates(TreeUpdates);
818*82d56013Sjoerg         DTU.flush();
819*82d56013Sjoerg       }
820*82d56013Sjoerg       LLVM_DEBUG(
821*82d56013Sjoerg           dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
822*82d56013Sjoerg                  << " iterations from the first loop.\n"
823*82d56013Sjoerg                     "Both Loops have the same number of iterations now.\n");
824*82d56013Sjoerg     }
8257330f729Sjoerg   }
8267330f729Sjoerg 
8277330f729Sjoerg   /// Walk each set of control flow equivalent fusion candidates and attempt to
8287330f729Sjoerg   /// fuse them. This does a single linear traversal of all candidates in the
8297330f729Sjoerg   /// set. The conditions for legal fusion are checked at this point. If a pair
8307330f729Sjoerg   /// of fusion candidates passes all legality checks, they are fused together
8317330f729Sjoerg   /// and a new fusion candidate is created and added to the FusionCandidateSet.
8327330f729Sjoerg   /// The original fusion candidates are then removed, as they are no longer
8337330f729Sjoerg   /// valid.
fuseCandidates__anonc3322b0b0111::LoopFuser8347330f729Sjoerg   bool fuseCandidates() {
8357330f729Sjoerg     bool Fused = false;
8367330f729Sjoerg     LLVM_DEBUG(printFusionCandidates(FusionCandidates));
8377330f729Sjoerg     for (auto &CandidateSet : FusionCandidates) {
8387330f729Sjoerg       if (CandidateSet.size() < 2)
8397330f729Sjoerg         continue;
8407330f729Sjoerg 
8417330f729Sjoerg       LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
8427330f729Sjoerg                         << CandidateSet << "\n");
8437330f729Sjoerg 
8447330f729Sjoerg       for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
8457330f729Sjoerg         assert(!LDT.isRemovedLoop(FC0->L) &&
8467330f729Sjoerg                "Should not have removed loops in CandidateSet!");
8477330f729Sjoerg         auto FC1 = FC0;
8487330f729Sjoerg         for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
8497330f729Sjoerg           assert(!LDT.isRemovedLoop(FC1->L) &&
8507330f729Sjoerg                  "Should not have removed loops in CandidateSet!");
8517330f729Sjoerg 
8527330f729Sjoerg           LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
8537330f729Sjoerg                      dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
8547330f729Sjoerg 
8557330f729Sjoerg           FC0->verify();
8567330f729Sjoerg           FC1->verify();
8577330f729Sjoerg 
858*82d56013Sjoerg           // Check if the candidates have identical tripcounts (first value of
859*82d56013Sjoerg           // pair), and if not check the difference in the tripcounts between
860*82d56013Sjoerg           // the loops (second value of pair). The difference is not equal to
861*82d56013Sjoerg           // None iff the loops iterate a constant number of times, and have a
862*82d56013Sjoerg           // single exit.
863*82d56013Sjoerg           std::pair<bool, Optional<unsigned>> IdenticalTripCountRes =
864*82d56013Sjoerg               haveIdenticalTripCounts(*FC0, *FC1);
865*82d56013Sjoerg           bool SameTripCount = IdenticalTripCountRes.first;
866*82d56013Sjoerg           Optional<unsigned> TCDifference = IdenticalTripCountRes.second;
867*82d56013Sjoerg 
868*82d56013Sjoerg           // Here we are checking that FC0 (the first loop) can be peeled, and
869*82d56013Sjoerg           // both loops have different tripcounts.
870*82d56013Sjoerg           if (FC0->AbleToPeel && !SameTripCount && TCDifference) {
871*82d56013Sjoerg             if (*TCDifference > FusionPeelMaxCount) {
872*82d56013Sjoerg               LLVM_DEBUG(dbgs()
873*82d56013Sjoerg                          << "Difference in loop trip counts: " << *TCDifference
874*82d56013Sjoerg                          << " is greater than maximum peel count specificed: "
875*82d56013Sjoerg                          << FusionPeelMaxCount << "\n");
876*82d56013Sjoerg             } else {
877*82d56013Sjoerg               // Dependent on peeling being performed on the first loop, and
878*82d56013Sjoerg               // assuming all other conditions for fusion return true.
879*82d56013Sjoerg               SameTripCount = true;
880*82d56013Sjoerg             }
881*82d56013Sjoerg           }
882*82d56013Sjoerg 
883*82d56013Sjoerg           if (!SameTripCount) {
8847330f729Sjoerg             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
8857330f729Sjoerg                                  "counts. Not fusing.\n");
8867330f729Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
8877330f729Sjoerg                                                        NonEqualTripCount);
8887330f729Sjoerg             continue;
8897330f729Sjoerg           }
8907330f729Sjoerg 
8917330f729Sjoerg           if (!isAdjacent(*FC0, *FC1)) {
8927330f729Sjoerg             LLVM_DEBUG(dbgs()
8937330f729Sjoerg                        << "Fusion candidates are not adjacent. Not fusing.\n");
8947330f729Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
8957330f729Sjoerg             continue;
8967330f729Sjoerg           }
8977330f729Sjoerg 
898*82d56013Sjoerg           if (!FC0->GuardBranch && FC1->GuardBranch) {
899*82d56013Sjoerg             LLVM_DEBUG(dbgs() << "The second candidate is guarded while the "
900*82d56013Sjoerg                                  "first one is not. Not fusing.\n");
901*82d56013Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(
902*82d56013Sjoerg                 *FC0, *FC1, OnlySecondCandidateIsGuarded);
903*82d56013Sjoerg             continue;
904*82d56013Sjoerg           }
905*82d56013Sjoerg 
9067330f729Sjoerg           // Ensure that FC0 and FC1 have identical guards.
9077330f729Sjoerg           // If one (or both) are not guarded, this check is not necessary.
9087330f729Sjoerg           if (FC0->GuardBranch && FC1->GuardBranch &&
909*82d56013Sjoerg               !haveIdenticalGuards(*FC0, *FC1) && !TCDifference) {
9107330f729Sjoerg             LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
9117330f729Sjoerg                                  "guards. Not Fusing.\n");
9127330f729Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
9137330f729Sjoerg                                                        NonIdenticalGuards);
9147330f729Sjoerg             continue;
9157330f729Sjoerg           }
9167330f729Sjoerg 
917*82d56013Sjoerg           if (!isSafeToMoveBefore(*FC1->Preheader,
918*82d56013Sjoerg                                   *FC0->Preheader->getTerminator(), DT, &PDT,
919*82d56013Sjoerg                                   &DI)) {
920*82d56013Sjoerg             LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
921*82d56013Sjoerg                                  "instructions in preheader. Not fusing.\n");
9227330f729Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
9237330f729Sjoerg                                                        NonEmptyPreheader);
9247330f729Sjoerg             continue;
9257330f729Sjoerg           }
9267330f729Sjoerg 
927*82d56013Sjoerg           if (FC0->GuardBranch) {
928*82d56013Sjoerg             assert(FC1->GuardBranch && "Expecting valid FC1 guard branch");
929*82d56013Sjoerg 
930*82d56013Sjoerg             if (!isSafeToMoveBefore(*FC0->ExitBlock,
931*82d56013Sjoerg                                     *FC1->ExitBlock->getFirstNonPHIOrDbg(), DT,
932*82d56013Sjoerg                                     &PDT, &DI)) {
933*82d56013Sjoerg               LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
934*82d56013Sjoerg                                    "instructions in exit block. Not fusing.\n");
9357330f729Sjoerg               reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
9367330f729Sjoerg                                                          NonEmptyExitBlock);
9377330f729Sjoerg               continue;
9387330f729Sjoerg             }
9397330f729Sjoerg 
940*82d56013Sjoerg             if (!isSafeToMoveBefore(
941*82d56013Sjoerg                     *FC1->GuardBranch->getParent(),
942*82d56013Sjoerg                     *FC0->GuardBranch->getParent()->getTerminator(), DT, &PDT,
943*82d56013Sjoerg                     &DI)) {
944*82d56013Sjoerg               LLVM_DEBUG(dbgs()
945*82d56013Sjoerg                          << "Fusion candidate contains unsafe "
946*82d56013Sjoerg                             "instructions in guard block. Not fusing.\n");
9477330f729Sjoerg               reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
9487330f729Sjoerg                                                          NonEmptyGuardBlock);
9497330f729Sjoerg               continue;
9507330f729Sjoerg             }
951*82d56013Sjoerg           }
9527330f729Sjoerg 
9537330f729Sjoerg           // Check the dependencies across the loops and do not fuse if it would
9547330f729Sjoerg           // violate them.
9557330f729Sjoerg           if (!dependencesAllowFusion(*FC0, *FC1)) {
9567330f729Sjoerg             LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
9577330f729Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
9587330f729Sjoerg                                                        InvalidDependencies);
9597330f729Sjoerg             continue;
9607330f729Sjoerg           }
9617330f729Sjoerg 
9627330f729Sjoerg           bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
9637330f729Sjoerg           LLVM_DEBUG(dbgs()
9647330f729Sjoerg                      << "\tFusion appears to be "
9657330f729Sjoerg                      << (BeneficialToFuse ? "" : "un") << "profitable!\n");
9667330f729Sjoerg           if (!BeneficialToFuse) {
9677330f729Sjoerg             reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
9687330f729Sjoerg                                                        FusionNotBeneficial);
9697330f729Sjoerg             continue;
9707330f729Sjoerg           }
9717330f729Sjoerg           // All analysis has completed and has determined that fusion is legal
9727330f729Sjoerg           // and profitable. At this point, start transforming the code and
9737330f729Sjoerg           // perform fusion.
9747330f729Sjoerg 
9757330f729Sjoerg           LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
9767330f729Sjoerg                             << *FC1 << "\n");
9777330f729Sjoerg 
978*82d56013Sjoerg           FusionCandidate FC0Copy = *FC0;
979*82d56013Sjoerg           // Peel the loop after determining that fusion is legal. The Loops
980*82d56013Sjoerg           // will still be safe to fuse after the peeling is performed.
981*82d56013Sjoerg           bool Peel = TCDifference && *TCDifference > 0;
982*82d56013Sjoerg           if (Peel)
983*82d56013Sjoerg             peelFusionCandidate(FC0Copy, *FC1, *TCDifference);
984*82d56013Sjoerg 
9857330f729Sjoerg           // Report fusion to the Optimization Remarks.
9867330f729Sjoerg           // Note this needs to be done *before* performFusion because
9877330f729Sjoerg           // performFusion will change the original loops, making it not
9887330f729Sjoerg           // possible to identify them after fusion is complete.
989*82d56013Sjoerg           reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : *FC0), *FC1,
990*82d56013Sjoerg                                                FuseCounter);
9917330f729Sjoerg 
992*82d56013Sjoerg           FusionCandidate FusedCand(
993*82d56013Sjoerg               performFusion((Peel ? FC0Copy : *FC0), *FC1), &DT, &PDT, ORE,
994*82d56013Sjoerg               FC0Copy.PP);
9957330f729Sjoerg           FusedCand.verify();
9967330f729Sjoerg           assert(FusedCand.isEligibleForFusion(SE) &&
9977330f729Sjoerg                  "Fused candidate should be eligible for fusion!");
9987330f729Sjoerg 
9997330f729Sjoerg           // Notify the loop-depth-tree that these loops are not valid objects
10007330f729Sjoerg           LDT.removeLoop(FC1->L);
10017330f729Sjoerg 
10027330f729Sjoerg           CandidateSet.erase(FC0);
10037330f729Sjoerg           CandidateSet.erase(FC1);
10047330f729Sjoerg 
10057330f729Sjoerg           auto InsertPos = CandidateSet.insert(FusedCand);
10067330f729Sjoerg 
10077330f729Sjoerg           assert(InsertPos.second &&
10087330f729Sjoerg                  "Unable to insert TargetCandidate in CandidateSet!");
10097330f729Sjoerg 
10107330f729Sjoerg           // Reset FC0 and FC1 the new (fused) candidate. Subsequent iterations
10117330f729Sjoerg           // of the FC1 loop will attempt to fuse the new (fused) loop with the
10127330f729Sjoerg           // remaining candidates in the current candidate set.
10137330f729Sjoerg           FC0 = FC1 = InsertPos.first;
10147330f729Sjoerg 
10157330f729Sjoerg           LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet
10167330f729Sjoerg                             << "\n");
10177330f729Sjoerg 
10187330f729Sjoerg           Fused = true;
10197330f729Sjoerg         }
10207330f729Sjoerg       }
10217330f729Sjoerg     }
10227330f729Sjoerg     return Fused;
10237330f729Sjoerg   }
10247330f729Sjoerg 
10257330f729Sjoerg   /// Rewrite all additive recurrences in a SCEV to use a new loop.
10267330f729Sjoerg   class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> {
10277330f729Sjoerg   public:
AddRecLoopReplacer(ScalarEvolution & SE,const Loop & OldL,const Loop & NewL,bool UseMax=true)10287330f729Sjoerg     AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL,
10297330f729Sjoerg                        bool UseMax = true)
10307330f729Sjoerg         : SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL),
10317330f729Sjoerg           NewL(NewL) {}
10327330f729Sjoerg 
visitAddRecExpr(const SCEVAddRecExpr * Expr)10337330f729Sjoerg     const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
10347330f729Sjoerg       const Loop *ExprL = Expr->getLoop();
10357330f729Sjoerg       SmallVector<const SCEV *, 2> Operands;
10367330f729Sjoerg       if (ExprL == &OldL) {
10377330f729Sjoerg         Operands.append(Expr->op_begin(), Expr->op_end());
10387330f729Sjoerg         return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags());
10397330f729Sjoerg       }
10407330f729Sjoerg 
10417330f729Sjoerg       if (OldL.contains(ExprL)) {
10427330f729Sjoerg         bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE));
10437330f729Sjoerg         if (!UseMax || !Pos || !Expr->isAffine()) {
10447330f729Sjoerg           Valid = false;
10457330f729Sjoerg           return Expr;
10467330f729Sjoerg         }
10477330f729Sjoerg         return visit(Expr->getStart());
10487330f729Sjoerg       }
10497330f729Sjoerg 
10507330f729Sjoerg       for (const SCEV *Op : Expr->operands())
10517330f729Sjoerg         Operands.push_back(visit(Op));
10527330f729Sjoerg       return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags());
10537330f729Sjoerg     }
10547330f729Sjoerg 
wasValidSCEV() const10557330f729Sjoerg     bool wasValidSCEV() const { return Valid; }
10567330f729Sjoerg 
10577330f729Sjoerg   private:
10587330f729Sjoerg     bool Valid, UseMax;
10597330f729Sjoerg     const Loop &OldL, &NewL;
10607330f729Sjoerg   };
10617330f729Sjoerg 
10627330f729Sjoerg   /// Return false if the access functions of \p I0 and \p I1 could cause
10637330f729Sjoerg   /// a negative dependence.
accessDiffIsPositive__anonc3322b0b0111::LoopFuser10647330f729Sjoerg   bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0,
10657330f729Sjoerg                             Instruction &I1, bool EqualIsInvalid) {
10667330f729Sjoerg     Value *Ptr0 = getLoadStorePointerOperand(&I0);
10677330f729Sjoerg     Value *Ptr1 = getLoadStorePointerOperand(&I1);
10687330f729Sjoerg     if (!Ptr0 || !Ptr1)
10697330f729Sjoerg       return false;
10707330f729Sjoerg 
10717330f729Sjoerg     const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
10727330f729Sjoerg     const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
10737330f729Sjoerg #ifndef NDEBUG
10747330f729Sjoerg     if (VerboseFusionDebugging)
10757330f729Sjoerg       LLVM_DEBUG(dbgs() << "    Access function check: " << *SCEVPtr0 << " vs "
10767330f729Sjoerg                         << *SCEVPtr1 << "\n");
10777330f729Sjoerg #endif
10787330f729Sjoerg     AddRecLoopReplacer Rewriter(SE, L0, L1);
10797330f729Sjoerg     SCEVPtr0 = Rewriter.visit(SCEVPtr0);
10807330f729Sjoerg #ifndef NDEBUG
10817330f729Sjoerg     if (VerboseFusionDebugging)
10827330f729Sjoerg       LLVM_DEBUG(dbgs() << "    Access function after rewrite: " << *SCEVPtr0
10837330f729Sjoerg                         << " [Valid: " << Rewriter.wasValidSCEV() << "]\n");
10847330f729Sjoerg #endif
10857330f729Sjoerg     if (!Rewriter.wasValidSCEV())
10867330f729Sjoerg       return false;
10877330f729Sjoerg 
10887330f729Sjoerg     // TODO: isKnownPredicate doesnt work well when one SCEV is loop carried (by
10897330f729Sjoerg     //       L0) and the other is not. We could check if it is monotone and test
10907330f729Sjoerg     //       the beginning and end value instead.
10917330f729Sjoerg 
10927330f729Sjoerg     BasicBlock *L0Header = L0.getHeader();
10937330f729Sjoerg     auto HasNonLinearDominanceRelation = [&](const SCEV *S) {
10947330f729Sjoerg       const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10957330f729Sjoerg       if (!AddRec)
10967330f729Sjoerg         return false;
10977330f729Sjoerg       return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) &&
10987330f729Sjoerg              !DT.dominates(AddRec->getLoop()->getHeader(), L0Header);
10997330f729Sjoerg     };
11007330f729Sjoerg     if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation))
11017330f729Sjoerg       return false;
11027330f729Sjoerg 
11037330f729Sjoerg     ICmpInst::Predicate Pred =
11047330f729Sjoerg         EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
11057330f729Sjoerg     bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
11067330f729Sjoerg #ifndef NDEBUG
11077330f729Sjoerg     if (VerboseFusionDebugging)
11087330f729Sjoerg       LLVM_DEBUG(dbgs() << "    Relation: " << *SCEVPtr0
11097330f729Sjoerg                         << (IsAlwaysGE ? "  >=  " : "  may <  ") << *SCEVPtr1
11107330f729Sjoerg                         << "\n");
11117330f729Sjoerg #endif
11127330f729Sjoerg     return IsAlwaysGE;
11137330f729Sjoerg   }
11147330f729Sjoerg 
11157330f729Sjoerg   /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
11167330f729Sjoerg   /// @p L1) allow loop fusion of @p L0 and @p L1. The dependence analyses
11177330f729Sjoerg   /// specified by @p DepChoice are used to determine this.
dependencesAllowFusion__anonc3322b0b0111::LoopFuser11187330f729Sjoerg   bool dependencesAllowFusion(const FusionCandidate &FC0,
11197330f729Sjoerg                               const FusionCandidate &FC1, Instruction &I0,
11207330f729Sjoerg                               Instruction &I1, bool AnyDep,
11217330f729Sjoerg                               FusionDependenceAnalysisChoice DepChoice) {
11227330f729Sjoerg #ifndef NDEBUG
11237330f729Sjoerg     if (VerboseFusionDebugging) {
11247330f729Sjoerg       LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : "
11257330f729Sjoerg                         << DepChoice << "\n");
11267330f729Sjoerg     }
11277330f729Sjoerg #endif
11287330f729Sjoerg     switch (DepChoice) {
11297330f729Sjoerg     case FUSION_DEPENDENCE_ANALYSIS_SCEV:
11307330f729Sjoerg       return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
11317330f729Sjoerg     case FUSION_DEPENDENCE_ANALYSIS_DA: {
11327330f729Sjoerg       auto DepResult = DI.depends(&I0, &I1, true);
11337330f729Sjoerg       if (!DepResult)
11347330f729Sjoerg         return true;
11357330f729Sjoerg #ifndef NDEBUG
11367330f729Sjoerg       if (VerboseFusionDebugging) {
11377330f729Sjoerg         LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
11387330f729Sjoerg                    dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
11397330f729Sjoerg                           << (DepResult->isOrdered() ? "true" : "false")
11407330f729Sjoerg                           << "]\n");
11417330f729Sjoerg         LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
11427330f729Sjoerg                           << "\n");
11437330f729Sjoerg       }
11447330f729Sjoerg #endif
11457330f729Sjoerg 
11467330f729Sjoerg       if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
11477330f729Sjoerg         LLVM_DEBUG(
11487330f729Sjoerg             dbgs() << "TODO: Implement pred/succ dependence handling!\n");
11497330f729Sjoerg 
11507330f729Sjoerg       // TODO: Can we actually use the dependence info analysis here?
11517330f729Sjoerg       return false;
11527330f729Sjoerg     }
11537330f729Sjoerg 
11547330f729Sjoerg     case FUSION_DEPENDENCE_ANALYSIS_ALL:
11557330f729Sjoerg       return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
11567330f729Sjoerg                                     FUSION_DEPENDENCE_ANALYSIS_SCEV) ||
11577330f729Sjoerg              dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
11587330f729Sjoerg                                     FUSION_DEPENDENCE_ANALYSIS_DA);
11597330f729Sjoerg     }
11607330f729Sjoerg 
11617330f729Sjoerg     llvm_unreachable("Unknown fusion dependence analysis choice!");
11627330f729Sjoerg   }
11637330f729Sjoerg 
11647330f729Sjoerg   /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
dependencesAllowFusion__anonc3322b0b0111::LoopFuser11657330f729Sjoerg   bool dependencesAllowFusion(const FusionCandidate &FC0,
11667330f729Sjoerg                               const FusionCandidate &FC1) {
11677330f729Sjoerg     LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
11687330f729Sjoerg                       << "\n");
11697330f729Sjoerg     assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
11707330f729Sjoerg     assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
11717330f729Sjoerg 
11727330f729Sjoerg     for (Instruction *WriteL0 : FC0.MemWrites) {
11737330f729Sjoerg       for (Instruction *WriteL1 : FC1.MemWrites)
11747330f729Sjoerg         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
11757330f729Sjoerg                                     /* AnyDep */ false,
11767330f729Sjoerg                                     FusionDependenceAnalysis)) {
11777330f729Sjoerg           InvalidDependencies++;
11787330f729Sjoerg           return false;
11797330f729Sjoerg         }
11807330f729Sjoerg       for (Instruction *ReadL1 : FC1.MemReads)
11817330f729Sjoerg         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
11827330f729Sjoerg                                     /* AnyDep */ false,
11837330f729Sjoerg                                     FusionDependenceAnalysis)) {
11847330f729Sjoerg           InvalidDependencies++;
11857330f729Sjoerg           return false;
11867330f729Sjoerg         }
11877330f729Sjoerg     }
11887330f729Sjoerg 
11897330f729Sjoerg     for (Instruction *WriteL1 : FC1.MemWrites) {
11907330f729Sjoerg       for (Instruction *WriteL0 : FC0.MemWrites)
11917330f729Sjoerg         if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
11927330f729Sjoerg                                     /* AnyDep */ false,
11937330f729Sjoerg                                     FusionDependenceAnalysis)) {
11947330f729Sjoerg           InvalidDependencies++;
11957330f729Sjoerg           return false;
11967330f729Sjoerg         }
11977330f729Sjoerg       for (Instruction *ReadL0 : FC0.MemReads)
11987330f729Sjoerg         if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
11997330f729Sjoerg                                     /* AnyDep */ false,
12007330f729Sjoerg                                     FusionDependenceAnalysis)) {
12017330f729Sjoerg           InvalidDependencies++;
12027330f729Sjoerg           return false;
12037330f729Sjoerg         }
12047330f729Sjoerg     }
12057330f729Sjoerg 
12067330f729Sjoerg     // Walk through all uses in FC1. For each use, find the reaching def. If the
12077330f729Sjoerg     // def is located in FC0 then it is is not safe to fuse.
12087330f729Sjoerg     for (BasicBlock *BB : FC1.L->blocks())
12097330f729Sjoerg       for (Instruction &I : *BB)
12107330f729Sjoerg         for (auto &Op : I.operands())
12117330f729Sjoerg           if (Instruction *Def = dyn_cast<Instruction>(Op))
12127330f729Sjoerg             if (FC0.L->contains(Def->getParent())) {
12137330f729Sjoerg               InvalidDependencies++;
12147330f729Sjoerg               return false;
12157330f729Sjoerg             }
12167330f729Sjoerg 
12177330f729Sjoerg     return true;
12187330f729Sjoerg   }
12197330f729Sjoerg 
12207330f729Sjoerg   /// Determine if two fusion candidates are adjacent in the CFG.
12217330f729Sjoerg   ///
12227330f729Sjoerg   /// This method will determine if there are additional basic blocks in the CFG
12237330f729Sjoerg   /// between the exit of \p FC0 and the entry of \p FC1.
12247330f729Sjoerg   /// If the two candidates are guarded loops, then it checks whether the
12257330f729Sjoerg   /// non-loop successor of the \p FC0 guard branch is the entry block of \p
12267330f729Sjoerg   /// FC1. If not, then the loops are not adjacent. If the two candidates are
12277330f729Sjoerg   /// not guarded loops, then it checks whether the exit block of \p FC0 is the
12287330f729Sjoerg   /// preheader of \p FC1.
isAdjacent__anonc3322b0b0111::LoopFuser12297330f729Sjoerg   bool isAdjacent(const FusionCandidate &FC0,
12307330f729Sjoerg                   const FusionCandidate &FC1) const {
12317330f729Sjoerg     // If the successor of the guard branch is FC1, then the loops are adjacent
12327330f729Sjoerg     if (FC0.GuardBranch)
12337330f729Sjoerg       return FC0.getNonLoopBlock() == FC1.getEntryBlock();
12347330f729Sjoerg     else
12357330f729Sjoerg       return FC0.ExitBlock == FC1.getEntryBlock();
12367330f729Sjoerg   }
12377330f729Sjoerg 
12387330f729Sjoerg   /// Determine if two fusion candidates have identical guards
12397330f729Sjoerg   ///
12407330f729Sjoerg   /// This method will determine if two fusion candidates have the same guards.
12417330f729Sjoerg   /// The guards are considered the same if:
12427330f729Sjoerg   ///   1. The instructions to compute the condition used in the compare are
12437330f729Sjoerg   ///      identical.
12447330f729Sjoerg   ///   2. The successors of the guard have the same flow into/around the loop.
12457330f729Sjoerg   /// If the compare instructions are identical, then the first successor of the
12467330f729Sjoerg   /// guard must go to the same place (either the preheader of the loop or the
12477330f729Sjoerg   /// NonLoopBlock). In other words, the the first successor of both loops must
12487330f729Sjoerg   /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
12497330f729Sjoerg   /// the NonLoopBlock). The same must be true for the second successor.
haveIdenticalGuards__anonc3322b0b0111::LoopFuser12507330f729Sjoerg   bool haveIdenticalGuards(const FusionCandidate &FC0,
12517330f729Sjoerg                            const FusionCandidate &FC1) const {
12527330f729Sjoerg     assert(FC0.GuardBranch && FC1.GuardBranch &&
12537330f729Sjoerg            "Expecting FC0 and FC1 to be guarded loops.");
12547330f729Sjoerg 
12557330f729Sjoerg     if (auto FC0CmpInst =
12567330f729Sjoerg             dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
12577330f729Sjoerg       if (auto FC1CmpInst =
12587330f729Sjoerg               dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
12597330f729Sjoerg         if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
12607330f729Sjoerg           return false;
12617330f729Sjoerg 
12627330f729Sjoerg     // The compare instructions are identical.
12637330f729Sjoerg     // Now make sure the successor of the guards have the same flow into/around
12647330f729Sjoerg     // the loop
12657330f729Sjoerg     if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
12667330f729Sjoerg       return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
12677330f729Sjoerg     else
12687330f729Sjoerg       return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
12697330f729Sjoerg   }
12707330f729Sjoerg 
1271*82d56013Sjoerg   /// Modify the latch branch of FC to be unconditional since successors of the
1272*82d56013Sjoerg   /// branch are the same.
simplifyLatchBranch__anonc3322b0b0111::LoopFuser1273*82d56013Sjoerg   void simplifyLatchBranch(const FusionCandidate &FC) const {
1274*82d56013Sjoerg     BranchInst *FCLatchBranch = dyn_cast<BranchInst>(FC.Latch->getTerminator());
1275*82d56013Sjoerg     if (FCLatchBranch) {
1276*82d56013Sjoerg       assert(FCLatchBranch->isConditional() &&
1277*82d56013Sjoerg              FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) &&
1278*82d56013Sjoerg              "Expecting the two successors of FCLatchBranch to be the same");
1279*82d56013Sjoerg       BranchInst *NewBranch =
1280*82d56013Sjoerg           BranchInst::Create(FCLatchBranch->getSuccessor(0));
1281*82d56013Sjoerg       ReplaceInstWithInst(FCLatchBranch, NewBranch);
1282*82d56013Sjoerg     }
12837330f729Sjoerg   }
12847330f729Sjoerg 
1285*82d56013Sjoerg   /// Move instructions from FC0.Latch to FC1.Latch. If FC0.Latch has an unique
1286*82d56013Sjoerg   /// successor, then merge FC0.Latch with its unique successor.
mergeLatch__anonc3322b0b0111::LoopFuser1287*82d56013Sjoerg   void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1288*82d56013Sjoerg     moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI);
1289*82d56013Sjoerg     if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
1290*82d56013Sjoerg       MergeBlockIntoPredecessor(Succ, &DTU, &LI);
1291*82d56013Sjoerg       DTU.flush();
12927330f729Sjoerg     }
12937330f729Sjoerg   }
12947330f729Sjoerg 
12957330f729Sjoerg   /// Fuse two fusion candidates, creating a new fused loop.
12967330f729Sjoerg   ///
12977330f729Sjoerg   /// This method contains the mechanics of fusing two loops, represented by \p
12987330f729Sjoerg   /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
12997330f729Sjoerg   /// postdominates \p FC0 (making them control flow equivalent). It also
13007330f729Sjoerg   /// assumes that the other conditions for fusion have been met: adjacent,
13017330f729Sjoerg   /// identical trip counts, and no negative distance dependencies exist that
13027330f729Sjoerg   /// would prevent fusion. Thus, there is no checking for these conditions in
13037330f729Sjoerg   /// this method.
13047330f729Sjoerg   ///
13057330f729Sjoerg   /// Fusion is performed by rewiring the CFG to update successor blocks of the
13067330f729Sjoerg   /// components of tho loop. Specifically, the following changes are done:
13077330f729Sjoerg   ///
13087330f729Sjoerg   ///   1. The preheader of \p FC1 is removed as it is no longer necessary
13097330f729Sjoerg   ///   (because it is currently only a single statement block).
13107330f729Sjoerg   ///   2. The latch of \p FC0 is modified to jump to the header of \p FC1.
13117330f729Sjoerg   ///   3. The latch of \p FC1 i modified to jump to the header of \p FC0.
13127330f729Sjoerg   ///   4. All blocks from \p FC1 are removed from FC1 and added to FC0.
13137330f729Sjoerg   ///
13147330f729Sjoerg   /// All of these modifications are done with dominator tree updates, thus
13157330f729Sjoerg   /// keeping the dominator (and post dominator) information up-to-date.
13167330f729Sjoerg   ///
13177330f729Sjoerg   /// This can be improved in the future by actually merging blocks during
13187330f729Sjoerg   /// fusion. For example, the preheader of \p FC1 can be merged with the
13197330f729Sjoerg   /// preheader of \p FC0. This would allow loops with more than a single
13207330f729Sjoerg   /// statement in the preheader to be fused. Similarly, the latch blocks of the
13217330f729Sjoerg   /// two loops could also be fused into a single block. This will require
13227330f729Sjoerg   /// analysis to prove it is safe to move the contents of the block past
13237330f729Sjoerg   /// existing code, which currently has not been implemented.
performFusion__anonc3322b0b0111::LoopFuser13247330f729Sjoerg   Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
13257330f729Sjoerg     assert(FC0.isValid() && FC1.isValid() &&
13267330f729Sjoerg            "Expecting valid fusion candidates");
13277330f729Sjoerg 
13287330f729Sjoerg     LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
13297330f729Sjoerg                dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
13307330f729Sjoerg 
1331*82d56013Sjoerg     // Move instructions from the preheader of FC1 to the end of the preheader
1332*82d56013Sjoerg     // of FC0.
1333*82d56013Sjoerg     moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI);
1334*82d56013Sjoerg 
13357330f729Sjoerg     // Fusing guarded loops is handled slightly differently than non-guarded
13367330f729Sjoerg     // loops and has been broken out into a separate method instead of trying to
13377330f729Sjoerg     // intersperse the logic within a single method.
13387330f729Sjoerg     if (FC0.GuardBranch)
13397330f729Sjoerg       return fuseGuardedLoops(FC0, FC1);
13407330f729Sjoerg 
1341*82d56013Sjoerg     assert(FC1.Preheader ==
1342*82d56013Sjoerg            (FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
13437330f729Sjoerg     assert(FC1.Preheader->size() == 1 &&
13447330f729Sjoerg            FC1.Preheader->getSingleSuccessor() == FC1.Header);
13457330f729Sjoerg 
13467330f729Sjoerg     // Remember the phi nodes originally in the header of FC0 in order to rewire
13477330f729Sjoerg     // them later. However, this is only necessary if the new loop carried
13487330f729Sjoerg     // values might not dominate the exiting branch. While we do not generally
13497330f729Sjoerg     // test if this is the case but simply insert intermediate phi nodes, we
13507330f729Sjoerg     // need to make sure these intermediate phi nodes have different
13517330f729Sjoerg     // predecessors. To this end, we filter the special case where the exiting
13527330f729Sjoerg     // block is the latch block of the first loop. Nothing needs to be done
13537330f729Sjoerg     // anyway as all loop carried values dominate the latch and thereby also the
13547330f729Sjoerg     // exiting branch.
13557330f729Sjoerg     SmallVector<PHINode *, 8> OriginalFC0PHIs;
13567330f729Sjoerg     if (FC0.ExitingBlock != FC0.Latch)
13577330f729Sjoerg       for (PHINode &PHI : FC0.Header->phis())
13587330f729Sjoerg         OriginalFC0PHIs.push_back(&PHI);
13597330f729Sjoerg 
13607330f729Sjoerg     // Replace incoming blocks for header PHIs first.
13617330f729Sjoerg     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
13627330f729Sjoerg     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
13637330f729Sjoerg 
13647330f729Sjoerg     // Then modify the control flow and update DT and PDT.
13657330f729Sjoerg     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
13667330f729Sjoerg 
13677330f729Sjoerg     // The old exiting block of the first loop (FC0) has to jump to the header
13687330f729Sjoerg     // of the second as we need to execute the code in the second header block
13697330f729Sjoerg     // regardless of the trip count. That is, if the trip count is 0, so the
13707330f729Sjoerg     // back edge is never taken, we still have to execute both loop headers,
13717330f729Sjoerg     // especially (but not only!) if the second is a do-while style loop.
13727330f729Sjoerg     // However, doing so might invalidate the phi nodes of the first loop as
13737330f729Sjoerg     // the new values do only need to dominate their latch and not the exiting
13747330f729Sjoerg     // predicate. To remedy this potential problem we always introduce phi
13757330f729Sjoerg     // nodes in the header of the second loop later that select the loop carried
13767330f729Sjoerg     // value, if the second header was reached through an old latch of the
13777330f729Sjoerg     // first, or undef otherwise. This is sound as exiting the first implies the
13787330f729Sjoerg     // second will exit too, __without__ taking the back-edge. [Their
13797330f729Sjoerg     // trip-counts are equal after all.
13807330f729Sjoerg     // KB: Would this sequence be simpler to just just make FC0.ExitingBlock go
13817330f729Sjoerg     // to FC1.Header? I think this is basically what the three sequences are
13827330f729Sjoerg     // trying to accomplish; however, doing this directly in the CFG may mean
13837330f729Sjoerg     // the DT/PDT becomes invalid
1384*82d56013Sjoerg     if (!FC0.Peeled) {
13857330f729Sjoerg       FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
13867330f729Sjoerg                                                            FC1.Header);
13877330f729Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
13887330f729Sjoerg           DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
13897330f729Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
13907330f729Sjoerg           DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1391*82d56013Sjoerg     } else {
1392*82d56013Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1393*82d56013Sjoerg           DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1394*82d56013Sjoerg 
1395*82d56013Sjoerg       // Remove the ExitBlock of the first Loop (also not needed)
1396*82d56013Sjoerg       FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1397*82d56013Sjoerg                                                            FC1.Header);
1398*82d56013Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1399*82d56013Sjoerg           DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1400*82d56013Sjoerg       FC0.ExitBlock->getTerminator()->eraseFromParent();
1401*82d56013Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1402*82d56013Sjoerg           DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1403*82d56013Sjoerg       new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1404*82d56013Sjoerg     }
14057330f729Sjoerg 
14067330f729Sjoerg     // The pre-header of L1 is not necessary anymore.
1407*82d56013Sjoerg     assert(pred_empty(FC1.Preheader));
14087330f729Sjoerg     FC1.Preheader->getTerminator()->eraseFromParent();
14097330f729Sjoerg     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
14107330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
14117330f729Sjoerg         DominatorTree::Delete, FC1.Preheader, FC1.Header));
14127330f729Sjoerg 
14137330f729Sjoerg     // Moves the phi nodes from the second to the first loops header block.
14147330f729Sjoerg     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
14157330f729Sjoerg       if (SE.isSCEVable(PHI->getType()))
14167330f729Sjoerg         SE.forgetValue(PHI);
14177330f729Sjoerg       if (PHI->hasNUsesOrMore(1))
14187330f729Sjoerg         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
14197330f729Sjoerg       else
14207330f729Sjoerg         PHI->eraseFromParent();
14217330f729Sjoerg     }
14227330f729Sjoerg 
14237330f729Sjoerg     // Introduce new phi nodes in the second loop header to ensure
14247330f729Sjoerg     // exiting the first and jumping to the header of the second does not break
14257330f729Sjoerg     // the SSA property of the phis originally in the first loop. See also the
14267330f729Sjoerg     // comment above.
14277330f729Sjoerg     Instruction *L1HeaderIP = &FC1.Header->front();
14287330f729Sjoerg     for (PHINode *LCPHI : OriginalFC0PHIs) {
14297330f729Sjoerg       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
14307330f729Sjoerg       assert(L1LatchBBIdx >= 0 &&
14317330f729Sjoerg              "Expected loop carried value to be rewired at this point!");
14327330f729Sjoerg 
14337330f729Sjoerg       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
14347330f729Sjoerg 
14357330f729Sjoerg       PHINode *L1HeaderPHI = PHINode::Create(
14367330f729Sjoerg           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
14377330f729Sjoerg       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
14387330f729Sjoerg       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
14397330f729Sjoerg                                FC0.ExitingBlock);
14407330f729Sjoerg 
14417330f729Sjoerg       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
14427330f729Sjoerg     }
14437330f729Sjoerg 
14447330f729Sjoerg     // Replace latch terminator destinations.
14457330f729Sjoerg     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
14467330f729Sjoerg     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
14477330f729Sjoerg 
1448*82d56013Sjoerg     // Modify the latch branch of FC0 to be unconditional as both successors of
1449*82d56013Sjoerg     // the branch are the same.
1450*82d56013Sjoerg     simplifyLatchBranch(FC0);
1451*82d56013Sjoerg 
14527330f729Sjoerg     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
14537330f729Sjoerg     // performed the updates above.
14547330f729Sjoerg     if (FC0.Latch != FC0.ExitingBlock)
14557330f729Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
14567330f729Sjoerg           DominatorTree::Insert, FC0.Latch, FC1.Header));
14577330f729Sjoerg 
14587330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
14597330f729Sjoerg                                                        FC0.Latch, FC0.Header));
14607330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
14617330f729Sjoerg                                                        FC1.Latch, FC0.Header));
14627330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
14637330f729Sjoerg                                                        FC1.Latch, FC1.Header));
14647330f729Sjoerg 
14657330f729Sjoerg     // Update DT/PDT
14667330f729Sjoerg     DTU.applyUpdates(TreeUpdates);
14677330f729Sjoerg 
14687330f729Sjoerg     LI.removeBlock(FC1.Preheader);
14697330f729Sjoerg     DTU.deleteBB(FC1.Preheader);
1470*82d56013Sjoerg     if (FC0.Peeled) {
1471*82d56013Sjoerg       LI.removeBlock(FC0.ExitBlock);
1472*82d56013Sjoerg       DTU.deleteBB(FC0.ExitBlock);
1473*82d56013Sjoerg     }
1474*82d56013Sjoerg 
14757330f729Sjoerg     DTU.flush();
14767330f729Sjoerg 
14777330f729Sjoerg     // Is there a way to keep SE up-to-date so we don't need to forget the loops
14787330f729Sjoerg     // and rebuild the information in subsequent passes of fusion?
1479*82d56013Sjoerg     // Note: Need to forget the loops before merging the loop latches, as
1480*82d56013Sjoerg     // mergeLatch may remove the only block in FC1.
14817330f729Sjoerg     SE.forgetLoop(FC1.L);
14827330f729Sjoerg     SE.forgetLoop(FC0.L);
14837330f729Sjoerg 
1484*82d56013Sjoerg     // Move instructions from FC0.Latch to FC1.Latch.
1485*82d56013Sjoerg     // Note: mergeLatch requires an updated DT.
1486*82d56013Sjoerg     mergeLatch(FC0, FC1);
1487*82d56013Sjoerg 
14887330f729Sjoerg     // Merge the loops.
1489*82d56013Sjoerg     SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
14907330f729Sjoerg     for (BasicBlock *BB : Blocks) {
14917330f729Sjoerg       FC0.L->addBlockEntry(BB);
14927330f729Sjoerg       FC1.L->removeBlockFromLoop(BB);
14937330f729Sjoerg       if (LI.getLoopFor(BB) != FC1.L)
14947330f729Sjoerg         continue;
14957330f729Sjoerg       LI.changeLoopFor(BB, FC0.L);
14967330f729Sjoerg     }
1497*82d56013Sjoerg     while (!FC1.L->isInnermost()) {
14987330f729Sjoerg       const auto &ChildLoopIt = FC1.L->begin();
14997330f729Sjoerg       Loop *ChildLoop = *ChildLoopIt;
15007330f729Sjoerg       FC1.L->removeChildLoop(ChildLoopIt);
15017330f729Sjoerg       FC0.L->addChildLoop(ChildLoop);
15027330f729Sjoerg     }
15037330f729Sjoerg 
15047330f729Sjoerg     // Delete the now empty loop L1.
15057330f729Sjoerg     LI.erase(FC1.L);
15067330f729Sjoerg 
15077330f729Sjoerg #ifndef NDEBUG
15087330f729Sjoerg     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
15097330f729Sjoerg     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
15107330f729Sjoerg     assert(PDT.verify());
15117330f729Sjoerg     LI.verify(DT);
15127330f729Sjoerg     SE.verify();
15137330f729Sjoerg #endif
15147330f729Sjoerg 
15157330f729Sjoerg     LLVM_DEBUG(dbgs() << "Fusion done:\n");
15167330f729Sjoerg 
15177330f729Sjoerg     return FC0.L;
15187330f729Sjoerg   }
15197330f729Sjoerg 
15207330f729Sjoerg   /// Report details on loop fusion opportunities.
15217330f729Sjoerg   ///
15227330f729Sjoerg   /// This template function can be used to report both successful and missed
15237330f729Sjoerg   /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
15247330f729Sjoerg   /// be one of:
15257330f729Sjoerg   ///   - OptimizationRemarkMissed to report when loop fusion is unsuccessful
15267330f729Sjoerg   ///     given two valid fusion candidates.
15277330f729Sjoerg   ///   - OptimizationRemark to report successful fusion of two fusion
15287330f729Sjoerg   ///     candidates.
15297330f729Sjoerg   /// The remarks will be printed using the form:
15307330f729Sjoerg   ///    <path/filename>:<line number>:<column number>: [<function name>]:
15317330f729Sjoerg   ///       <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
15327330f729Sjoerg   template <typename RemarkKind>
reportLoopFusion__anonc3322b0b0111::LoopFuser15337330f729Sjoerg   void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
15347330f729Sjoerg                         llvm::Statistic &Stat) {
15357330f729Sjoerg     assert(FC0.Preheader && FC1.Preheader &&
15367330f729Sjoerg            "Expecting valid fusion candidates");
15377330f729Sjoerg     using namespace ore;
1538*82d56013Sjoerg #if LLVM_ENABLE_STATS
15397330f729Sjoerg     ++Stat;
15407330f729Sjoerg     ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
15417330f729Sjoerg                         FC0.Preheader)
15427330f729Sjoerg              << "[" << FC0.Preheader->getParent()->getName()
15437330f729Sjoerg              << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
15447330f729Sjoerg              << " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
15457330f729Sjoerg              << ": " << Stat.getDesc());
1546*82d56013Sjoerg #endif
15477330f729Sjoerg   }
15487330f729Sjoerg 
15497330f729Sjoerg   /// Fuse two guarded fusion candidates, creating a new fused loop.
15507330f729Sjoerg   ///
15517330f729Sjoerg   /// Fusing guarded loops is handled much the same way as fusing non-guarded
15527330f729Sjoerg   /// loops. The rewiring of the CFG is slightly different though, because of
15537330f729Sjoerg   /// the presence of the guards around the loops and the exit blocks after the
15547330f729Sjoerg   /// loop body. As such, the new loop is rewired as follows:
15557330f729Sjoerg   ///    1. Keep the guard branch from FC0 and use the non-loop block target
15567330f729Sjoerg   /// from the FC1 guard branch.
15577330f729Sjoerg   ///    2. Remove the exit block from FC0 (this exit block should be empty
15587330f729Sjoerg   /// right now).
15597330f729Sjoerg   ///    3. Remove the guard branch for FC1
15607330f729Sjoerg   ///    4. Remove the preheader for FC1.
15617330f729Sjoerg   /// The exit block successor for the latch of FC0 is updated to be the header
15627330f729Sjoerg   /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
15637330f729Sjoerg   /// be the header of FC0, thus creating the fused loop.
fuseGuardedLoops__anonc3322b0b0111::LoopFuser15647330f729Sjoerg   Loop *fuseGuardedLoops(const FusionCandidate &FC0,
15657330f729Sjoerg                          const FusionCandidate &FC1) {
15667330f729Sjoerg     assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
15677330f729Sjoerg 
15687330f729Sjoerg     BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
15697330f729Sjoerg     BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
15707330f729Sjoerg     BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
15717330f729Sjoerg     BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1572*82d56013Sjoerg     BasicBlock *FC0ExitBlockSuccessor = FC0.ExitBlock->getUniqueSuccessor();
1573*82d56013Sjoerg 
1574*82d56013Sjoerg     // Move instructions from the exit block of FC0 to the beginning of the exit
1575*82d56013Sjoerg     // block of FC1, in the case that the FC0 loop has not been peeled. In the
1576*82d56013Sjoerg     // case that FC0 loop is peeled, then move the instructions of the successor
1577*82d56013Sjoerg     // of the FC0 Exit block to the beginning of the exit block of FC1.
1578*82d56013Sjoerg     moveInstructionsToTheBeginning(
1579*82d56013Sjoerg         (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1580*82d56013Sjoerg         DT, PDT, DI);
1581*82d56013Sjoerg 
1582*82d56013Sjoerg     // Move instructions from the guard block of FC1 to the end of the guard
1583*82d56013Sjoerg     // block of FC0.
1584*82d56013Sjoerg     moveInstructionsToTheEnd(*FC1GuardBlock, *FC0GuardBlock, DT, PDT, DI);
15857330f729Sjoerg 
15867330f729Sjoerg     assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
15877330f729Sjoerg 
15887330f729Sjoerg     SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
15897330f729Sjoerg 
15907330f729Sjoerg     ////////////////////////////////////////////////////////////////////////////
15917330f729Sjoerg     // Update the Loop Guard
15927330f729Sjoerg     ////////////////////////////////////////////////////////////////////////////
15937330f729Sjoerg     // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
15947330f729Sjoerg     // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
15957330f729Sjoerg     // Thus, one path from the guard goes to the preheader for FC0 (and thus
15967330f729Sjoerg     // executes the new fused loop) and the other path goes to the NonLoopBlock
15977330f729Sjoerg     // for FC1 (where FC1 guard would have gone if FC1 was not executed).
1598*82d56013Sjoerg     FC1NonLoopBlock->replacePhiUsesWith(FC1GuardBlock, FC0GuardBlock);
15997330f729Sjoerg     FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1600*82d56013Sjoerg 
1601*82d56013Sjoerg     BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1602*82d56013Sjoerg     BBToUpdate->getTerminator()->replaceUsesOfWith(FC1GuardBlock, FC1.Header);
16037330f729Sjoerg 
16047330f729Sjoerg     // The guard of FC1 is not necessary anymore.
16057330f729Sjoerg     FC1.GuardBranch->eraseFromParent();
16067330f729Sjoerg     new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
16077330f729Sjoerg 
16087330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16097330f729Sjoerg         DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
16107330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16117330f729Sjoerg         DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
16127330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16137330f729Sjoerg         DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
16147330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16157330f729Sjoerg         DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
16167330f729Sjoerg 
1617*82d56013Sjoerg     if (FC0.Peeled) {
1618*82d56013Sjoerg       // Remove the Block after the ExitBlock of FC0
1619*82d56013Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
1620*82d56013Sjoerg           DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1621*82d56013Sjoerg       FC0ExitBlockSuccessor->getTerminator()->eraseFromParent();
1622*82d56013Sjoerg       new UnreachableInst(FC0ExitBlockSuccessor->getContext(),
1623*82d56013Sjoerg                           FC0ExitBlockSuccessor);
1624*82d56013Sjoerg     }
1625*82d56013Sjoerg 
1626*82d56013Sjoerg     assert(pred_empty(FC1GuardBlock) &&
16277330f729Sjoerg            "Expecting guard block to have no predecessors");
1628*82d56013Sjoerg     assert(succ_empty(FC1GuardBlock) &&
16297330f729Sjoerg            "Expecting guard block to have no successors");
16307330f729Sjoerg 
16317330f729Sjoerg     // Remember the phi nodes originally in the header of FC0 in order to rewire
16327330f729Sjoerg     // them later. However, this is only necessary if the new loop carried
16337330f729Sjoerg     // values might not dominate the exiting branch. While we do not generally
16347330f729Sjoerg     // test if this is the case but simply insert intermediate phi nodes, we
16357330f729Sjoerg     // need to make sure these intermediate phi nodes have different
16367330f729Sjoerg     // predecessors. To this end, we filter the special case where the exiting
16377330f729Sjoerg     // block is the latch block of the first loop. Nothing needs to be done
16387330f729Sjoerg     // anyway as all loop carried values dominate the latch and thereby also the
16397330f729Sjoerg     // exiting branch.
16407330f729Sjoerg     // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
16417330f729Sjoerg     // (because the loops are rotated. Thus, nothing will ever be added to
16427330f729Sjoerg     // OriginalFC0PHIs.
16437330f729Sjoerg     SmallVector<PHINode *, 8> OriginalFC0PHIs;
16447330f729Sjoerg     if (FC0.ExitingBlock != FC0.Latch)
16457330f729Sjoerg       for (PHINode &PHI : FC0.Header->phis())
16467330f729Sjoerg         OriginalFC0PHIs.push_back(&PHI);
16477330f729Sjoerg 
16487330f729Sjoerg     assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
16497330f729Sjoerg 
16507330f729Sjoerg     // Replace incoming blocks for header PHIs first.
16517330f729Sjoerg     FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
16527330f729Sjoerg     FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
16537330f729Sjoerg 
16547330f729Sjoerg     // The old exiting block of the first loop (FC0) has to jump to the header
16557330f729Sjoerg     // of the second as we need to execute the code in the second header block
16567330f729Sjoerg     // regardless of the trip count. That is, if the trip count is 0, so the
16577330f729Sjoerg     // back edge is never taken, we still have to execute both loop headers,
16587330f729Sjoerg     // especially (but not only!) if the second is a do-while style loop.
16597330f729Sjoerg     // However, doing so might invalidate the phi nodes of the first loop as
16607330f729Sjoerg     // the new values do only need to dominate their latch and not the exiting
16617330f729Sjoerg     // predicate. To remedy this potential problem we always introduce phi
16627330f729Sjoerg     // nodes in the header of the second loop later that select the loop carried
16637330f729Sjoerg     // value, if the second header was reached through an old latch of the
16647330f729Sjoerg     // first, or undef otherwise. This is sound as exiting the first implies the
16657330f729Sjoerg     // second will exit too, __without__ taking the back-edge (their
16667330f729Sjoerg     // trip-counts are equal after all).
16677330f729Sjoerg     FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
16687330f729Sjoerg                                                          FC1.Header);
16697330f729Sjoerg 
16707330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16717330f729Sjoerg         DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
16727330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16737330f729Sjoerg         DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
16747330f729Sjoerg 
16757330f729Sjoerg     // Remove FC0 Exit Block
16767330f729Sjoerg     // The exit block for FC0 is no longer needed since control will flow
16777330f729Sjoerg     // directly to the header of FC1. Since it is an empty block, it can be
16787330f729Sjoerg     // removed at this point.
16797330f729Sjoerg     // TODO: In the future, we can handle non-empty exit blocks my merging any
16807330f729Sjoerg     // instructions from FC0 exit block into FC1 exit block prior to removing
16817330f729Sjoerg     // the block.
1682*82d56013Sjoerg     assert(pred_empty(FC0.ExitBlock) && "Expecting exit block to be empty");
16837330f729Sjoerg     FC0.ExitBlock->getTerminator()->eraseFromParent();
16847330f729Sjoerg     new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
16857330f729Sjoerg 
16867330f729Sjoerg     // Remove FC1 Preheader
16877330f729Sjoerg     // The pre-header of L1 is not necessary anymore.
1688*82d56013Sjoerg     assert(pred_empty(FC1.Preheader));
16897330f729Sjoerg     FC1.Preheader->getTerminator()->eraseFromParent();
16907330f729Sjoerg     new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
16917330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(
16927330f729Sjoerg         DominatorTree::Delete, FC1.Preheader, FC1.Header));
16937330f729Sjoerg 
16947330f729Sjoerg     // Moves the phi nodes from the second to the first loops header block.
16957330f729Sjoerg     while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
16967330f729Sjoerg       if (SE.isSCEVable(PHI->getType()))
16977330f729Sjoerg         SE.forgetValue(PHI);
16987330f729Sjoerg       if (PHI->hasNUsesOrMore(1))
16997330f729Sjoerg         PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
17007330f729Sjoerg       else
17017330f729Sjoerg         PHI->eraseFromParent();
17027330f729Sjoerg     }
17037330f729Sjoerg 
17047330f729Sjoerg     // Introduce new phi nodes in the second loop header to ensure
17057330f729Sjoerg     // exiting the first and jumping to the header of the second does not break
17067330f729Sjoerg     // the SSA property of the phis originally in the first loop. See also the
17077330f729Sjoerg     // comment above.
17087330f729Sjoerg     Instruction *L1HeaderIP = &FC1.Header->front();
17097330f729Sjoerg     for (PHINode *LCPHI : OriginalFC0PHIs) {
17107330f729Sjoerg       int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
17117330f729Sjoerg       assert(L1LatchBBIdx >= 0 &&
17127330f729Sjoerg              "Expected loop carried value to be rewired at this point!");
17137330f729Sjoerg 
17147330f729Sjoerg       Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
17157330f729Sjoerg 
17167330f729Sjoerg       PHINode *L1HeaderPHI = PHINode::Create(
17177330f729Sjoerg           LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
17187330f729Sjoerg       L1HeaderPHI->addIncoming(LCV, FC0.Latch);
17197330f729Sjoerg       L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
17207330f729Sjoerg                                FC0.ExitingBlock);
17217330f729Sjoerg 
17227330f729Sjoerg       LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
17237330f729Sjoerg     }
17247330f729Sjoerg 
17257330f729Sjoerg     // Update the latches
17267330f729Sjoerg 
17277330f729Sjoerg     // Replace latch terminator destinations.
17287330f729Sjoerg     FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
17297330f729Sjoerg     FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
17307330f729Sjoerg 
1731*82d56013Sjoerg     // Modify the latch branch of FC0 to be unconditional as both successors of
1732*82d56013Sjoerg     // the branch are the same.
1733*82d56013Sjoerg     simplifyLatchBranch(FC0);
1734*82d56013Sjoerg 
17357330f729Sjoerg     // If FC0.Latch and FC0.ExitingBlock are the same then we have already
17367330f729Sjoerg     // performed the updates above.
17377330f729Sjoerg     if (FC0.Latch != FC0.ExitingBlock)
17387330f729Sjoerg       TreeUpdates.emplace_back(DominatorTree::UpdateType(
17397330f729Sjoerg           DominatorTree::Insert, FC0.Latch, FC1.Header));
17407330f729Sjoerg 
17417330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
17427330f729Sjoerg                                                        FC0.Latch, FC0.Header));
17437330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
17447330f729Sjoerg                                                        FC1.Latch, FC0.Header));
17457330f729Sjoerg     TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
17467330f729Sjoerg                                                        FC1.Latch, FC1.Header));
17477330f729Sjoerg 
17487330f729Sjoerg     // All done
17497330f729Sjoerg     // Apply the updates to the Dominator Tree and cleanup.
17507330f729Sjoerg 
1751*82d56013Sjoerg     assert(succ_empty(FC1GuardBlock) && "FC1GuardBlock has successors!!");
1752*82d56013Sjoerg     assert(pred_empty(FC1GuardBlock) && "FC1GuardBlock has predecessors!!");
17537330f729Sjoerg 
17547330f729Sjoerg     // Update DT/PDT
17557330f729Sjoerg     DTU.applyUpdates(TreeUpdates);
17567330f729Sjoerg 
1757*82d56013Sjoerg     LI.removeBlock(FC1GuardBlock);
17587330f729Sjoerg     LI.removeBlock(FC1.Preheader);
1759*82d56013Sjoerg     LI.removeBlock(FC0.ExitBlock);
1760*82d56013Sjoerg     if (FC0.Peeled) {
1761*82d56013Sjoerg       LI.removeBlock(FC0ExitBlockSuccessor);
1762*82d56013Sjoerg       DTU.deleteBB(FC0ExitBlockSuccessor);
1763*82d56013Sjoerg     }
1764*82d56013Sjoerg     DTU.deleteBB(FC1GuardBlock);
17657330f729Sjoerg     DTU.deleteBB(FC1.Preheader);
17667330f729Sjoerg     DTU.deleteBB(FC0.ExitBlock);
17677330f729Sjoerg     DTU.flush();
17687330f729Sjoerg 
17697330f729Sjoerg     // Is there a way to keep SE up-to-date so we don't need to forget the loops
17707330f729Sjoerg     // and rebuild the information in subsequent passes of fusion?
1771*82d56013Sjoerg     // Note: Need to forget the loops before merging the loop latches, as
1772*82d56013Sjoerg     // mergeLatch may remove the only block in FC1.
17737330f729Sjoerg     SE.forgetLoop(FC1.L);
17747330f729Sjoerg     SE.forgetLoop(FC0.L);
17757330f729Sjoerg 
1776*82d56013Sjoerg     // Move instructions from FC0.Latch to FC1.Latch.
1777*82d56013Sjoerg     // Note: mergeLatch requires an updated DT.
1778*82d56013Sjoerg     mergeLatch(FC0, FC1);
1779*82d56013Sjoerg 
17807330f729Sjoerg     // Merge the loops.
1781*82d56013Sjoerg     SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
17827330f729Sjoerg     for (BasicBlock *BB : Blocks) {
17837330f729Sjoerg       FC0.L->addBlockEntry(BB);
17847330f729Sjoerg       FC1.L->removeBlockFromLoop(BB);
17857330f729Sjoerg       if (LI.getLoopFor(BB) != FC1.L)
17867330f729Sjoerg         continue;
17877330f729Sjoerg       LI.changeLoopFor(BB, FC0.L);
17887330f729Sjoerg     }
1789*82d56013Sjoerg     while (!FC1.L->isInnermost()) {
17907330f729Sjoerg       const auto &ChildLoopIt = FC1.L->begin();
17917330f729Sjoerg       Loop *ChildLoop = *ChildLoopIt;
17927330f729Sjoerg       FC1.L->removeChildLoop(ChildLoopIt);
17937330f729Sjoerg       FC0.L->addChildLoop(ChildLoop);
17947330f729Sjoerg     }
17957330f729Sjoerg 
17967330f729Sjoerg     // Delete the now empty loop L1.
17977330f729Sjoerg     LI.erase(FC1.L);
17987330f729Sjoerg 
17997330f729Sjoerg #ifndef NDEBUG
18007330f729Sjoerg     assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
18017330f729Sjoerg     assert(DT.verify(DominatorTree::VerificationLevel::Fast));
18027330f729Sjoerg     assert(PDT.verify());
18037330f729Sjoerg     LI.verify(DT);
18047330f729Sjoerg     SE.verify();
18057330f729Sjoerg #endif
18067330f729Sjoerg 
18077330f729Sjoerg     LLVM_DEBUG(dbgs() << "Fusion done:\n");
18087330f729Sjoerg 
18097330f729Sjoerg     return FC0.L;
18107330f729Sjoerg   }
18117330f729Sjoerg };
18127330f729Sjoerg 
18137330f729Sjoerg struct LoopFuseLegacy : public FunctionPass {
18147330f729Sjoerg 
18157330f729Sjoerg   static char ID;
18167330f729Sjoerg 
LoopFuseLegacy__anonc3322b0b0111::LoopFuseLegacy18177330f729Sjoerg   LoopFuseLegacy() : FunctionPass(ID) {
18187330f729Sjoerg     initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry());
18197330f729Sjoerg   }
18207330f729Sjoerg 
getAnalysisUsage__anonc3322b0b0111::LoopFuseLegacy18217330f729Sjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
18227330f729Sjoerg     AU.addRequiredID(LoopSimplifyID);
18237330f729Sjoerg     AU.addRequired<ScalarEvolutionWrapperPass>();
18247330f729Sjoerg     AU.addRequired<LoopInfoWrapperPass>();
18257330f729Sjoerg     AU.addRequired<DominatorTreeWrapperPass>();
18267330f729Sjoerg     AU.addRequired<PostDominatorTreeWrapperPass>();
18277330f729Sjoerg     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
18287330f729Sjoerg     AU.addRequired<DependenceAnalysisWrapperPass>();
1829*82d56013Sjoerg     AU.addRequired<AssumptionCacheTracker>();
1830*82d56013Sjoerg     AU.addRequired<TargetTransformInfoWrapperPass>();
18317330f729Sjoerg 
18327330f729Sjoerg     AU.addPreserved<ScalarEvolutionWrapperPass>();
18337330f729Sjoerg     AU.addPreserved<LoopInfoWrapperPass>();
18347330f729Sjoerg     AU.addPreserved<DominatorTreeWrapperPass>();
18357330f729Sjoerg     AU.addPreserved<PostDominatorTreeWrapperPass>();
18367330f729Sjoerg   }
18377330f729Sjoerg 
runOnFunction__anonc3322b0b0111::LoopFuseLegacy18387330f729Sjoerg   bool runOnFunction(Function &F) override {
18397330f729Sjoerg     if (skipFunction(F))
18407330f729Sjoerg       return false;
18417330f729Sjoerg     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
18427330f729Sjoerg     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
18437330f729Sjoerg     auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
18447330f729Sjoerg     auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
18457330f729Sjoerg     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
18467330f729Sjoerg     auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1847*82d56013Sjoerg     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1848*82d56013Sjoerg     const TargetTransformInfo &TTI =
1849*82d56013Sjoerg         getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
18507330f729Sjoerg     const DataLayout &DL = F.getParent()->getDataLayout();
1851*82d56013Sjoerg 
1852*82d56013Sjoerg     LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
18537330f729Sjoerg     return LF.fuseLoops(F);
18547330f729Sjoerg   }
18557330f729Sjoerg };
18567330f729Sjoerg } // namespace
18577330f729Sjoerg 
run(Function & F,FunctionAnalysisManager & AM)18587330f729Sjoerg PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) {
18597330f729Sjoerg   auto &LI = AM.getResult<LoopAnalysis>(F);
18607330f729Sjoerg   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
18617330f729Sjoerg   auto &DI = AM.getResult<DependenceAnalysis>(F);
18627330f729Sjoerg   auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
18637330f729Sjoerg   auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
18647330f729Sjoerg   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1865*82d56013Sjoerg   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1866*82d56013Sjoerg   const TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
18677330f729Sjoerg   const DataLayout &DL = F.getParent()->getDataLayout();
1868*82d56013Sjoerg 
1869*82d56013Sjoerg   LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
18707330f729Sjoerg   bool Changed = LF.fuseLoops(F);
18717330f729Sjoerg   if (!Changed)
18727330f729Sjoerg     return PreservedAnalyses::all();
18737330f729Sjoerg 
18747330f729Sjoerg   PreservedAnalyses PA;
18757330f729Sjoerg   PA.preserve<DominatorTreeAnalysis>();
18767330f729Sjoerg   PA.preserve<PostDominatorTreeAnalysis>();
18777330f729Sjoerg   PA.preserve<ScalarEvolutionAnalysis>();
18787330f729Sjoerg   PA.preserve<LoopAnalysis>();
18797330f729Sjoerg   return PA;
18807330f729Sjoerg }
18817330f729Sjoerg 
18827330f729Sjoerg char LoopFuseLegacy::ID = 0;
18837330f729Sjoerg 
18847330f729Sjoerg INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false,
18857330f729Sjoerg                       false)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)18867330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
18877330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
18887330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
18897330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
18907330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
18917330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
1892*82d56013Sjoerg INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1893*82d56013Sjoerg INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
18947330f729Sjoerg INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false)
18957330f729Sjoerg 
18967330f729Sjoerg FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); }
1897