xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
163faed5bSDimitry Andric //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
263faed5bSDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
663faed5bSDimitry Andric //
763faed5bSDimitry Andric //===----------------------------------------------------------------------===//
863faed5bSDimitry Andric //
963faed5bSDimitry Andric // This file implements some loop unrolling utilities for loops with run-time
1063faed5bSDimitry Andric // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
1163faed5bSDimitry Andric // trip counts.
1263faed5bSDimitry Andric //
1363faed5bSDimitry Andric // The functions in this file are used to generate extra code when the
1463faed5bSDimitry Andric // run-time trip count modulo the unroll factor is not 0.  When this is the
1563faed5bSDimitry Andric // case, we need to generate code to execute these 'left over' iterations.
1663faed5bSDimitry Andric //
1763faed5bSDimitry Andric // The current strategy generates an if-then-else sequence prior to the
1801095a5dSDimitry Andric // unrolled loop to execute the 'left over' iterations before or after the
1901095a5dSDimitry Andric // unrolled loop.
2063faed5bSDimitry Andric //
2163faed5bSDimitry Andric //===----------------------------------------------------------------------===//
2263faed5bSDimitry Andric 
2363faed5bSDimitry Andric #include "llvm/ADT/Statistic.h"
24145449b1SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
25c0981da4SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
2663faed5bSDimitry Andric #include "llvm/Analysis/LoopIterator.h"
2763faed5bSDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
28145449b1SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
294a16efa3SDimitry Andric #include "llvm/IR/BasicBlock.h"
305a5ac124SDimitry Andric #include "llvm/IR/Dominators.h"
31b60736ecSDimitry Andric #include "llvm/IR/MDBuilder.h"
325a5ac124SDimitry Andric #include "llvm/IR/Module.h"
33e3b55780SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
34706b4fc4SDimitry Andric #include "llvm/Support/CommandLine.h"
3563faed5bSDimitry Andric #include "llvm/Support/Debug.h"
3663faed5bSDimitry Andric #include "llvm/Support/raw_ostream.h"
3763faed5bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3863faed5bSDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
39c0981da4SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
409df3605dSDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
41cfca06d7SDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
427ab83427SDimitry Andric #include "llvm/Transforms/Utils/UnrollLoop.h"
4363faed5bSDimitry Andric #include <algorithm>
4463faed5bSDimitry Andric 
4563faed5bSDimitry Andric using namespace llvm;
4663faed5bSDimitry Andric 
475ca98fd9SDimitry Andric #define DEBUG_TYPE "loop-unroll"
485ca98fd9SDimitry Andric 
4963faed5bSDimitry Andric STATISTIC(NumRuntimeUnrolled,
5063faed5bSDimitry Andric           "Number of loops unrolled with run-time trip counts");
519df3605dSDimitry Andric static cl::opt<bool> UnrollRuntimeMultiExit(
529df3605dSDimitry Andric     "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
539df3605dSDimitry Andric     cl::desc("Allow runtime unrolling for loops with multiple exits, when "
549df3605dSDimitry Andric              "epilog is generated"));
55344a3780SDimitry Andric static cl::opt<bool> UnrollRuntimeOtherExitPredictable(
56344a3780SDimitry Andric     "unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden,
57344a3780SDimitry Andric     cl::desc("Assume the non latch exit block to be predictable"));
5863faed5bSDimitry Andric 
59b1c73532SDimitry Andric // Probability that the loop trip count is so small that after the prolog
60b1c73532SDimitry Andric // we do not enter the unrolled loop at all.
61b1c73532SDimitry Andric // It is unlikely that the loop trip count is smaller than the unroll factor;
62b1c73532SDimitry Andric // other than that, the choice of constant is not tuned yet.
63b1c73532SDimitry Andric static const uint32_t UnrolledLoopHeaderWeights[] = {1, 127};
64b1c73532SDimitry Andric // Probability that the loop trip count is so small that we skip the unrolled
65b1c73532SDimitry Andric // loop completely and immediately enter the epilogue loop.
66b1c73532SDimitry Andric // It is unlikely that the loop trip count is smaller than the unroll factor;
67b1c73532SDimitry Andric // other than that, the choice of constant is not tuned yet.
68b1c73532SDimitry Andric static const uint32_t EpilogHeaderWeights[] = {1, 127};
69b1c73532SDimitry Andric 
7063faed5bSDimitry Andric /// Connect the unrolling prolog code to the original loop.
7163faed5bSDimitry Andric /// The unrolling prolog code contains code to execute the
7263faed5bSDimitry Andric /// 'extra' iterations if the run-time trip count modulo the
7363faed5bSDimitry Andric /// unroll count is non-zero.
7463faed5bSDimitry Andric ///
7563faed5bSDimitry Andric /// This function performs the following:
7663faed5bSDimitry Andric /// - Create PHI nodes at prolog end block to combine values
7763faed5bSDimitry Andric ///   that exit the prolog code and jump around the prolog.
7863faed5bSDimitry Andric /// - Add a PHI operand to a PHI node at the loop exit block
7963faed5bSDimitry Andric ///   for values that exit the prolog and go around the loop.
8063faed5bSDimitry Andric /// - Branch around the original loop if the trip count is less
8163faed5bSDimitry Andric ///   than the unroll factor.
8263faed5bSDimitry Andric ///
ConnectProlog(Loop * L,Value * BECount,unsigned Count,BasicBlock * PrologExit,BasicBlock * OriginalLoopLatchExit,BasicBlock * PreHeader,BasicBlock * NewPreHeader,ValueToValueMapTy & VMap,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA,ScalarEvolution & SE)838af9f201SDimitry Andric static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
84ca089b24SDimitry Andric                           BasicBlock *PrologExit,
85ca089b24SDimitry Andric                           BasicBlock *OriginalLoopLatchExit,
86ca089b24SDimitry Andric                           BasicBlock *PreHeader, BasicBlock *NewPreHeader,
87ca089b24SDimitry Andric                           ValueToValueMapTy &VMap, DominatorTree *DT,
88145449b1SDimitry Andric                           LoopInfo *LI, bool PreserveLCSSA,
89145449b1SDimitry Andric                           ScalarEvolution &SE) {
90d8e91e46SDimitry Andric   // Loop structure should be the following:
91d8e91e46SDimitry Andric   // Preheader
92d8e91e46SDimitry Andric   //  PrologHeader
93d8e91e46SDimitry Andric   //  ...
94d8e91e46SDimitry Andric   //  PrologLatch
95d8e91e46SDimitry Andric   //  PrologExit
96d8e91e46SDimitry Andric   //   NewPreheader
97d8e91e46SDimitry Andric   //    Header
98d8e91e46SDimitry Andric   //    ...
99d8e91e46SDimitry Andric   //    Latch
100d8e91e46SDimitry Andric   //      LatchExit
10163faed5bSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
1025ca98fd9SDimitry Andric   assert(Latch && "Loop must have a latch");
10301095a5dSDimitry Andric   BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
10463faed5bSDimitry Andric 
10563faed5bSDimitry Andric   // Create a PHI node for each outgoing value from the original loop
10663faed5bSDimitry Andric   // (which means it is an outgoing value from the prolog code too).
10763faed5bSDimitry Andric   // The new PHI node is inserted in the prolog end basic block.
10801095a5dSDimitry Andric   // The new PHI node value is added as an operand of a PHI node in either
10963faed5bSDimitry Andric   // the loop header or the loop exit block.
11001095a5dSDimitry Andric   for (BasicBlock *Succ : successors(Latch)) {
111eb11fae6SDimitry Andric     for (PHINode &PN : Succ->phis()) {
11263faed5bSDimitry Andric       // Add a new PHI node to the prolog end block and add the
11363faed5bSDimitry Andric       // appropriate incoming values.
114d8e91e46SDimitry Andric       // TODO: This code assumes that the PrologExit (or the LatchExit block for
115d8e91e46SDimitry Andric       // prolog loop) contains only one predecessor from the loop, i.e. the
116d8e91e46SDimitry Andric       // PrologLatch. When supporting multiple-exiting block loops, we can have
117d8e91e46SDimitry Andric       // two or more blocks that have the LatchExit as the target in the
118d8e91e46SDimitry Andric       // original loop.
119b1c73532SDimitry Andric       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr");
120b1c73532SDimitry Andric       NewPN->insertBefore(PrologExit->getFirstNonPHIIt());
12163faed5bSDimitry Andric       // Adding a value to the new PHI node from the original loop preheader.
12263faed5bSDimitry Andric       // This is the value that skips all the prolog code.
123eb11fae6SDimitry Andric       if (L->contains(&PN)) {
124d8e91e46SDimitry Andric         // Succ is loop header.
125eb11fae6SDimitry Andric         NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
12601095a5dSDimitry Andric                            PreHeader);
12763faed5bSDimitry Andric       } else {
128d8e91e46SDimitry Andric         // Succ is LatchExit.
129ac9a064cSDimitry Andric         NewPN->addIncoming(PoisonValue::get(PN.getType()), PreHeader);
13063faed5bSDimitry Andric       }
13163faed5bSDimitry Andric 
132eb11fae6SDimitry Andric       Value *V = PN.getIncomingValueForBlock(Latch);
13363faed5bSDimitry Andric       if (Instruction *I = dyn_cast<Instruction>(V)) {
13463faed5bSDimitry Andric         if (L->contains(I)) {
13501095a5dSDimitry Andric           V = VMap.lookup(I);
13663faed5bSDimitry Andric         }
13763faed5bSDimitry Andric       }
13863faed5bSDimitry Andric       // Adding a value to the new PHI node from the last prolog block
13963faed5bSDimitry Andric       // that was created.
14001095a5dSDimitry Andric       NewPN->addIncoming(V, PrologLatch);
14163faed5bSDimitry Andric 
14263faed5bSDimitry Andric       // Update the existing PHI node operand with the value from the
14363faed5bSDimitry Andric       // new PHI node.  How this is done depends on if the existing
14463faed5bSDimitry Andric       // PHI node is in the original loop block, or the exit block.
145e6d15924SDimitry Andric       if (L->contains(&PN))
146e6d15924SDimitry Andric         PN.setIncomingValueForBlock(NewPreHeader, NewPN);
147e6d15924SDimitry Andric       else
148eb11fae6SDimitry Andric         PN.addIncoming(NewPN, PrologExit);
149145449b1SDimitry Andric       SE.forgetValue(&PN);
15063faed5bSDimitry Andric     }
15163faed5bSDimitry Andric   }
15263faed5bSDimitry Andric 
153b915e9e0SDimitry Andric   // Make sure that created prolog loop is in simplified form
154b915e9e0SDimitry Andric   SmallVector<BasicBlock *, 4> PrologExitPreds;
155b915e9e0SDimitry Andric   Loop *PrologLoop = LI->getLoopFor(PrologLatch);
156b915e9e0SDimitry Andric   if (PrologLoop) {
157b915e9e0SDimitry Andric     for (BasicBlock *PredBB : predecessors(PrologExit))
158b915e9e0SDimitry Andric       if (PrologLoop->contains(PredBB))
159b915e9e0SDimitry Andric         PrologExitPreds.push_back(PredBB);
160b915e9e0SDimitry Andric 
161b915e9e0SDimitry Andric     SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
162d8e91e46SDimitry Andric                            nullptr, PreserveLCSSA);
163b915e9e0SDimitry Andric   }
164b915e9e0SDimitry Andric 
16501095a5dSDimitry Andric   // Create a branch around the original loop, which is taken if there are no
1668af9f201SDimitry Andric   // iterations remaining to be executed after running the prologue.
16701095a5dSDimitry Andric   Instruction *InsertPt = PrologExit->getTerminator();
1683a0822f0SDimitry Andric   IRBuilder<> B(InsertPt);
1698af9f201SDimitry Andric 
1708af9f201SDimitry Andric   assert(Count != 0 && "nonsensical Count!");
1718af9f201SDimitry Andric 
17201095a5dSDimitry Andric   // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
17301095a5dSDimitry Andric   // This means %xtraiter is (BECount + 1) and all of the iterations of this
17401095a5dSDimitry Andric   // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
17501095a5dSDimitry Andric   // then (BECount + 1) cannot unsigned-overflow.
1763a0822f0SDimitry Andric   Value *BrLoopExit =
1773a0822f0SDimitry Andric       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
17863faed5bSDimitry Andric   // Split the exit to maintain loop canonicalization guarantees
179ca089b24SDimitry Andric   SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
180ca089b24SDimitry Andric   SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
181d8e91e46SDimitry Andric                          nullptr, PreserveLCSSA);
18263faed5bSDimitry Andric   // Add the branch to the exit block (around the unrolled loop)
183b1c73532SDimitry Andric   MDNode *BranchWeights = nullptr;
184b1c73532SDimitry Andric   if (hasBranchWeightMD(*Latch->getTerminator())) {
185b1c73532SDimitry Andric     // Assume loop is nearly always entered.
186b1c73532SDimitry Andric     MDBuilder MDB(B.getContext());
187b1c73532SDimitry Andric     BranchWeights = MDB.createBranchWeights(UnrolledLoopHeaderWeights);
188b1c73532SDimitry Andric   }
189b1c73532SDimitry Andric   B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader,
190b1c73532SDimitry Andric                  BranchWeights);
19101095a5dSDimitry Andric   InsertPt->eraseFromParent();
192c0981da4SDimitry Andric   if (DT) {
193c0981da4SDimitry Andric     auto *NewDom = DT->findNearestCommonDominator(OriginalLoopLatchExit,
194c0981da4SDimitry Andric                                                   PrologExit);
195c0981da4SDimitry Andric     DT->changeImmediateDominator(OriginalLoopLatchExit, NewDom);
196c0981da4SDimitry Andric   }
19701095a5dSDimitry Andric }
19801095a5dSDimitry Andric 
19901095a5dSDimitry Andric /// Connect the unrolling epilog code to the original loop.
20001095a5dSDimitry Andric /// The unrolling epilog code contains code to execute the
20101095a5dSDimitry Andric /// 'extra' iterations if the run-time trip count modulo the
20201095a5dSDimitry Andric /// unroll count is non-zero.
20301095a5dSDimitry Andric ///
20401095a5dSDimitry Andric /// This function performs the following:
20501095a5dSDimitry Andric /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
20601095a5dSDimitry Andric /// - Create PHI nodes at the unrolling loop exit to combine
20701095a5dSDimitry Andric ///   values that exit the unrolling loop code and jump around it.
20801095a5dSDimitry Andric /// - Update PHI operands in the epilog loop by the new PHI nodes
20901095a5dSDimitry Andric /// - Branch around the epilog loop if extra iters (ModVal) is zero.
21001095a5dSDimitry Andric ///
ConnectEpilog(Loop * L,Value * ModVal,BasicBlock * NewExit,BasicBlock * Exit,BasicBlock * PreHeader,BasicBlock * EpilogPreHeader,BasicBlock * NewPreHeader,ValueToValueMapTy & VMap,DominatorTree * DT,LoopInfo * LI,bool PreserveLCSSA,ScalarEvolution & SE,unsigned Count)21101095a5dSDimitry Andric static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
21201095a5dSDimitry Andric                           BasicBlock *Exit, BasicBlock *PreHeader,
21301095a5dSDimitry Andric                           BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
21401095a5dSDimitry Andric                           ValueToValueMapTy &VMap, DominatorTree *DT,
215b1c73532SDimitry Andric                           LoopInfo *LI, bool PreserveLCSSA, ScalarEvolution &SE,
216b1c73532SDimitry Andric                           unsigned Count) {
21701095a5dSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
21801095a5dSDimitry Andric   assert(Latch && "Loop must have a latch");
21901095a5dSDimitry Andric   BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
22001095a5dSDimitry Andric 
22101095a5dSDimitry Andric   // Loop structure should be the following:
22201095a5dSDimitry Andric   //
22301095a5dSDimitry Andric   // PreHeader
22401095a5dSDimitry Andric   // NewPreHeader
22501095a5dSDimitry Andric   //   Header
22601095a5dSDimitry Andric   //   ...
22701095a5dSDimitry Andric   //   Latch
22801095a5dSDimitry Andric   // NewExit (PN)
22901095a5dSDimitry Andric   // EpilogPreHeader
23001095a5dSDimitry Andric   //   EpilogHeader
23101095a5dSDimitry Andric   //   ...
23201095a5dSDimitry Andric   //   EpilogLatch
23301095a5dSDimitry Andric   // Exit (EpilogPN)
23401095a5dSDimitry Andric 
23501095a5dSDimitry Andric   // Update PHI nodes at NewExit and Exit.
236eb11fae6SDimitry Andric   for (PHINode &PN : NewExit->phis()) {
23701095a5dSDimitry Andric     // PN should be used in another PHI located in Exit block as
23801095a5dSDimitry Andric     // Exit was split by SplitBlockPredecessors into Exit and NewExit
239e3b55780SDimitry Andric     // Basically it should look like:
24001095a5dSDimitry Andric     // NewExit:
24101095a5dSDimitry Andric     //   PN = PHI [I, Latch]
24201095a5dSDimitry Andric     // ...
24301095a5dSDimitry Andric     // Exit:
244c0981da4SDimitry Andric     //   EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
245c0981da4SDimitry Andric     //
246c0981da4SDimitry Andric     // Exits from non-latch blocks point to the original exit block and the
247c0981da4SDimitry Andric     // epilogue edges have already been added.
24801095a5dSDimitry Andric     //
24901095a5dSDimitry Andric     // There is EpilogPreHeader incoming block instead of NewExit as
25001095a5dSDimitry Andric     // NewExit was spilt 1 more time to get EpilogPreHeader.
251eb11fae6SDimitry Andric     assert(PN.hasOneUse() && "The phi should have 1 use");
252eb11fae6SDimitry Andric     PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
25301095a5dSDimitry Andric     assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
25401095a5dSDimitry Andric 
25501095a5dSDimitry Andric     // Add incoming PreHeader from branch around the Loop
256ac9a064cSDimitry Andric     PN.addIncoming(PoisonValue::get(PN.getType()), PreHeader);
257145449b1SDimitry Andric     SE.forgetValue(&PN);
25801095a5dSDimitry Andric 
259eb11fae6SDimitry Andric     Value *V = PN.getIncomingValueForBlock(Latch);
26001095a5dSDimitry Andric     Instruction *I = dyn_cast<Instruction>(V);
26101095a5dSDimitry Andric     if (I && L->contains(I))
26201095a5dSDimitry Andric       // If value comes from an instruction in the loop add VMap value.
26301095a5dSDimitry Andric       V = VMap.lookup(I);
26401095a5dSDimitry Andric     // For the instruction out of the loop, constant or undefined value
26501095a5dSDimitry Andric     // insert value itself.
26601095a5dSDimitry Andric     EpilogPN->addIncoming(V, EpilogLatch);
26701095a5dSDimitry Andric 
26801095a5dSDimitry Andric     assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
26901095a5dSDimitry Andric           "EpilogPN should have EpilogPreHeader incoming block");
27001095a5dSDimitry Andric     // Change EpilogPreHeader incoming block to NewExit.
27101095a5dSDimitry Andric     EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
27201095a5dSDimitry Andric                                NewExit);
27301095a5dSDimitry Andric     // Now PHIs should look like:
27401095a5dSDimitry Andric     // NewExit:
275ac9a064cSDimitry Andric     //   PN = PHI [I, Latch], [poison, PreHeader]
27601095a5dSDimitry Andric     // ...
27701095a5dSDimitry Andric     // Exit:
27801095a5dSDimitry Andric     //   EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
27901095a5dSDimitry Andric   }
28001095a5dSDimitry Andric 
28101095a5dSDimitry Andric   // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
28201095a5dSDimitry Andric   // Update corresponding PHI nodes in epilog loop.
28301095a5dSDimitry Andric   for (BasicBlock *Succ : successors(Latch)) {
28401095a5dSDimitry Andric     // Skip this as we already updated phis in exit blocks.
28501095a5dSDimitry Andric     if (!L->contains(Succ))
28601095a5dSDimitry Andric       continue;
287eb11fae6SDimitry Andric     for (PHINode &PN : Succ->phis()) {
28801095a5dSDimitry Andric       // Add new PHI nodes to the loop exit block and update epilog
28901095a5dSDimitry Andric       // PHIs with the new PHI values.
290b1c73532SDimitry Andric       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr");
291b1c73532SDimitry Andric       NewPN->insertBefore(NewExit->getFirstNonPHIIt());
29201095a5dSDimitry Andric       // Adding a value to the new PHI node from the unrolling loop preheader.
293eb11fae6SDimitry Andric       NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
29401095a5dSDimitry Andric       // Adding a value to the new PHI node from the unrolling loop latch.
295eb11fae6SDimitry Andric       NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
29601095a5dSDimitry Andric 
29701095a5dSDimitry Andric       // Update the existing PHI node operand with the value from the new PHI
29801095a5dSDimitry Andric       // node.  Corresponding instruction in epilog loop should be PHI.
299eb11fae6SDimitry Andric       PHINode *VPN = cast<PHINode>(VMap[&PN]);
300e6d15924SDimitry Andric       VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN);
30101095a5dSDimitry Andric     }
30201095a5dSDimitry Andric   }
30301095a5dSDimitry Andric 
30401095a5dSDimitry Andric   Instruction *InsertPt = NewExit->getTerminator();
30501095a5dSDimitry Andric   IRBuilder<> B(InsertPt);
30601095a5dSDimitry Andric   Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
30701095a5dSDimitry Andric   assert(Exit && "Loop must have a single exit block only");
30871d5a254SDimitry Andric   // Split the epilogue exit to maintain loop canonicalization guarantees
30901095a5dSDimitry Andric   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
310d8e91e46SDimitry Andric   SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
31101095a5dSDimitry Andric                          PreserveLCSSA);
31201095a5dSDimitry Andric   // Add the branch to the exit block (around the unrolling loop)
313b1c73532SDimitry Andric   MDNode *BranchWeights = nullptr;
314b1c73532SDimitry Andric   if (hasBranchWeightMD(*Latch->getTerminator())) {
315b1c73532SDimitry Andric     // Assume equal distribution in interval [0, Count).
316b1c73532SDimitry Andric     MDBuilder MDB(B.getContext());
317b1c73532SDimitry Andric     BranchWeights = MDB.createBranchWeights(1, Count - 1);
318b1c73532SDimitry Andric   }
319b1c73532SDimitry Andric   B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit, BranchWeights);
32063faed5bSDimitry Andric   InsertPt->eraseFromParent();
321c0981da4SDimitry Andric   if (DT) {
322c0981da4SDimitry Andric     auto *NewDom = DT->findNearestCommonDominator(Exit, NewExit);
323c0981da4SDimitry Andric     DT->changeImmediateDominator(Exit, NewDom);
324c0981da4SDimitry Andric   }
32571d5a254SDimitry Andric 
32671d5a254SDimitry Andric   // Split the main loop exit to maintain canonicalization guarantees.
32771d5a254SDimitry Andric   SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
328d8e91e46SDimitry Andric   SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
32971d5a254SDimitry Andric                          PreserveLCSSA);
33063faed5bSDimitry Andric }
33163faed5bSDimitry Andric 
332c0981da4SDimitry Andric /// Create a clone of the blocks in a loop and connect them together. A new
333c0981da4SDimitry Andric /// loop will be created including all cloned blocks, and the iterator of the
334c0981da4SDimitry Andric /// new loop switched to count NewIter down to 0.
33501095a5dSDimitry Andric /// The cloned blocks should be inserted between InsertTop and InsertBot.
336c0981da4SDimitry Andric /// InsertTop should be new preheader, InsertBot new loop exit.
337c0981da4SDimitry Andric /// Returns the new cloned loop that is created.
3389df3605dSDimitry Andric static Loop *
CloneLoopBlocks(Loop * L,Value * NewIter,const bool UseEpilogRemainder,const bool UnrollRemainder,BasicBlock * InsertTop,BasicBlock * InsertBot,BasicBlock * Preheader,std::vector<BasicBlock * > & NewBlocks,LoopBlocksDFS & LoopBlocks,ValueToValueMapTy & VMap,DominatorTree * DT,LoopInfo * LI,unsigned Count)339c0981da4SDimitry Andric CloneLoopBlocks(Loop *L, Value *NewIter, const bool UseEpilogRemainder,
340c0981da4SDimitry Andric                 const bool UnrollRemainder,
341044eb2f6SDimitry Andric                 BasicBlock *InsertTop,
3429df3605dSDimitry Andric                 BasicBlock *InsertBot, BasicBlock *Preheader,
343b1c73532SDimitry Andric                              std::vector<BasicBlock *> &NewBlocks,
344b1c73532SDimitry Andric                              LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
345b1c73532SDimitry Andric                              DominatorTree *DT, LoopInfo *LI, unsigned Count) {
34601095a5dSDimitry Andric   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
34763faed5bSDimitry Andric   BasicBlock *Header = L->getHeader();
34863faed5bSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
34963faed5bSDimitry Andric   Function *F = Header->getParent();
35063faed5bSDimitry Andric   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
35163faed5bSDimitry Andric   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
35267c32a98SDimitry Andric   Loop *ParentLoop = L->getParentLoop();
353581a6d85SDimitry Andric   NewLoopsMap NewLoops;
35471d5a254SDimitry Andric   NewLoops[ParentLoop] = ParentLoop;
355c60b9581SDimitry Andric 
35663faed5bSDimitry Andric   // For each block in the original loop, create a new copy,
35763faed5bSDimitry Andric   // and update the value map with the newly created values.
35863faed5bSDimitry Andric   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
35901095a5dSDimitry Andric     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
36063faed5bSDimitry Andric     NewBlocks.push_back(NewBB);
36163faed5bSDimitry Andric 
362581a6d85SDimitry Andric     addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
36363faed5bSDimitry Andric 
36463faed5bSDimitry Andric     VMap[*BB] = NewBB;
36563faed5bSDimitry Andric     if (Header == *BB) {
36663faed5bSDimitry Andric       // For the first block, add a CFG connection to this newly
36767c32a98SDimitry Andric       // created block.
36863faed5bSDimitry Andric       InsertTop->getTerminator()->setSuccessor(0, NewBB);
36967c32a98SDimitry Andric     }
37001095a5dSDimitry Andric 
37171d5a254SDimitry Andric     if (DT) {
37271d5a254SDimitry Andric       if (Header == *BB) {
37371d5a254SDimitry Andric         // The header is dominated by the preheader.
37471d5a254SDimitry Andric         DT->addNewBlock(NewBB, InsertTop);
37571d5a254SDimitry Andric       } else {
37671d5a254SDimitry Andric         // Copy information from original loop to unrolled loop.
37771d5a254SDimitry Andric         BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
37871d5a254SDimitry Andric         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
37971d5a254SDimitry Andric       }
38071d5a254SDimitry Andric     }
38171d5a254SDimitry Andric 
38267c32a98SDimitry Andric     if (Latch == *BB) {
383c0981da4SDimitry Andric       // For the last block, create a loop back to cloned head.
38467c32a98SDimitry Andric       VMap.erase((*BB)->getTerminator());
385c0981da4SDimitry Andric       // Use an incrementing IV.  Pre-incr/post-incr is backedge/trip count.
386c0981da4SDimitry Andric       // Subtle: NewIter can be 0 if we wrapped when computing the trip count,
387c0981da4SDimitry Andric       // thus we must compare the post-increment (wrapping) value.
38867c32a98SDimitry Andric       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
38967c32a98SDimitry Andric       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
3903a0822f0SDimitry Andric       IRBuilder<> Builder(LatchBR);
391b1c73532SDimitry Andric       PHINode *NewIdx =
392b1c73532SDimitry Andric           PHINode::Create(NewIter->getType(), 2, suffix + ".iter");
393b1c73532SDimitry Andric       NewIdx->insertBefore(FirstLoopBB->getFirstNonPHIIt());
394c0981da4SDimitry Andric       auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
395c0981da4SDimitry Andric       auto *One = ConstantInt::get(NewIdx->getType(), 1);
396b1c73532SDimitry Andric       Value *IdxNext =
397b1c73532SDimitry Andric           Builder.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
398c0981da4SDimitry Andric       Value *IdxCmp = Builder.CreateICmpNE(IdxNext, NewIter, NewIdx->getName() + ".cmp");
399b1c73532SDimitry Andric       MDNode *BranchWeights = nullptr;
400b1c73532SDimitry Andric       if (hasBranchWeightMD(*LatchBR)) {
401b1c73532SDimitry Andric         uint32_t ExitWeight;
402b1c73532SDimitry Andric         uint32_t BackEdgeWeight;
403b1c73532SDimitry Andric         if (Count >= 3) {
404b1c73532SDimitry Andric           // Note: We do not enter this loop for zero-remainders. The check
405b1c73532SDimitry Andric           // is at the end of the loop. We assume equal distribution between
406b1c73532SDimitry Andric           // possible remainders in [1, Count).
407b1c73532SDimitry Andric           ExitWeight = 1;
408b1c73532SDimitry Andric           BackEdgeWeight = (Count - 2) / 2;
409b1c73532SDimitry Andric         } else {
410b1c73532SDimitry Andric           // Unnecessary backedge, should never be taken. The conditional
411b1c73532SDimitry Andric           // jump should be optimized away later.
412b1c73532SDimitry Andric           ExitWeight = 1;
413b1c73532SDimitry Andric           BackEdgeWeight = 0;
414b1c73532SDimitry Andric         }
415b1c73532SDimitry Andric         MDBuilder MDB(Builder.getContext());
416b1c73532SDimitry Andric         BranchWeights = MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
417b1c73532SDimitry Andric       }
418b1c73532SDimitry Andric       Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot, BranchWeights);
419c0981da4SDimitry Andric       NewIdx->addIncoming(Zero, InsertTop);
420c0981da4SDimitry Andric       NewIdx->addIncoming(IdxNext, NewBB);
4213a0822f0SDimitry Andric       LatchBR->eraseFromParent();
42263faed5bSDimitry Andric     }
42363faed5bSDimitry Andric   }
42463faed5bSDimitry Andric 
42567c32a98SDimitry Andric   // Change the incoming values to the ones defined in the preheader or
42667c32a98SDimitry Andric   // cloned loop.
42767c32a98SDimitry Andric   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
428dd58ef01SDimitry Andric     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
42967c32a98SDimitry Andric     unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
43067c32a98SDimitry Andric     NewPHI->setIncomingBlock(idx, InsertTop);
43167c32a98SDimitry Andric     BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
43267c32a98SDimitry Andric     idx = NewPHI->getBasicBlockIndex(Latch);
43367c32a98SDimitry Andric     Value *InVal = NewPHI->getIncomingValue(idx);
43467c32a98SDimitry Andric     NewPHI->setIncomingBlock(idx, NewLatch);
43501095a5dSDimitry Andric     if (Value *V = VMap.lookup(InVal))
43601095a5dSDimitry Andric       NewPHI->setIncomingValue(idx, V);
43763faed5bSDimitry Andric   }
438c0981da4SDimitry Andric 
43971d5a254SDimitry Andric   Loop *NewLoop = NewLoops[L];
44071d5a254SDimitry Andric   assert(NewLoop && "L should have been cloned");
441706b4fc4SDimitry Andric   MDNode *LoopID = NewLoop->getLoopID();
442044eb2f6SDimitry Andric 
443044eb2f6SDimitry Andric   // Only add loop metadata if the loop is not going to be completely
444044eb2f6SDimitry Andric   // unrolled.
445044eb2f6SDimitry Andric   if (UnrollRemainder)
446044eb2f6SDimitry Andric     return NewLoop;
447044eb2f6SDimitry Andric 
448e3b55780SDimitry Andric   std::optional<MDNode *> NewLoopID = makeFollowupLoopID(
449d8e91e46SDimitry Andric       LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
450145449b1SDimitry Andric   if (NewLoopID) {
451e3b55780SDimitry Andric     NewLoop->setLoopID(*NewLoopID);
452d8e91e46SDimitry Andric 
453d8e91e46SDimitry Andric     // Do not setLoopAlreadyUnrolled if loop attributes have been defined
454d8e91e46SDimitry Andric     // explicitly.
455d8e91e46SDimitry Andric     return NewLoop;
456d8e91e46SDimitry Andric   }
457d8e91e46SDimitry Andric 
45867c32a98SDimitry Andric   // Add unroll disable metadata to disable future unrolling for this loop.
459044eb2f6SDimitry Andric   NewLoop->setLoopAlreadyUnrolled();
4609df3605dSDimitry Andric   return NewLoop;
46163faed5bSDimitry Andric }
462ca089b24SDimitry Andric 
463044eb2f6SDimitry Andric /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
464044eb2f6SDimitry Andric /// we return true only if UnrollRuntimeMultiExit is set to true.
canProfitablyUnrollMultiExitLoop(Loop * L,SmallVectorImpl<BasicBlock * > & OtherExits,BasicBlock * LatchExit,bool UseEpilogRemainder)465044eb2f6SDimitry Andric static bool canProfitablyUnrollMultiExitLoop(
466044eb2f6SDimitry Andric     Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
467c0981da4SDimitry Andric     bool UseEpilogRemainder) {
468044eb2f6SDimitry Andric 
469044eb2f6SDimitry Andric   // Priority goes to UnrollRuntimeMultiExit if it's supplied.
470044eb2f6SDimitry Andric   if (UnrollRuntimeMultiExit.getNumOccurrences())
471044eb2f6SDimitry Andric     return UnrollRuntimeMultiExit;
472044eb2f6SDimitry Andric 
473044eb2f6SDimitry Andric   // The main pain point with multi-exit loop unrolling is that once unrolled,
474044eb2f6SDimitry Andric   // we will not be able to merge all blocks into a straight line code.
475044eb2f6SDimitry Andric   // There are branches within the unrolled loop that go to the OtherExits.
476044eb2f6SDimitry Andric   // The second point is the increase in code size, but this is true
477044eb2f6SDimitry Andric   // irrespective of multiple exits.
478044eb2f6SDimitry Andric 
479044eb2f6SDimitry Andric   // Note: Both the heuristics below are coarse grained. We are essentially
480044eb2f6SDimitry Andric   // enabling unrolling of loops that have a single side exit other than the
481044eb2f6SDimitry Andric   // normal LatchExit (i.e. exiting into a deoptimize block).
482044eb2f6SDimitry Andric   // The heuristics considered are:
483044eb2f6SDimitry Andric   // 1. low number of branches in the unrolled version.
484044eb2f6SDimitry Andric   // 2. high predictability of these extra branches.
485044eb2f6SDimitry Andric   // We avoid unrolling loops that have more than two exiting blocks. This
486044eb2f6SDimitry Andric   // limits the total number of branches in the unrolled loop to be atmost
487044eb2f6SDimitry Andric   // the unroll factor (since one of the exiting blocks is the latch block).
488044eb2f6SDimitry Andric   SmallVector<BasicBlock*, 4> ExitingBlocks;
489044eb2f6SDimitry Andric   L->getExitingBlocks(ExitingBlocks);
490044eb2f6SDimitry Andric   if (ExitingBlocks.size() > 2)
491044eb2f6SDimitry Andric     return false;
492044eb2f6SDimitry Andric 
493344a3780SDimitry Andric   // Allow unrolling of loops with no non latch exit blocks.
494344a3780SDimitry Andric   if (OtherExits.size() == 0)
495344a3780SDimitry Andric     return true;
496344a3780SDimitry Andric 
497044eb2f6SDimitry Andric   // The second heuristic is that L has one exit other than the latchexit and
498044eb2f6SDimitry Andric   // that exit is a deoptimize block. We know that deoptimize blocks are rarely
499044eb2f6SDimitry Andric   // taken, which also implies the branch leading to the deoptimize block is
500344a3780SDimitry Andric   // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
501344a3780SDimitry Andric   // assume the other exit branch is predictable even if it has no deoptimize
502344a3780SDimitry Andric   // call.
503044eb2f6SDimitry Andric   return (OtherExits.size() == 1 &&
504344a3780SDimitry Andric           (UnrollRuntimeOtherExitPredictable ||
5057fa27ce4SDimitry Andric            OtherExits[0]->getPostdominatingDeoptimizeCall()));
506044eb2f6SDimitry Andric   // TODO: These can be fine-tuned further to consider code size or deopt states
507044eb2f6SDimitry Andric   // that are captured by the deoptimize exit block.
508044eb2f6SDimitry Andric   // Also, we can extend this to support more cases, if we actually
509044eb2f6SDimitry Andric   // know of kinds of multiexit loops that would benefit from unrolling.
510044eb2f6SDimitry Andric }
511ca089b24SDimitry Andric 
512c0981da4SDimitry Andric /// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
513c0981da4SDimitry Andric /// accounting for the possibility of unsigned overflow in the 2s complement
514c0981da4SDimitry Andric /// domain. Preconditions:
515c0981da4SDimitry Andric /// 1) TripCount = BECount + 1 (allowing overflow)
516c0981da4SDimitry Andric /// 2) Log2(Count) <= BitWidth(BECount)
CreateTripRemainder(IRBuilder<> & B,Value * BECount,Value * TripCount,unsigned Count)517c0981da4SDimitry Andric static Value *CreateTripRemainder(IRBuilder<> &B, Value *BECount,
518c0981da4SDimitry Andric                                   Value *TripCount, unsigned Count) {
519c0981da4SDimitry Andric   // Note that TripCount is BECount + 1.
520c0981da4SDimitry Andric   if (isPowerOf2_32(Count))
521c0981da4SDimitry Andric     // If the expression is zero, then either:
522c0981da4SDimitry Andric     //  1. There are no iterations to be run in the prolog/epilog loop.
523c0981da4SDimitry Andric     // OR
524c0981da4SDimitry Andric     //  2. The addition computing TripCount overflowed.
525c0981da4SDimitry Andric     //
526c0981da4SDimitry Andric     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
527c0981da4SDimitry Andric     // the number of iterations that remain to be run in the original loop is a
528c0981da4SDimitry Andric     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
529c0981da4SDimitry Andric     // precondition of this method).
530c0981da4SDimitry Andric     return B.CreateAnd(TripCount, Count - 1, "xtraiter");
531c0981da4SDimitry Andric 
532c0981da4SDimitry Andric   // As (BECount + 1) can potentially unsigned overflow we count
533c0981da4SDimitry Andric   // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
534c0981da4SDimitry Andric   Constant *CountC = ConstantInt::get(BECount->getType(), Count);
535c0981da4SDimitry Andric   Value *ModValTmp = B.CreateURem(BECount, CountC);
536c0981da4SDimitry Andric   Value *ModValAdd = B.CreateAdd(ModValTmp,
537c0981da4SDimitry Andric                                  ConstantInt::get(ModValTmp->getType(), 1));
538c0981da4SDimitry Andric   // At that point (BECount % Count) + 1 could be equal to Count.
539c0981da4SDimitry Andric   // To handle this case we need to take mod by Count one more time.
540c0981da4SDimitry Andric   return B.CreateURem(ModValAdd, CountC, "xtraiter");
541b60736ecSDimitry Andric }
542b60736ecSDimitry Andric 
543c0981da4SDimitry Andric 
54401095a5dSDimitry Andric /// Insert code in the prolog/epilog code when unrolling a loop with a
54563faed5bSDimitry Andric /// run-time trip-count.
54663faed5bSDimitry Andric ///
54763faed5bSDimitry Andric /// This method assumes that the loop unroll factor is total number
54801095a5dSDimitry Andric /// of loop bodies in the loop after unrolling. (Some folks refer
54963faed5bSDimitry Andric /// to the unroll factor as the number of *extra* copies added).
55063faed5bSDimitry Andric /// We assume also that the loop unroll factor is a power-of-two. So, after
55163faed5bSDimitry Andric /// unrolling the loop, the number of loop bodies executed is 2,
55263faed5bSDimitry Andric /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
55363faed5bSDimitry Andric /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
55463faed5bSDimitry Andric /// the switch instruction is generated.
55563faed5bSDimitry Andric ///
55601095a5dSDimitry Andric /// ***Prolog case***
55763faed5bSDimitry Andric ///        extraiters = tripcount % loopfactor
55863faed5bSDimitry Andric ///        if (extraiters == 0) jump Loop:
55901095a5dSDimitry Andric ///        else jump Prol:
56067c32a98SDimitry Andric /// Prol:  LoopBody;
56167c32a98SDimitry Andric ///        extraiters -= 1                 // Omitted if unroll factor is 2.
56267c32a98SDimitry Andric ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
56301095a5dSDimitry Andric ///        if (tripcount < loopfactor) jump End:
56463faed5bSDimitry Andric /// Loop:
56563faed5bSDimitry Andric /// ...
56663faed5bSDimitry Andric /// End:
56763faed5bSDimitry Andric ///
56801095a5dSDimitry Andric /// ***Epilog case***
56901095a5dSDimitry Andric ///        extraiters = tripcount % loopfactor
57001095a5dSDimitry Andric ///        if (tripcount < loopfactor) jump LoopExit:
57101095a5dSDimitry Andric ///        unroll_iters = tripcount - extraiters
57201095a5dSDimitry Andric /// Loop:  LoopBody; (executes unroll_iter times);
57301095a5dSDimitry Andric ///        unroll_iter -= 1
57401095a5dSDimitry Andric ///        if (unroll_iter != 0) jump Loop:
57501095a5dSDimitry Andric /// LoopExit:
57601095a5dSDimitry Andric ///        if (extraiters == 0) jump EpilExit:
57701095a5dSDimitry Andric /// Epil:  LoopBody; (executes extraiters times)
57801095a5dSDimitry Andric ///        extraiters -= 1                 // Omitted if unroll factor is 2.
57901095a5dSDimitry Andric ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
58001095a5dSDimitry Andric /// EpilExit:
58101095a5dSDimitry Andric 
UnrollRuntimeLoopRemainder(Loop * L,unsigned Count,bool AllowExpensiveTripCount,bool UseEpilogRemainder,bool UnrollRemainder,bool ForgetAllSCEV,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,AssumptionCache * AC,const TargetTransformInfo * TTI,bool PreserveLCSSA,Loop ** ResultLoop)582cfca06d7SDimitry Andric bool llvm::UnrollRuntimeLoopRemainder(
583cfca06d7SDimitry Andric     Loop *L, unsigned Count, bool AllowExpensiveTripCount,
584cfca06d7SDimitry Andric     bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
585cfca06d7SDimitry Andric     LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC,
586cfca06d7SDimitry Andric     const TargetTransformInfo *TTI, bool PreserveLCSSA, Loop **ResultLoop) {
587eb11fae6SDimitry Andric   LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
588eb11fae6SDimitry Andric   LLVM_DEBUG(L->dump());
589eb11fae6SDimitry Andric   LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
590eb11fae6SDimitry Andric                                 : dbgs() << "Using prolog remainder.\n");
59163faed5bSDimitry Andric 
5929df3605dSDimitry Andric   // Make sure the loop is in canonical form.
593ca089b24SDimitry Andric   if (!L->isLoopSimplifyForm()) {
594eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
59501095a5dSDimitry Andric     return false;
596ca089b24SDimitry Andric   }
59763faed5bSDimitry Andric 
59808bbd35aSDimitry Andric   // Guaranteed by LoopSimplifyForm.
59908bbd35aSDimitry Andric   BasicBlock *Latch = L->getLoopLatch();
6009df3605dSDimitry Andric   BasicBlock *Header = L->getHeader();
60108bbd35aSDimitry Andric 
60208bbd35aSDimitry Andric   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
603d8e91e46SDimitry Andric 
604d8e91e46SDimitry Andric   if (!LatchBR || LatchBR->isUnconditional()) {
605d8e91e46SDimitry Andric     // The loop-rotate pass can be helpful to avoid this in many cases.
606d8e91e46SDimitry Andric     LLVM_DEBUG(
607d8e91e46SDimitry Andric         dbgs()
608d8e91e46SDimitry Andric         << "Loop latch not terminated by a conditional branch.\n");
609d8e91e46SDimitry Andric     return false;
610d8e91e46SDimitry Andric   }
611d8e91e46SDimitry Andric 
612ca089b24SDimitry Andric   unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
613ca089b24SDimitry Andric   BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
614d8e91e46SDimitry Andric 
615d8e91e46SDimitry Andric   if (L->contains(LatchExit)) {
6169df3605dSDimitry Andric     // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
617d8e91e46SDimitry Andric     // targets of the Latch be an exit block out of the loop.
618d8e91e46SDimitry Andric     LLVM_DEBUG(
619d8e91e46SDimitry Andric         dbgs()
620d8e91e46SDimitry Andric         << "One of the loop latch successors must be the exit block.\n");
621d8e91e46SDimitry Andric     return false;
622d8e91e46SDimitry Andric   }
623d8e91e46SDimitry Andric 
624ca089b24SDimitry Andric   // These are exit blocks other than the target of the latch exiting block.
625ca089b24SDimitry Andric   SmallVector<BasicBlock *, 4> OtherExits;
626e6d15924SDimitry Andric   L->getUniqueNonLatchExitBlocks(OtherExits);
627c0981da4SDimitry Andric   // Support only single exit and exiting block unless multi-exit loop
628c0981da4SDimitry Andric   // unrolling is enabled.
629c0981da4SDimitry Andric   if (!L->getExitingBlock() || OtherExits.size()) {
630c0981da4SDimitry Andric     // We rely on LCSSA form being preserved when the exit blocks are transformed.
631c0981da4SDimitry Andric     // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
632c0981da4SDimitry Andric     if (!PreserveLCSSA)
633c0981da4SDimitry Andric       return false;
634c0981da4SDimitry Andric 
635c0981da4SDimitry Andric     if (!canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit,
636c0981da4SDimitry Andric                                           UseEpilogRemainder)) {
637eb11fae6SDimitry Andric       LLVM_DEBUG(
638ca089b24SDimitry Andric           dbgs()
639ca089b24SDimitry Andric           << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
640ca089b24SDimitry Andric              "enabled!\n");
6419df3605dSDimitry Andric       return false;
6429df3605dSDimitry Andric     }
643c0981da4SDimitry Andric   }
64401095a5dSDimitry Andric   // Use Scalar Evolution to compute the trip count. This allows more loops to
64501095a5dSDimitry Andric   // be unrolled than relying on induction var simplification.
6465ca98fd9SDimitry Andric   if (!SE)
64763faed5bSDimitry Andric     return false;
64863faed5bSDimitry Andric 
649f65dcba8SDimitry Andric   // Only unroll loops with a computable trip count.
6509df3605dSDimitry Andric   // We calculate the backedge count by using getExitCount on the Latch block,
6519df3605dSDimitry Andric   // which is proven to be the only exiting block in this loop. This is same as
6529df3605dSDimitry Andric   // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
6539df3605dSDimitry Andric   // exiting blocks).
6549df3605dSDimitry Andric   const SCEV *BECountSC = SE->getExitCount(L, Latch);
655f65dcba8SDimitry Andric   if (isa<SCEVCouldNotCompute>(BECountSC)) {
656eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
65763faed5bSDimitry Andric     return false;
658ca089b24SDimitry Andric   }
65963faed5bSDimitry Andric 
6608af9f201SDimitry Andric   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
66167c32a98SDimitry Andric 
66201095a5dSDimitry Andric   // Add 1 since the backedge count doesn't include the first loop iteration.
663c0981da4SDimitry Andric   // (Note that overflow can occur, this is handled explicitly below)
66463faed5bSDimitry Andric   const SCEV *TripCountSC =
6658af9f201SDimitry Andric       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
666ca089b24SDimitry Andric   if (isa<SCEVCouldNotCompute>(TripCountSC)) {
667eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
66863faed5bSDimitry Andric     return false;
669ca089b24SDimitry Andric   }
67063faed5bSDimitry Andric 
67101095a5dSDimitry Andric   BasicBlock *PreHeader = L->getLoopPreheader();
67201095a5dSDimitry Andric   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
673ac9a064cSDimitry Andric   const DataLayout &DL = Header->getDataLayout();
6745a5ac124SDimitry Andric   SCEVExpander Expander(*SE, DL, "loop-unroll");
67501095a5dSDimitry Andric   if (!AllowExpensiveTripCount &&
676cfca06d7SDimitry Andric       Expander.isHighCostExpansion(TripCountSC, L, SCEVCheapExpansionBudget,
677cfca06d7SDimitry Andric                                    TTI, PreHeaderBR)) {
678eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
6798af9f201SDimitry Andric     return false;
680ca089b24SDimitry Andric   }
6818af9f201SDimitry Andric 
6828af9f201SDimitry Andric   // This constraint lets us deal with an overflowing trip count easily; see the
6835a5ac124SDimitry Andric   // comment on ModVal below.
684ca089b24SDimitry Andric   if (Log2_32(Count) > BEWidth) {
685eb11fae6SDimitry Andric     LLVM_DEBUG(
686eb11fae6SDimitry Andric         dbgs()
687ca089b24SDimitry Andric         << "Count failed constraint on overflow trip count calculation.\n");
68863faed5bSDimitry Andric     return false;
689ca089b24SDimitry Andric   }
69063faed5bSDimitry Andric 
69101095a5dSDimitry Andric   // Loop structure is the following:
69201095a5dSDimitry Andric   //
69301095a5dSDimitry Andric   // PreHeader
69401095a5dSDimitry Andric   //   Header
69501095a5dSDimitry Andric   //   ...
69601095a5dSDimitry Andric   //   Latch
69708bbd35aSDimitry Andric   // LatchExit
69801095a5dSDimitry Andric 
69901095a5dSDimitry Andric   BasicBlock *NewPreHeader;
70001095a5dSDimitry Andric   BasicBlock *NewExit = nullptr;
70101095a5dSDimitry Andric   BasicBlock *PrologExit = nullptr;
70201095a5dSDimitry Andric   BasicBlock *EpilogPreHeader = nullptr;
70301095a5dSDimitry Andric   BasicBlock *PrologPreHeader = nullptr;
70401095a5dSDimitry Andric 
70501095a5dSDimitry Andric   if (UseEpilogRemainder) {
70601095a5dSDimitry Andric     // If epilog remainder
70701095a5dSDimitry Andric     // Split PreHeader to insert a branch around loop for unrolling.
70801095a5dSDimitry Andric     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
70901095a5dSDimitry Andric     NewPreHeader->setName(PreHeader->getName() + ".new");
71008bbd35aSDimitry Andric     // Split LatchExit to create phi nodes from branch above.
711c0981da4SDimitry Andric     NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
712d8e91e46SDimitry Andric                                      nullptr, PreserveLCSSA);
713b2b7c066SDimitry Andric     // NewExit gets its DebugLoc from LatchExit, which is not part of the
714b2b7c066SDimitry Andric     // original Loop.
715b2b7c066SDimitry Andric     // Fix this by setting Loop's DebugLoc to NewExit.
716b2b7c066SDimitry Andric     auto *NewExitTerminator = NewExit->getTerminator();
717b2b7c066SDimitry Andric     NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
71801095a5dSDimitry Andric     // Split NewExit to insert epilog remainder loop.
719b2b7c066SDimitry Andric     EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
72001095a5dSDimitry Andric     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
721c0981da4SDimitry Andric 
722c0981da4SDimitry Andric     // If the latch exits from multiple level of nested loops, then
723c0981da4SDimitry Andric     // by assumption there must be another loop exit which branches to the
724c0981da4SDimitry Andric     // outer loop and we must adjust the loop for the newly inserted blocks
725c0981da4SDimitry Andric     // to account for the fact that our epilogue is still in the same outer
726c0981da4SDimitry Andric     // loop. Note that this leaves loopinfo temporarily out of sync with the
727c0981da4SDimitry Andric     // CFG until the actual epilogue loop is inserted.
728c0981da4SDimitry Andric     if (auto *ParentL = L->getParentLoop())
729c0981da4SDimitry Andric       if (LI->getLoopFor(LatchExit) != ParentL) {
730c0981da4SDimitry Andric         LI->removeBlock(NewExit);
731c0981da4SDimitry Andric         ParentL->addBasicBlockToLoop(NewExit, *LI);
732c0981da4SDimitry Andric         LI->removeBlock(EpilogPreHeader);
733c0981da4SDimitry Andric         ParentL->addBasicBlockToLoop(EpilogPreHeader, *LI);
734c0981da4SDimitry Andric       }
735c0981da4SDimitry Andric 
73601095a5dSDimitry Andric   } else {
73701095a5dSDimitry Andric     // If prolog remainder
73801095a5dSDimitry Andric     // Split the original preheader twice to insert prolog remainder loop
73901095a5dSDimitry Andric     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
74001095a5dSDimitry Andric     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
74101095a5dSDimitry Andric     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
74201095a5dSDimitry Andric                             DT, LI);
74301095a5dSDimitry Andric     PrologExit->setName(Header->getName() + ".prol.loopexit");
74401095a5dSDimitry Andric     // Split PrologExit to get NewPreHeader.
74501095a5dSDimitry Andric     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
74601095a5dSDimitry Andric     NewPreHeader->setName(PreHeader->getName() + ".new");
74701095a5dSDimitry Andric   }
74801095a5dSDimitry Andric   // Loop structure should be the following:
74901095a5dSDimitry Andric   //  Epilog             Prolog
75001095a5dSDimitry Andric   //
75101095a5dSDimitry Andric   // PreHeader         PreHeader
75201095a5dSDimitry Andric   // *NewPreHeader     *PrologPreHeader
75301095a5dSDimitry Andric   //   Header          *PrologExit
75401095a5dSDimitry Andric   //   ...             *NewPreHeader
75501095a5dSDimitry Andric   //   Latch             Header
75601095a5dSDimitry Andric   // *NewExit            ...
75701095a5dSDimitry Andric   // *EpilogPreHeader    Latch
75808bbd35aSDimitry Andric   // LatchExit              LatchExit
75901095a5dSDimitry Andric 
76001095a5dSDimitry Andric   // Calculate conditions for branch around loop for unrolling
76101095a5dSDimitry Andric   // in epilog case and around prolog remainder loop in prolog case.
76263faed5bSDimitry Andric   // Compute the number of extra iterations required, which is:
76301095a5dSDimitry Andric   //  extra iterations = run-time trip count % loop unroll factor
76401095a5dSDimitry Andric   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
765145449b1SDimitry Andric   IRBuilder<> B(PreHeaderBR);
76663faed5bSDimitry Andric   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
76763faed5bSDimitry Andric                                             PreHeaderBR);
768145449b1SDimitry Andric   Value *BECount;
769145449b1SDimitry Andric   // If there are other exits before the latch, that may cause the latch exit
770145449b1SDimitry Andric   // branch to never be executed, and the latch exit count may be poison.
771145449b1SDimitry Andric   // In this case, freeze the TripCount and base BECount on the frozen
772145449b1SDimitry Andric   // TripCount. We will introduce two branches using these values, and it's
773145449b1SDimitry Andric   // important that they see a consistent value (which would not be guaranteed
774145449b1SDimitry Andric   // if were frozen independently.)
775145449b1SDimitry Andric   if ((!OtherExits.empty() || !SE->loopHasNoAbnormalExits(L)) &&
776145449b1SDimitry Andric       !isGuaranteedNotToBeUndefOrPoison(TripCount, AC, PreHeaderBR, DT)) {
777145449b1SDimitry Andric     TripCount = B.CreateFreeze(TripCount);
778145449b1SDimitry Andric     BECount =
779ac9a064cSDimitry Andric         B.CreateAdd(TripCount, Constant::getAllOnesValue(TripCount->getType()));
780145449b1SDimitry Andric   } else {
781145449b1SDimitry Andric     // If we don't need to freeze, use SCEVExpander for BECount as well, to
782145449b1SDimitry Andric     // allow slightly better value reuse.
783145449b1SDimitry Andric     BECount =
784145449b1SDimitry Andric         Expander.expandCodeFor(BECountSC, BECountSC->getType(), PreHeaderBR);
785145449b1SDimitry Andric   }
786145449b1SDimitry Andric 
787c0981da4SDimitry Andric   Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
788c0981da4SDimitry Andric 
78901095a5dSDimitry Andric   Value *BranchVal =
79001095a5dSDimitry Andric       UseEpilogRemainder ? B.CreateICmpULT(BECount,
79101095a5dSDimitry Andric                                            ConstantInt::get(BECount->getType(),
79201095a5dSDimitry Andric                                                             Count - 1)) :
79301095a5dSDimitry Andric                            B.CreateIsNotNull(ModVal, "lcmp.mod");
79401095a5dSDimitry Andric   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
79501095a5dSDimitry Andric   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
79601095a5dSDimitry Andric   // Branch to either remainder (extra iterations) loop or unrolling loop.
797b1c73532SDimitry Andric   MDNode *BranchWeights = nullptr;
798b1c73532SDimitry Andric   if (hasBranchWeightMD(*Latch->getTerminator())) {
799b1c73532SDimitry Andric     // Assume loop is nearly always entered.
800b1c73532SDimitry Andric     MDBuilder MDB(B.getContext());
801b1c73532SDimitry Andric     BranchWeights = MDB.createBranchWeights(EpilogHeaderWeights);
802b1c73532SDimitry Andric   }
803b1c73532SDimitry Andric   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop, BranchWeights);
80463faed5bSDimitry Andric   PreHeaderBR->eraseFromParent();
80571d5a254SDimitry Andric   if (DT) {
80671d5a254SDimitry Andric     if (UseEpilogRemainder)
80771d5a254SDimitry Andric       DT->changeImmediateDominator(NewExit, PreHeader);
80871d5a254SDimitry Andric     else
80971d5a254SDimitry Andric       DT->changeImmediateDominator(PrologExit, PreHeader);
81071d5a254SDimitry Andric   }
81163faed5bSDimitry Andric   Function *F = Header->getParent();
81263faed5bSDimitry Andric   // Get an ordered list of blocks in the loop to help with the ordering of the
81301095a5dSDimitry Andric   // cloned blocks in the prolog/epilog code
81463faed5bSDimitry Andric   LoopBlocksDFS LoopBlocks(L);
81563faed5bSDimitry Andric   LoopBlocks.perform(LI);
81663faed5bSDimitry Andric 
81763faed5bSDimitry Andric   //
81863faed5bSDimitry Andric   // For each extra loop iteration, create a copy of the loop's basic blocks
81963faed5bSDimitry Andric   // and generate a condition that branches to the copy depending on the
82063faed5bSDimitry Andric   // number of 'left over' iterations.
82163faed5bSDimitry Andric   //
82263faed5bSDimitry Andric   std::vector<BasicBlock *> NewBlocks;
82363faed5bSDimitry Andric   ValueToValueMapTy VMap;
82463faed5bSDimitry Andric 
82567c32a98SDimitry Andric   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
82667c32a98SDimitry Andric   // the loop, otherwise we create a cloned loop to execute the extra
82767c32a98SDimitry Andric   // iterations. This function adds the appropriate CFG connections.
82808bbd35aSDimitry Andric   BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
82901095a5dSDimitry Andric   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
8309df3605dSDimitry Andric   Loop *remainderLoop = CloneLoopBlocks(
831c0981da4SDimitry Andric       L, ModVal, UseEpilogRemainder, UnrollRemainder, InsertTop, InsertBot,
832b1c73532SDimitry Andric       NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI, Count);
833b60736ecSDimitry Andric 
83401095a5dSDimitry Andric   // Insert the cloned blocks into the function.
835e3b55780SDimitry Andric   F->splice(InsertBot->getIterator(), F, NewBlocks[0]->getIterator(), F->end());
83663faed5bSDimitry Andric 
8379df3605dSDimitry Andric   // Now the loop blocks are cloned and the other exiting blocks from the
8389df3605dSDimitry Andric   // remainder are connected to the original Loop's exit blocks. The remaining
8399df3605dSDimitry Andric   // work is to update the phi nodes in the original loop, and take in the
840d8e91e46SDimitry Andric   // values from the cloned region.
8419df3605dSDimitry Andric   for (auto *BB : OtherExits) {
8429df3605dSDimitry Andric     // Given we preserve LCSSA form, we know that the values used outside the
8439df3605dSDimitry Andric     // loop will be used through these phi nodes at the exit blocks that are
8449df3605dSDimitry Andric     // transformed below.
845c0981da4SDimitry Andric     for (PHINode &PN : BB->phis()) {
846c0981da4SDimitry Andric      unsigned oldNumOperands = PN.getNumIncomingValues();
8479df3605dSDimitry Andric      // Add the incoming values from the remainder code to the end of the phi
8489df3605dSDimitry Andric      // node.
8499df3605dSDimitry Andric      for (unsigned i = 0; i < oldNumOperands; i++){
850c0981da4SDimitry Andric        auto *PredBB =PN.getIncomingBlock(i);
851c0981da4SDimitry Andric        if (PredBB == Latch)
852ac9a064cSDimitry Andric          // The latch exit is handled separately, see connectX
853c0981da4SDimitry Andric          continue;
854c0981da4SDimitry Andric        if (!L->contains(PredBB))
855c0981da4SDimitry Andric          // Even if we had dedicated exits, the code above inserted an
856c0981da4SDimitry Andric          // extra branch which can reach the latch exit.
857c0981da4SDimitry Andric          continue;
858c0981da4SDimitry Andric 
859c0981da4SDimitry Andric        auto *V = PN.getIncomingValue(i);
860c0981da4SDimitry Andric        if (Instruction *I = dyn_cast<Instruction>(V))
861c0981da4SDimitry Andric          if (L->contains(I))
862c0981da4SDimitry Andric            V = VMap.lookup(I);
863c0981da4SDimitry Andric        PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
8649df3605dSDimitry Andric      }
8659df3605dSDimitry Andric    }
86693c91e39SDimitry Andric #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
86793c91e39SDimitry Andric     for (BasicBlock *SuccBB : successors(BB)) {
868c0981da4SDimitry Andric       assert(!(llvm::is_contained(OtherExits, SuccBB) || SuccBB == LatchExit) &&
86993c91e39SDimitry Andric              "Breaks the definition of dedicated exits!");
87093c91e39SDimitry Andric     }
87193c91e39SDimitry Andric #endif
872d8e91e46SDimitry Andric   }
873d8e91e46SDimitry Andric 
874d8e91e46SDimitry Andric   // Update the immediate dominator of the exit blocks and blocks that are
875d8e91e46SDimitry Andric   // reachable from the exit blocks. This is needed because we now have paths
876d8e91e46SDimitry Andric   // from both the original loop and the remainder code reaching the exit
877d8e91e46SDimitry Andric   // blocks. While the IDom of these exit blocks were from the original loop,
878d8e91e46SDimitry Andric   // now the IDom is the preheader (which decides whether the original loop or
879d8e91e46SDimitry Andric   // remainder code should run).
880d8e91e46SDimitry Andric   if (DT && !L->getExitingBlock()) {
881d8e91e46SDimitry Andric     SmallVector<BasicBlock *, 16> ChildrenToUpdate;
882d8e91e46SDimitry Andric     // NB! We have to examine the dom children of all loop blocks, not just
883d8e91e46SDimitry Andric     // those which are the IDom of the exit blocks. This is because blocks
884d8e91e46SDimitry Andric     // reachable from the exit blocks can have their IDom as the nearest common
885d8e91e46SDimitry Andric     // dominator of the exit blocks.
886d8e91e46SDimitry Andric     for (auto *BB : L->blocks()) {
887d8e91e46SDimitry Andric       auto *DomNodeBB = DT->getNode(BB);
888cfca06d7SDimitry Andric       for (auto *DomChild : DomNodeBB->children()) {
889d8e91e46SDimitry Andric         auto *DomChildBB = DomChild->getBlock();
890d8e91e46SDimitry Andric         if (!L->contains(LI->getLoopFor(DomChildBB)))
891d8e91e46SDimitry Andric           ChildrenToUpdate.push_back(DomChildBB);
892d8e91e46SDimitry Andric       }
893d8e91e46SDimitry Andric     }
894d8e91e46SDimitry Andric     for (auto *BB : ChildrenToUpdate)
8959df3605dSDimitry Andric       DT->changeImmediateDominator(BB, PreHeader);
8969df3605dSDimitry Andric   }
8979df3605dSDimitry Andric 
89801095a5dSDimitry Andric   // Loop structure should be the following:
89901095a5dSDimitry Andric   //  Epilog             Prolog
90001095a5dSDimitry Andric   //
90101095a5dSDimitry Andric   // PreHeader         PreHeader
90201095a5dSDimitry Andric   // NewPreHeader      PrologPreHeader
90301095a5dSDimitry Andric   //   Header            PrologHeader
90401095a5dSDimitry Andric   //   ...               ...
90501095a5dSDimitry Andric   //   Latch             PrologLatch
90601095a5dSDimitry Andric   // NewExit           PrologExit
90701095a5dSDimitry Andric   // EpilogPreHeader   NewPreHeader
90801095a5dSDimitry Andric   //   EpilogHeader      Header
90901095a5dSDimitry Andric   //   ...               ...
91001095a5dSDimitry Andric   //   EpilogLatch       Latch
91108bbd35aSDimitry Andric   // LatchExit              LatchExit
91201095a5dSDimitry Andric 
91301095a5dSDimitry Andric   // Rewrite the cloned instruction operands to use the values created when the
91401095a5dSDimitry Andric   // clone is created.
91501095a5dSDimitry Andric   for (BasicBlock *BB : NewBlocks) {
916b1c73532SDimitry Andric     Module *M = BB->getModule();
91701095a5dSDimitry Andric     for (Instruction &I : *BB) {
91801095a5dSDimitry Andric       RemapInstruction(&I, VMap,
91901095a5dSDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
920ac9a064cSDimitry Andric       RemapDbgRecordRange(M, I.getDbgRecordRange(), VMap,
921b1c73532SDimitry Andric                           RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
92263faed5bSDimitry Andric     }
92363faed5bSDimitry Andric   }
92463faed5bSDimitry Andric 
92501095a5dSDimitry Andric   if (UseEpilogRemainder) {
92601095a5dSDimitry Andric     // Connect the epilog code to the original loop and update the
92701095a5dSDimitry Andric     // PHI functions.
928145449b1SDimitry Andric     ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader, EpilogPreHeader,
929b1c73532SDimitry Andric                   NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE, Count);
93001095a5dSDimitry Andric 
93101095a5dSDimitry Andric     // Update counter in loop for unrolling.
932c0981da4SDimitry Andric     // Use an incrementing IV.  Pre-incr/post-incr is backedge/trip count.
933c0981da4SDimitry Andric     // Subtle: TestVal can be 0 if we wrapped when computing the trip count,
934c0981da4SDimitry Andric     // thus we must compare the post-increment (wrapping) value.
93501095a5dSDimitry Andric     IRBuilder<> B2(NewPreHeader->getTerminator());
93601095a5dSDimitry Andric     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
93701095a5dSDimitry Andric     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
938b1c73532SDimitry Andric     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter");
939b1c73532SDimitry Andric     NewIdx->insertBefore(Header->getFirstNonPHIIt());
940c0981da4SDimitry Andric     B2.SetInsertPoint(LatchBR);
941c0981da4SDimitry Andric     auto *Zero = ConstantInt::get(NewIdx->getType(), 0);
942c0981da4SDimitry Andric     auto *One = ConstantInt::get(NewIdx->getType(), 1);
943c0981da4SDimitry Andric     Value *IdxNext = B2.CreateAdd(NewIdx, One, NewIdx->getName() + ".next");
944c0981da4SDimitry Andric     auto Pred = LatchBR->getSuccessor(0) == Header ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
945c0981da4SDimitry Andric     Value *IdxCmp = B2.CreateICmp(Pred, IdxNext, TestVal, NewIdx->getName() + ".ncmp");
946c0981da4SDimitry Andric     NewIdx->addIncoming(Zero, NewPreHeader);
947c0981da4SDimitry Andric     NewIdx->addIncoming(IdxNext, Latch);
94801095a5dSDimitry Andric     LatchBR->setCondition(IdxCmp);
94901095a5dSDimitry Andric   } else {
95063faed5bSDimitry Andric     // Connect the prolog code to the original loop and update the
95163faed5bSDimitry Andric     // PHI functions.
952ca089b24SDimitry Andric     ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
953145449b1SDimitry Andric                   NewPreHeader, VMap, DT, LI, PreserveLCSSA, *SE);
95401095a5dSDimitry Andric   }
955b915e9e0SDimitry Andric 
956eb11fae6SDimitry Andric   // If this loop is nested, then the loop unroller changes the code in the any
957eb11fae6SDimitry Andric   // of its parent loops, so the Scalar Evolution pass needs to be run again.
958eb11fae6SDimitry Andric   SE->forgetTopmostLoop(L);
959b915e9e0SDimitry Andric 
960c0981da4SDimitry Andric   // Verify that the Dom Tree and Loop Info are correct.
961d8e91e46SDimitry Andric #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
962c0981da4SDimitry Andric   if (DT) {
963d8e91e46SDimitry Andric     assert(DT->verify(DominatorTree::VerificationLevel::Full));
964c0981da4SDimitry Andric     LI->verify(*DT);
965c0981da4SDimitry Andric   }
966d8e91e46SDimitry Andric #endif
967d8e91e46SDimitry Andric 
968c0981da4SDimitry Andric   // For unroll factor 2 remainder loop will have 1 iteration.
969c0981da4SDimitry Andric   if (Count == 2 && DT && LI && SE) {
970c0981da4SDimitry Andric     // TODO: This code could probably be pulled out into a helper function
971c0981da4SDimitry Andric     // (e.g. breakLoopBackedgeAndSimplify) and reused in loop-deletion.
972c0981da4SDimitry Andric     BasicBlock *RemainderLatch = remainderLoop->getLoopLatch();
973c0981da4SDimitry Andric     assert(RemainderLatch);
974c0981da4SDimitry Andric     SmallVector<BasicBlock*> RemainderBlocks(remainderLoop->getBlocks().begin(),
975c0981da4SDimitry Andric                                              remainderLoop->getBlocks().end());
976c0981da4SDimitry Andric     breakLoopBackedge(remainderLoop, *DT, *SE, *LI, nullptr);
977c0981da4SDimitry Andric     remainderLoop = nullptr;
978c0981da4SDimitry Andric 
979c0981da4SDimitry Andric     // Simplify loop values after breaking the backedge
980ac9a064cSDimitry Andric     const DataLayout &DL = L->getHeader()->getDataLayout();
981c0981da4SDimitry Andric     SmallVector<WeakTrackingVH, 16> DeadInsts;
982c0981da4SDimitry Andric     for (BasicBlock *BB : RemainderBlocks) {
983c0981da4SDimitry Andric       for (Instruction &Inst : llvm::make_early_inc_range(*BB)) {
984145449b1SDimitry Andric         if (Value *V = simplifyInstruction(&Inst, {DL, nullptr, DT, AC}))
985c0981da4SDimitry Andric           if (LI->replacementPreservesLCSSAForm(&Inst, V))
986c0981da4SDimitry Andric             Inst.replaceAllUsesWith(V);
987c0981da4SDimitry Andric         if (isInstructionTriviallyDead(&Inst))
988c0981da4SDimitry Andric           DeadInsts.emplace_back(&Inst);
989c0981da4SDimitry Andric       }
990c0981da4SDimitry Andric       // We can't do recursive deletion until we're done iterating, as we might
991c0981da4SDimitry Andric       // have a phi which (potentially indirectly) uses instructions later in
992c0981da4SDimitry Andric       // the block we're iterating through.
993c0981da4SDimitry Andric       RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
994c0981da4SDimitry Andric     }
995c0981da4SDimitry Andric 
996c0981da4SDimitry Andric     // Merge latch into exit block.
997c0981da4SDimitry Andric     auto *ExitBB = RemainderLatch->getSingleSuccessor();
998c0981da4SDimitry Andric     assert(ExitBB && "required after breaking cond br backedge");
999c0981da4SDimitry Andric     DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
1000c0981da4SDimitry Andric     MergeBlockIntoPredecessor(ExitBB, &DTU, LI);
1001c0981da4SDimitry Andric   }
1002c0981da4SDimitry Andric 
10039df3605dSDimitry Andric   // Canonicalize to LoopSimplifyForm both original and remainder loops. We
10049df3605dSDimitry Andric   // cannot rely on the LoopUnrollPass to do this because it only does
10059df3605dSDimitry Andric   // canonicalization for parent/subloops and not the sibling loops.
10069df3605dSDimitry Andric   if (OtherExits.size() > 0) {
10079df3605dSDimitry Andric     // Generate dedicated exit blocks for the original loop, to preserve
10089df3605dSDimitry Andric     // LoopSimplifyForm.
1009e6d15924SDimitry Andric     formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
10109df3605dSDimitry Andric     // Generate dedicated exit blocks for the remainder loop if one exists, to
10119df3605dSDimitry Andric     // preserve LoopSimplifyForm.
10129df3605dSDimitry Andric     if (remainderLoop)
1013e6d15924SDimitry Andric       formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
10149df3605dSDimitry Andric   }
10159df3605dSDimitry Andric 
1016d8e91e46SDimitry Andric   auto UnrollResult = LoopUnrollResult::Unmodified;
1017044eb2f6SDimitry Andric   if (remainderLoop && UnrollRemainder) {
1018eb11fae6SDimitry Andric     LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
1019ac9a064cSDimitry Andric     UnrollLoopOptions ULO;
1020ac9a064cSDimitry Andric     ULO.Count = Count - 1;
1021ac9a064cSDimitry Andric     ULO.Force = false;
1022ac9a064cSDimitry Andric     ULO.Runtime = false;
1023ac9a064cSDimitry Andric     ULO.AllowExpensiveTripCount = false;
1024ac9a064cSDimitry Andric     ULO.UnrollRemainder = false;
1025ac9a064cSDimitry Andric     ULO.ForgetAllSCEV = ForgetAllSCEV;
1026ac9a064cSDimitry Andric     assert(!getLoopConvergenceHeart(L) &&
1027ac9a064cSDimitry Andric            "A loop with a convergence heart does not allow runtime unrolling.");
1028ac9a064cSDimitry Andric     UnrollResult = UnrollLoop(remainderLoop, ULO, LI, SE, DT, AC, TTI,
1029ac9a064cSDimitry Andric                               /*ORE*/ nullptr, PreserveLCSSA);
1030044eb2f6SDimitry Andric   }
1031044eb2f6SDimitry Andric 
1032d8e91e46SDimitry Andric   if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1033d8e91e46SDimitry Andric     *ResultLoop = remainderLoop;
103463faed5bSDimitry Andric   NumRuntimeUnrolled++;
103563faed5bSDimitry Andric   return true;
103663faed5bSDimitry Andric }
1037