xref: /llvm-project/llvm/lib/Transforms/Utils/LoopUnrollRuntime.cpp (revision 94d091429253e46e4cdd31a30e4d1b25b2879d6a)
1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements some loop unrolling utilities for loops with run-time
10 // trip counts.  See LoopUnroll.cpp for unrolling loops with compile-time
11 // trip counts.
12 //
13 // The functions in this file are used to generate extra code when the
14 // run-time trip count modulo the unroll factor is not 0.  When this is the
15 // case, we need to generate code to execute these 'left over' iterations.
16 //
17 // The current strategy generates an if-then-else sequence prior to the
18 // unrolled loop to execute the 'left over' iterations before or after the
19 // unrolled loop.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/LoopIterator.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Transforms/Utils.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 #include "llvm/Transforms/Utils/LoopUtils.h"
39 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
40 #include "llvm/Transforms/Utils/UnrollLoop.h"
41 #include <algorithm>
42 
43 using namespace llvm;
44 
45 #define DEBUG_TYPE "loop-unroll"
46 
47 STATISTIC(NumRuntimeUnrolled,
48           "Number of loops unrolled with run-time trip counts");
49 static cl::opt<bool> UnrollRuntimeMultiExit(
50     "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
51     cl::desc("Allow runtime unrolling for loops with multiple exits, when "
52              "epilog is generated"));
53 static cl::opt<bool> UnrollRuntimeOtherExitPredictable(
54     "unroll-runtime-other-exit-predictable", cl::init(false), cl::Hidden,
55     cl::desc("Assume the non latch exit block to be predictable"));
56 
57 /// Connect the unrolling prolog code to the original loop.
58 /// The unrolling prolog code contains code to execute the
59 /// 'extra' iterations if the run-time trip count modulo the
60 /// unroll count is non-zero.
61 ///
62 /// This function performs the following:
63 /// - Create PHI nodes at prolog end block to combine values
64 ///   that exit the prolog code and jump around the prolog.
65 /// - Add a PHI operand to a PHI node at the loop exit block
66 ///   for values that exit the prolog and go around the loop.
67 /// - Branch around the original loop if the trip count is less
68 ///   than the unroll factor.
69 ///
70 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
71                           BasicBlock *PrologExit,
72                           BasicBlock *OriginalLoopLatchExit,
73                           BasicBlock *PreHeader, BasicBlock *NewPreHeader,
74                           ValueToValueMapTy &VMap, DominatorTree *DT,
75                           LoopInfo *LI, bool PreserveLCSSA) {
76   // Loop structure should be the following:
77   // Preheader
78   //  PrologHeader
79   //  ...
80   //  PrologLatch
81   //  PrologExit
82   //   NewPreheader
83   //    Header
84   //    ...
85   //    Latch
86   //      LatchExit
87   BasicBlock *Latch = L->getLoopLatch();
88   assert(Latch && "Loop must have a latch");
89   BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
90 
91   // Create a PHI node for each outgoing value from the original loop
92   // (which means it is an outgoing value from the prolog code too).
93   // The new PHI node is inserted in the prolog end basic block.
94   // The new PHI node value is added as an operand of a PHI node in either
95   // the loop header or the loop exit block.
96   for (BasicBlock *Succ : successors(Latch)) {
97     for (PHINode &PN : Succ->phis()) {
98       // Add a new PHI node to the prolog end block and add the
99       // appropriate incoming values.
100       // TODO: This code assumes that the PrologExit (or the LatchExit block for
101       // prolog loop) contains only one predecessor from the loop, i.e. the
102       // PrologLatch. When supporting multiple-exiting block loops, we can have
103       // two or more blocks that have the LatchExit as the target in the
104       // original loop.
105       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
106                                        PrologExit->getFirstNonPHI());
107       // Adding a value to the new PHI node from the original loop preheader.
108       // This is the value that skips all the prolog code.
109       if (L->contains(&PN)) {
110         // Succ is loop header.
111         NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
112                            PreHeader);
113       } else {
114         // Succ is LatchExit.
115         NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
116       }
117 
118       Value *V = PN.getIncomingValueForBlock(Latch);
119       if (Instruction *I = dyn_cast<Instruction>(V)) {
120         if (L->contains(I)) {
121           V = VMap.lookup(I);
122         }
123       }
124       // Adding a value to the new PHI node from the last prolog block
125       // that was created.
126       NewPN->addIncoming(V, PrologLatch);
127 
128       // Update the existing PHI node operand with the value from the
129       // new PHI node.  How this is done depends on if the existing
130       // PHI node is in the original loop block, or the exit block.
131       if (L->contains(&PN))
132         PN.setIncomingValueForBlock(NewPreHeader, NewPN);
133       else
134         PN.addIncoming(NewPN, PrologExit);
135     }
136   }
137 
138   // Make sure that created prolog loop is in simplified form
139   SmallVector<BasicBlock *, 4> PrologExitPreds;
140   Loop *PrologLoop = LI->getLoopFor(PrologLatch);
141   if (PrologLoop) {
142     for (BasicBlock *PredBB : predecessors(PrologExit))
143       if (PrologLoop->contains(PredBB))
144         PrologExitPreds.push_back(PredBB);
145 
146     SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
147                            nullptr, PreserveLCSSA);
148   }
149 
150   // Create a branch around the original loop, which is taken if there are no
151   // iterations remaining to be executed after running the prologue.
152   Instruction *InsertPt = PrologExit->getTerminator();
153   IRBuilder<> B(InsertPt);
154 
155   assert(Count != 0 && "nonsensical Count!");
156 
157   // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
158   // This means %xtraiter is (BECount + 1) and all of the iterations of this
159   // loop were executed by the prologue.  Note that if BECount <u (Count - 1)
160   // then (BECount + 1) cannot unsigned-overflow.
161   Value *BrLoopExit =
162       B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
163   // Split the exit to maintain loop canonicalization guarantees
164   SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
165   SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
166                          nullptr, PreserveLCSSA);
167   // Add the branch to the exit block (around the unrolled loop)
168   B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
169   InsertPt->eraseFromParent();
170   if (DT)
171     DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
172 }
173 
174 /// Connect the unrolling epilog code to the original loop.
175 /// The unrolling epilog code contains code to execute the
176 /// 'extra' iterations if the run-time trip count modulo the
177 /// unroll count is non-zero.
178 ///
179 /// This function performs the following:
180 /// - Update PHI nodes at the unrolling loop exit and epilog loop exit
181 /// - Create PHI nodes at the unrolling loop exit to combine
182 ///   values that exit the unrolling loop code and jump around it.
183 /// - Update PHI operands in the epilog loop by the new PHI nodes
184 /// - Branch around the epilog loop if extra iters (ModVal) is zero.
185 ///
186 static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
187                           BasicBlock *Exit, BasicBlock *PreHeader,
188                           BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
189                           ValueToValueMapTy &VMap, DominatorTree *DT,
190                           LoopInfo *LI, bool PreserveLCSSA)  {
191   BasicBlock *Latch = L->getLoopLatch();
192   assert(Latch && "Loop must have a latch");
193   BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
194 
195   // Loop structure should be the following:
196   //
197   // PreHeader
198   // NewPreHeader
199   //   Header
200   //   ...
201   //   Latch
202   // NewExit (PN)
203   // EpilogPreHeader
204   //   EpilogHeader
205   //   ...
206   //   EpilogLatch
207   // Exit (EpilogPN)
208 
209   // Update PHI nodes at NewExit and Exit.
210   for (PHINode &PN : NewExit->phis()) {
211     // PN should be used in another PHI located in Exit block as
212     // Exit was split by SplitBlockPredecessors into Exit and NewExit
213     // Basicaly it should look like:
214     // NewExit:
215     //   PN = PHI [I, Latch]
216     // ...
217     // Exit:
218     //   EpilogPN = PHI [PN, EpilogPreHeader], [X, Exit2], [Y, Exit2.epil]
219     //
220     // Exits from non-latch blocks point to the original exit block and the
221     // epilogue edges have already been added.
222     //
223     // There is EpilogPreHeader incoming block instead of NewExit as
224     // NewExit was spilt 1 more time to get EpilogPreHeader.
225     assert(PN.hasOneUse() && "The phi should have 1 use");
226     PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
227     assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
228 
229     // Add incoming PreHeader from branch around the Loop
230     PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
231 
232     Value *V = PN.getIncomingValueForBlock(Latch);
233     Instruction *I = dyn_cast<Instruction>(V);
234     if (I && L->contains(I))
235       // If value comes from an instruction in the loop add VMap value.
236       V = VMap.lookup(I);
237     // For the instruction out of the loop, constant or undefined value
238     // insert value itself.
239     EpilogPN->addIncoming(V, EpilogLatch);
240 
241     assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
242           "EpilogPN should have EpilogPreHeader incoming block");
243     // Change EpilogPreHeader incoming block to NewExit.
244     EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
245                                NewExit);
246     // Now PHIs should look like:
247     // NewExit:
248     //   PN = PHI [I, Latch], [undef, PreHeader]
249     // ...
250     // Exit:
251     //   EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
252   }
253 
254   // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
255   // Update corresponding PHI nodes in epilog loop.
256   for (BasicBlock *Succ : successors(Latch)) {
257     // Skip this as we already updated phis in exit blocks.
258     if (!L->contains(Succ))
259       continue;
260     for (PHINode &PN : Succ->phis()) {
261       // Add new PHI nodes to the loop exit block and update epilog
262       // PHIs with the new PHI values.
263       PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
264                                        NewExit->getFirstNonPHI());
265       // Adding a value to the new PHI node from the unrolling loop preheader.
266       NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
267       // Adding a value to the new PHI node from the unrolling loop latch.
268       NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
269 
270       // Update the existing PHI node operand with the value from the new PHI
271       // node.  Corresponding instruction in epilog loop should be PHI.
272       PHINode *VPN = cast<PHINode>(VMap[&PN]);
273       VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN);
274     }
275   }
276 
277   Instruction *InsertPt = NewExit->getTerminator();
278   IRBuilder<> B(InsertPt);
279   Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
280   assert(Exit && "Loop must have a single exit block only");
281   // Split the epilogue exit to maintain loop canonicalization guarantees
282   SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
283   SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
284                          PreserveLCSSA);
285   // Add the branch to the exit block (around the unrolling loop)
286   B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
287   InsertPt->eraseFromParent();
288   if (DT)
289     DT->changeImmediateDominator(Exit, NewExit);
290 
291   // Split the main loop exit to maintain canonicalization guarantees.
292   SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
293   SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
294                          PreserveLCSSA);
295 }
296 
297 /// Create a clone of the blocks in a loop and connect them together.
298 /// If CreateRemainderLoop is false, loop structure will not be cloned,
299 /// otherwise a new loop will be created including all cloned blocks, and the
300 /// iterator of it switches to count NewIter down to 0.
301 /// The cloned blocks should be inserted between InsertTop and InsertBot.
302 /// If loop structure is cloned InsertTop should be new preheader, InsertBot
303 /// new loop exit.
304 /// Return the new cloned loop that is created when CreateRemainderLoop is true.
305 static Loop *
306 CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
307                 const bool UseEpilogRemainder, const bool UnrollRemainder,
308                 BasicBlock *InsertTop,
309                 BasicBlock *InsertBot, BasicBlock *Preheader,
310                 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
311                 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
312   StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
313   BasicBlock *Header = L->getHeader();
314   BasicBlock *Latch = L->getLoopLatch();
315   Function *F = Header->getParent();
316   LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
317   LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
318   Loop *ParentLoop = L->getParentLoop();
319   NewLoopsMap NewLoops;
320   NewLoops[ParentLoop] = ParentLoop;
321   if (!CreateRemainderLoop)
322     NewLoops[L] = ParentLoop;
323 
324   // For each block in the original loop, create a new copy,
325   // and update the value map with the newly created values.
326   for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
327     BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
328     NewBlocks.push_back(NewBB);
329 
330     // If we're unrolling the outermost loop, there's no remainder loop,
331     // and this block isn't in a nested loop, then the new block is not
332     // in any loop. Otherwise, add it to loopinfo.
333     if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
334       addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
335 
336     VMap[*BB] = NewBB;
337     if (Header == *BB) {
338       // For the first block, add a CFG connection to this newly
339       // created block.
340       InsertTop->getTerminator()->setSuccessor(0, NewBB);
341     }
342 
343     if (DT) {
344       if (Header == *BB) {
345         // The header is dominated by the preheader.
346         DT->addNewBlock(NewBB, InsertTop);
347       } else {
348         // Copy information from original loop to unrolled loop.
349         BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
350         DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
351       }
352     }
353 
354     if (Latch == *BB) {
355       // For the last block, if CreateRemainderLoop is false, create a direct
356       // jump to InsertBot. If not, create a loop back to cloned head.
357       VMap.erase((*BB)->getTerminator());
358       BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
359       BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
360       IRBuilder<> Builder(LatchBR);
361       if (!CreateRemainderLoop) {
362         Builder.CreateBr(InsertBot);
363       } else {
364         PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
365                                           suffix + ".iter",
366                                           FirstLoopBB->getFirstNonPHI());
367         Value *IdxSub =
368             Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
369                               NewIdx->getName() + ".sub");
370         Value *IdxCmp =
371             Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
372         Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
373         NewIdx->addIncoming(NewIter, InsertTop);
374         NewIdx->addIncoming(IdxSub, NewBB);
375       }
376       LatchBR->eraseFromParent();
377     }
378   }
379 
380   // Change the incoming values to the ones defined in the preheader or
381   // cloned loop.
382   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
383     PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
384     if (!CreateRemainderLoop) {
385       if (UseEpilogRemainder) {
386         unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
387         NewPHI->setIncomingBlock(idx, InsertTop);
388         NewPHI->removeIncomingValue(Latch, false);
389       } else {
390         VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
391         cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
392       }
393     } else {
394       unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
395       NewPHI->setIncomingBlock(idx, InsertTop);
396       BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
397       idx = NewPHI->getBasicBlockIndex(Latch);
398       Value *InVal = NewPHI->getIncomingValue(idx);
399       NewPHI->setIncomingBlock(idx, NewLatch);
400       if (Value *V = VMap.lookup(InVal))
401         NewPHI->setIncomingValue(idx, V);
402     }
403   }
404   if (CreateRemainderLoop) {
405     Loop *NewLoop = NewLoops[L];
406     assert(NewLoop && "L should have been cloned");
407     MDNode *LoopID = NewLoop->getLoopID();
408 
409     // Only add loop metadata if the loop is not going to be completely
410     // unrolled.
411     if (UnrollRemainder)
412       return NewLoop;
413 
414     Optional<MDNode *> NewLoopID = makeFollowupLoopID(
415         LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
416     if (NewLoopID.hasValue()) {
417       NewLoop->setLoopID(NewLoopID.getValue());
418 
419       // Do not setLoopAlreadyUnrolled if loop attributes have been defined
420       // explicitly.
421       return NewLoop;
422     }
423 
424     // Add unroll disable metadata to disable future unrolling for this loop.
425     NewLoop->setLoopAlreadyUnrolled();
426     return NewLoop;
427   }
428   else
429     return nullptr;
430 }
431 
432 /// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
433 /// is populated with all the loop exit blocks other than the LatchExit block.
434 static bool canSafelyUnrollMultiExitLoop(Loop *L, BasicBlock *LatchExit,
435                                          bool PreserveLCSSA,
436                                          bool UseEpilogRemainder) {
437 
438   // We currently have some correctness constrains in unrolling a multi-exit
439   // loop. Check for these below.
440 
441   // We rely on LCSSA form being preserved when the exit blocks are transformed.
442   // (Note that only an off-by-default mode of the old PM disables PreserveLCCA.)
443   if (!PreserveLCSSA)
444     return false;
445 
446   // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
447   // using a prolog loop.
448   if (!UseEpilogRemainder && !LatchExit->getSinglePredecessor()) {
449     LLVM_DEBUG(
450         dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
451                   "predecessor.\n");
452     return false;
453   }
454   // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
455   // and L is an inner loop. This is because in presence of multiple exits, the
456   // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
457   // outer loop. This is automatically handled in the prolog case, so we do not
458   // have that bug in prolog generation.
459   if (UseEpilogRemainder && L->getParentLoop())
460     return false;
461 
462   // All constraints have been satisfied.
463   return true;
464 }
465 
466 /// Returns true if we can profitably unroll the multi-exit loop L. Currently,
467 /// we return true only if UnrollRuntimeMultiExit is set to true.
468 static bool canProfitablyUnrollMultiExitLoop(
469     Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
470     bool PreserveLCSSA, bool UseEpilogRemainder) {
471 
472 #if !defined(NDEBUG)
473   assert(canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA,
474                                       UseEpilogRemainder) &&
475          "Should be safe to unroll before checking profitability!");
476 #endif
477 
478   // Priority goes to UnrollRuntimeMultiExit if it's supplied.
479   if (UnrollRuntimeMultiExit.getNumOccurrences())
480     return UnrollRuntimeMultiExit;
481 
482   // TODO: We used to bail out for correctness (now fixed).  Under what
483   // circumstances is this case profitable to allow?
484   if (!LatchExit->getSinglePredecessor())
485     return false;
486 
487   // The main pain point with multi-exit loop unrolling is that once unrolled,
488   // we will not be able to merge all blocks into a straight line code.
489   // There are branches within the unrolled loop that go to the OtherExits.
490   // The second point is the increase in code size, but this is true
491   // irrespective of multiple exits.
492 
493   // Note: Both the heuristics below are coarse grained. We are essentially
494   // enabling unrolling of loops that have a single side exit other than the
495   // normal LatchExit (i.e. exiting into a deoptimize block).
496   // The heuristics considered are:
497   // 1. low number of branches in the unrolled version.
498   // 2. high predictability of these extra branches.
499   // We avoid unrolling loops that have more than two exiting blocks. This
500   // limits the total number of branches in the unrolled loop to be atmost
501   // the unroll factor (since one of the exiting blocks is the latch block).
502   SmallVector<BasicBlock*, 4> ExitingBlocks;
503   L->getExitingBlocks(ExitingBlocks);
504   if (ExitingBlocks.size() > 2)
505     return false;
506 
507   // Allow unrolling of loops with no non latch exit blocks.
508   if (OtherExits.size() == 0)
509     return true;
510 
511   // The second heuristic is that L has one exit other than the latchexit and
512   // that exit is a deoptimize block. We know that deoptimize blocks are rarely
513   // taken, which also implies the branch leading to the deoptimize block is
514   // highly predictable. When UnrollRuntimeOtherExitPredictable is specified, we
515   // assume the other exit branch is predictable even if it has no deoptimize
516   // call.
517   return (OtherExits.size() == 1 &&
518           (UnrollRuntimeOtherExitPredictable ||
519            OtherExits[0]->getTerminatingDeoptimizeCall()));
520   // TODO: These can be fine-tuned further to consider code size or deopt states
521   // that are captured by the deoptimize exit block.
522   // Also, we can extend this to support more cases, if we actually
523   // know of kinds of multiexit loops that would benefit from unrolling.
524 }
525 
526 // Assign the maximum possible trip count as the back edge weight for the
527 // remainder loop if the original loop comes with a branch weight.
528 static void updateLatchBranchWeightsForRemainderLoop(Loop *OrigLoop,
529                                                      Loop *RemainderLoop,
530                                                      uint64_t UnrollFactor) {
531   uint64_t TrueWeight, FalseWeight;
532   BranchInst *LatchBR =
533       cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator());
534   if (LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) {
535     uint64_t ExitWeight = LatchBR->getSuccessor(0) == OrigLoop->getHeader()
536                               ? FalseWeight
537                               : TrueWeight;
538     assert(UnrollFactor > 1);
539     uint64_t BackEdgeWeight = (UnrollFactor - 1) * ExitWeight;
540     BasicBlock *Header = RemainderLoop->getHeader();
541     BasicBlock *Latch = RemainderLoop->getLoopLatch();
542     auto *RemainderLatchBR = cast<BranchInst>(Latch->getTerminator());
543     unsigned HeaderIdx = (RemainderLatchBR->getSuccessor(0) == Header ? 0 : 1);
544     MDBuilder MDB(RemainderLatchBR->getContext());
545     MDNode *WeightNode =
546         HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
547                   : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
548     RemainderLatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
549   }
550 }
551 
552 /// Calculate ModVal = (BECount + 1) % Count on the abstract integer domain
553 /// accounting for the possibility of unsigned overflow in the 2s complement
554 /// domain. Preconditions:
555 /// 1) TripCount = BECount + 1 (allowing overflow)
556 /// 2) Log2(Count) <= BitWidth(BECount)
557 static Value *CreateTripRemainder(IRBuilder<> &B, Value *BECount,
558                                   Value *TripCount, unsigned Count) {
559   // Note that TripCount is BECount + 1.
560   if (isPowerOf2_32(Count))
561     // If the expression is zero, then either:
562     //  1. There are no iterations to be run in the prolog/epilog loop.
563     // OR
564     //  2. The addition computing TripCount overflowed.
565     //
566     // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
567     // the number of iterations that remain to be run in the original loop is a
568     // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (a
569     // precondition of this method).
570     return B.CreateAnd(TripCount, Count - 1, "xtraiter");
571 
572   // As (BECount + 1) can potentially unsigned overflow we count
573   // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
574   Constant *CountC = ConstantInt::get(BECount->getType(), Count);
575   Value *ModValTmp = B.CreateURem(BECount, CountC);
576   Value *ModValAdd = B.CreateAdd(ModValTmp,
577                                  ConstantInt::get(ModValTmp->getType(), 1));
578   // At that point (BECount % Count) + 1 could be equal to Count.
579   // To handle this case we need to take mod by Count one more time.
580   return B.CreateURem(ModValAdd, CountC, "xtraiter");
581 }
582 
583 
584 /// Insert code in the prolog/epilog code when unrolling a loop with a
585 /// run-time trip-count.
586 ///
587 /// This method assumes that the loop unroll factor is total number
588 /// of loop bodies in the loop after unrolling. (Some folks refer
589 /// to the unroll factor as the number of *extra* copies added).
590 /// We assume also that the loop unroll factor is a power-of-two. So, after
591 /// unrolling the loop, the number of loop bodies executed is 2,
592 /// 4, 8, etc.  Note - LLVM converts the if-then-sequence to a switch
593 /// instruction in SimplifyCFG.cpp.  Then, the backend decides how code for
594 /// the switch instruction is generated.
595 ///
596 /// ***Prolog case***
597 ///        extraiters = tripcount % loopfactor
598 ///        if (extraiters == 0) jump Loop:
599 ///        else jump Prol:
600 /// Prol:  LoopBody;
601 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
602 ///        if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
603 ///        if (tripcount < loopfactor) jump End:
604 /// Loop:
605 /// ...
606 /// End:
607 ///
608 /// ***Epilog case***
609 ///        extraiters = tripcount % loopfactor
610 ///        if (tripcount < loopfactor) jump LoopExit:
611 ///        unroll_iters = tripcount - extraiters
612 /// Loop:  LoopBody; (executes unroll_iter times);
613 ///        unroll_iter -= 1
614 ///        if (unroll_iter != 0) jump Loop:
615 /// LoopExit:
616 ///        if (extraiters == 0) jump EpilExit:
617 /// Epil:  LoopBody; (executes extraiters times)
618 ///        extraiters -= 1                 // Omitted if unroll factor is 2.
619 ///        if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
620 /// EpilExit:
621 
622 bool llvm::UnrollRuntimeLoopRemainder(
623     Loop *L, unsigned Count, bool AllowExpensiveTripCount,
624     bool UseEpilogRemainder, bool UnrollRemainder, bool ForgetAllSCEV,
625     LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC,
626     const TargetTransformInfo *TTI, bool PreserveLCSSA, Loop **ResultLoop) {
627   LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
628   LLVM_DEBUG(L->dump());
629   LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
630                                 : dbgs() << "Using prolog remainder.\n");
631 
632   // Make sure the loop is in canonical form.
633   if (!L->isLoopSimplifyForm()) {
634     LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
635     return false;
636   }
637 
638   // Guaranteed by LoopSimplifyForm.
639   BasicBlock *Latch = L->getLoopLatch();
640   BasicBlock *Header = L->getHeader();
641 
642   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
643 
644   if (!LatchBR || LatchBR->isUnconditional()) {
645     // The loop-rotate pass can be helpful to avoid this in many cases.
646     LLVM_DEBUG(
647         dbgs()
648         << "Loop latch not terminated by a conditional branch.\n");
649     return false;
650   }
651 
652   unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
653   BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
654 
655   if (L->contains(LatchExit)) {
656     // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
657     // targets of the Latch be an exit block out of the loop.
658     LLVM_DEBUG(
659         dbgs()
660         << "One of the loop latch successors must be the exit block.\n");
661     return false;
662   }
663 
664   // These are exit blocks other than the target of the latch exiting block.
665   SmallVector<BasicBlock *, 4> OtherExits;
666   L->getUniqueNonLatchExitBlocks(OtherExits);
667   bool isMultiExitUnrollingEnabled =
668       canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA,
669                                    UseEpilogRemainder) &&
670       canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
671                                        UseEpilogRemainder);
672   // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
673   if (!isMultiExitUnrollingEnabled &&
674       (!L->getExitingBlock() || OtherExits.size())) {
675     LLVM_DEBUG(
676         dbgs()
677         << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
678            "enabled!\n");
679     return false;
680   }
681   // Use Scalar Evolution to compute the trip count. This allows more loops to
682   // be unrolled than relying on induction var simplification.
683   if (!SE)
684     return false;
685 
686   // Only unroll loops with a computable trip count, and the trip count needs
687   // to be an int value (allowing a pointer type is a TODO item).
688   // We calculate the backedge count by using getExitCount on the Latch block,
689   // which is proven to be the only exiting block in this loop. This is same as
690   // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
691   // exiting blocks).
692   const SCEV *BECountSC = SE->getExitCount(L, Latch);
693   if (isa<SCEVCouldNotCompute>(BECountSC) ||
694       !BECountSC->getType()->isIntegerTy()) {
695     LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
696     return false;
697   }
698 
699   unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
700 
701   // Add 1 since the backedge count doesn't include the first loop iteration.
702   // (Note that overflow can occur, this is handled explicitly below)
703   const SCEV *TripCountSC =
704       SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
705   if (isa<SCEVCouldNotCompute>(TripCountSC)) {
706     LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
707     return false;
708   }
709 
710   BasicBlock *PreHeader = L->getLoopPreheader();
711   BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
712   const DataLayout &DL = Header->getModule()->getDataLayout();
713   SCEVExpander Expander(*SE, DL, "loop-unroll");
714   if (!AllowExpensiveTripCount &&
715       Expander.isHighCostExpansion(TripCountSC, L, SCEVCheapExpansionBudget,
716                                    TTI, PreHeaderBR)) {
717     LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
718     return false;
719   }
720 
721   // This constraint lets us deal with an overflowing trip count easily; see the
722   // comment on ModVal below.
723   if (Log2_32(Count) > BEWidth) {
724     LLVM_DEBUG(
725         dbgs()
726         << "Count failed constraint on overflow trip count calculation.\n");
727     return false;
728   }
729 
730   // Loop structure is the following:
731   //
732   // PreHeader
733   //   Header
734   //   ...
735   //   Latch
736   // LatchExit
737 
738   BasicBlock *NewPreHeader;
739   BasicBlock *NewExit = nullptr;
740   BasicBlock *PrologExit = nullptr;
741   BasicBlock *EpilogPreHeader = nullptr;
742   BasicBlock *PrologPreHeader = nullptr;
743 
744   if (UseEpilogRemainder) {
745     // If epilog remainder
746     // Split PreHeader to insert a branch around loop for unrolling.
747     NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
748     NewPreHeader->setName(PreHeader->getName() + ".new");
749     // Split LatchExit to create phi nodes from branch above.
750     NewExit = SplitBlockPredecessors(LatchExit, {Latch}, ".unr-lcssa", DT, LI,
751                                      nullptr, PreserveLCSSA);
752     // NewExit gets its DebugLoc from LatchExit, which is not part of the
753     // original Loop.
754     // Fix this by setting Loop's DebugLoc to NewExit.
755     auto *NewExitTerminator = NewExit->getTerminator();
756     NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
757     // Split NewExit to insert epilog remainder loop.
758     EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
759     EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
760   } else {
761     // If prolog remainder
762     // Split the original preheader twice to insert prolog remainder loop
763     PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
764     PrologPreHeader->setName(Header->getName() + ".prol.preheader");
765     PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
766                             DT, LI);
767     PrologExit->setName(Header->getName() + ".prol.loopexit");
768     // Split PrologExit to get NewPreHeader.
769     NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
770     NewPreHeader->setName(PreHeader->getName() + ".new");
771   }
772   // Loop structure should be the following:
773   //  Epilog             Prolog
774   //
775   // PreHeader         PreHeader
776   // *NewPreHeader     *PrologPreHeader
777   //   Header          *PrologExit
778   //   ...             *NewPreHeader
779   //   Latch             Header
780   // *NewExit            ...
781   // *EpilogPreHeader    Latch
782   // LatchExit              LatchExit
783 
784   // Calculate conditions for branch around loop for unrolling
785   // in epilog case and around prolog remainder loop in prolog case.
786   // Compute the number of extra iterations required, which is:
787   //  extra iterations = run-time trip count % loop unroll factor
788   PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
789   Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
790                                             PreHeaderBR);
791   Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
792                                           PreHeaderBR);
793   IRBuilder<> B(PreHeaderBR);
794   Value * const ModVal = CreateTripRemainder(B, BECount, TripCount, Count);
795 
796   Value *BranchVal =
797       UseEpilogRemainder ? B.CreateICmpULT(BECount,
798                                            ConstantInt::get(BECount->getType(),
799                                                             Count - 1)) :
800                            B.CreateIsNotNull(ModVal, "lcmp.mod");
801   BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
802   BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
803   // Branch to either remainder (extra iterations) loop or unrolling loop.
804   B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
805   PreHeaderBR->eraseFromParent();
806   if (DT) {
807     if (UseEpilogRemainder)
808       DT->changeImmediateDominator(NewExit, PreHeader);
809     else
810       DT->changeImmediateDominator(PrologExit, PreHeader);
811   }
812   Function *F = Header->getParent();
813   // Get an ordered list of blocks in the loop to help with the ordering of the
814   // cloned blocks in the prolog/epilog code
815   LoopBlocksDFS LoopBlocks(L);
816   LoopBlocks.perform(LI);
817 
818   //
819   // For each extra loop iteration, create a copy of the loop's basic blocks
820   // and generate a condition that branches to the copy depending on the
821   // number of 'left over' iterations.
822   //
823   std::vector<BasicBlock *> NewBlocks;
824   ValueToValueMapTy VMap;
825 
826   // For unroll factor 2 remainder loop will have 1 iterations.
827   // Do not create 1 iteration loop.
828   bool CreateRemainderLoop = (Count != 2);
829 
830   // Clone all the basic blocks in the loop. If Count is 2, we don't clone
831   // the loop, otherwise we create a cloned loop to execute the extra
832   // iterations. This function adds the appropriate CFG connections.
833   BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
834   BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
835   Loop *remainderLoop = CloneLoopBlocks(
836       L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
837       InsertTop, InsertBot,
838       NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
839 
840   // Assign the maximum possible trip count as the back edge weight for the
841   // remainder loop if the original loop comes with a branch weight.
842   if (remainderLoop && !UnrollRemainder)
843     updateLatchBranchWeightsForRemainderLoop(L, remainderLoop, Count);
844 
845   // Insert the cloned blocks into the function.
846   F->getBasicBlockList().splice(InsertBot->getIterator(),
847                                 F->getBasicBlockList(),
848                                 NewBlocks[0]->getIterator(),
849                                 F->end());
850 
851   // Now the loop blocks are cloned and the other exiting blocks from the
852   // remainder are connected to the original Loop's exit blocks. The remaining
853   // work is to update the phi nodes in the original loop, and take in the
854   // values from the cloned region.
855   for (auto *BB : OtherExits) {
856     // Given we preserve LCSSA form, we know that the values used outside the
857     // loop will be used through these phi nodes at the exit blocks that are
858     // transformed below.
859     for (PHINode &PN : BB->phis()) {
860      unsigned oldNumOperands = PN.getNumIncomingValues();
861      // Add the incoming values from the remainder code to the end of the phi
862      // node.
863      for (unsigned i = 0; i < oldNumOperands; i++){
864        auto *PredBB =PN.getIncomingBlock(i);
865        if (PredBB == Latch)
866          // The latch exit is handled seperately, see connectX
867          continue;
868        if (!L->contains(PredBB))
869          // Even if we had dedicated exits, the code above inserted an
870          // extra branch which can reach the latch exit.
871          continue;
872 
873        auto *V = PN.getIncomingValue(i);
874        if (Instruction *I = dyn_cast<Instruction>(V))
875          if (L->contains(I))
876            V = VMap.lookup(I);
877        PN.addIncoming(V, cast<BasicBlock>(VMap[PredBB]));
878      }
879    }
880 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
881     for (BasicBlock *SuccBB : successors(BB)) {
882       assert(!(any_of(OtherExits,
883                       [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
884                SuccBB == LatchExit) &&
885              "Breaks the definition of dedicated exits!");
886     }
887 #endif
888   }
889 
890   // Update the immediate dominator of the exit blocks and blocks that are
891   // reachable from the exit blocks. This is needed because we now have paths
892   // from both the original loop and the remainder code reaching the exit
893   // blocks. While the IDom of these exit blocks were from the original loop,
894   // now the IDom is the preheader (which decides whether the original loop or
895   // remainder code should run).
896   if (DT && !L->getExitingBlock()) {
897     SmallVector<BasicBlock *, 16> ChildrenToUpdate;
898     // NB! We have to examine the dom children of all loop blocks, not just
899     // those which are the IDom of the exit blocks. This is because blocks
900     // reachable from the exit blocks can have their IDom as the nearest common
901     // dominator of the exit blocks.
902     for (auto *BB : L->blocks()) {
903       auto *DomNodeBB = DT->getNode(BB);
904       for (auto *DomChild : DomNodeBB->children()) {
905         auto *DomChildBB = DomChild->getBlock();
906         if (!L->contains(LI->getLoopFor(DomChildBB)))
907           ChildrenToUpdate.push_back(DomChildBB);
908       }
909     }
910     for (auto *BB : ChildrenToUpdate)
911       DT->changeImmediateDominator(BB, PreHeader);
912   }
913 
914   // Loop structure should be the following:
915   //  Epilog             Prolog
916   //
917   // PreHeader         PreHeader
918   // NewPreHeader      PrologPreHeader
919   //   Header            PrologHeader
920   //   ...               ...
921   //   Latch             PrologLatch
922   // NewExit           PrologExit
923   // EpilogPreHeader   NewPreHeader
924   //   EpilogHeader      Header
925   //   ...               ...
926   //   EpilogLatch       Latch
927   // LatchExit              LatchExit
928 
929   // Rewrite the cloned instruction operands to use the values created when the
930   // clone is created.
931   for (BasicBlock *BB : NewBlocks) {
932     for (Instruction &I : *BB) {
933       RemapInstruction(&I, VMap,
934                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
935     }
936   }
937 
938   if (UseEpilogRemainder) {
939     // Connect the epilog code to the original loop and update the
940     // PHI functions.
941     ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
942                   EpilogPreHeader, NewPreHeader, VMap, DT, LI,
943                   PreserveLCSSA);
944 
945     // Update counter in loop for unrolling.
946     // I should be multiply of Count.
947     IRBuilder<> B2(NewPreHeader->getTerminator());
948     Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
949     BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
950     B2.SetInsertPoint(LatchBR);
951     PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
952                                       Header->getFirstNonPHI());
953     Value *IdxSub =
954         B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
955                      NewIdx->getName() + ".nsub");
956     Value *IdxCmp;
957     if (LatchBR->getSuccessor(0) == Header)
958       IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
959     else
960       IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
961     NewIdx->addIncoming(TestVal, NewPreHeader);
962     NewIdx->addIncoming(IdxSub, Latch);
963     LatchBR->setCondition(IdxCmp);
964   } else {
965     // Connect the prolog code to the original loop and update the
966     // PHI functions.
967     ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
968                   NewPreHeader, VMap, DT, LI, PreserveLCSSA);
969   }
970 
971   // If this loop is nested, then the loop unroller changes the code in the any
972   // of its parent loops, so the Scalar Evolution pass needs to be run again.
973   SE->forgetTopmostLoop(L);
974 
975   // Verify that the Dom Tree is correct.
976 #if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
977   if (DT)
978     assert(DT->verify(DominatorTree::VerificationLevel::Full));
979 #endif
980 
981   // Canonicalize to LoopSimplifyForm both original and remainder loops. We
982   // cannot rely on the LoopUnrollPass to do this because it only does
983   // canonicalization for parent/subloops and not the sibling loops.
984   if (OtherExits.size() > 0) {
985     // Generate dedicated exit blocks for the original loop, to preserve
986     // LoopSimplifyForm.
987     formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
988     // Generate dedicated exit blocks for the remainder loop if one exists, to
989     // preserve LoopSimplifyForm.
990     if (remainderLoop)
991       formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
992   }
993 
994   auto UnrollResult = LoopUnrollResult::Unmodified;
995   if (remainderLoop && UnrollRemainder) {
996     LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
997     UnrollResult =
998         UnrollLoop(remainderLoop,
999                    {/*Count*/ Count - 1, /*Force*/ false, /*Runtime*/ false,
1000                     /*AllowExpensiveTripCount*/ false,
1001                     /*UnrollRemainder*/ false, ForgetAllSCEV},
1002                    LI, SE, DT, AC, TTI, /*ORE*/ nullptr, PreserveLCSSA);
1003   }
1004 
1005   if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
1006     *ResultLoop = remainderLoop;
1007   NumRuntimeUnrolled++;
1008   return true;
1009 }
1010