blob: cbf4772e27781e3e9ea53c06c3e156106c55cb85 [file] [log] [blame]
Andrew Trickd04d15292011-12-09 06:19:40 +00001//===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Andrew Trickd04d15292011-12-09 06:19:40 +00006//
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//
Jakub Staszak1b1d5232011-12-18 21:52:30 +000013// The functions in this file are used to generate extra code when the
Andrew Trickd04d15292011-12-09 06:19:40 +000014// 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//
Jakub Staszak1b1d5232011-12-18 21:52:30 +000017// The current strategy generates an if-then-else sequence prior to the
David L Kreitzer188de5a2016-04-05 12:19:35 +000018// unrolled loop to execute the 'left over' iterations before or after the
19// unrolled loop.
Andrew Trickd04d15292011-12-09 06:19:40 +000020//
21//===----------------------------------------------------------------------===//
22
Florian Hahna1cc8482018-06-12 11:16:56 +000023#include "llvm/ADT/SmallPtrSet.h"
David Blaikiea373d182018-03-28 17:44:36 +000024#include "llvm/ADT/Statistic.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000025#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000026#include "llvm/Analysis/LoopIterator.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000027#include "llvm/Analysis/ScalarEvolution.h"
28#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/BasicBlock.h"
Chandler Carruth32c52c72015-01-18 02:39:37 +000030#include "llvm/IR/Dominators.h"
Kevin Qinfc02e3c2014-09-29 11:15:00 +000031#include "llvm/IR/Metadata.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000032#include "llvm/IR/Module.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/raw_ostream.h"
David Blaikiea373d182018-03-28 17:44:36 +000035#include "llvm/Transforms/Utils.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Cloning.h"
Anna Thomase5e5e592017-06-30 17:57:07 +000038#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/Transforms/Utils/UnrollLoop.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000040#include <algorithm>
41
42using namespace llvm;
43
Chandler Carruth964daaa2014-04-22 02:55:47 +000044#define DEBUG_TYPE "loop-unroll"
45
Jakub Staszak1b1d5232011-12-18 21:52:30 +000046STATISTIC(NumRuntimeUnrolled,
Andrew Trickd04d15292011-12-09 06:19:40 +000047 "Number of loops unrolled with run-time trip counts");
Anna Thomase5e5e592017-06-30 17:57:07 +000048static cl::opt<bool> UnrollRuntimeMultiExit(
49 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
50 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
51 "epilog is generated"));
Andrew Trickd04d15292011-12-09 06:19:40 +000052
53/// Connect the unrolling prolog code to the original loop.
54/// The unrolling prolog code contains code to execute the
55/// 'extra' iterations if the run-time trip count modulo the
56/// unroll count is non-zero.
57///
58/// This function performs the following:
59/// - Create PHI nodes at prolog end block to combine values
60/// that exit the prolog code and jump around the prolog.
61/// - Add a PHI operand to a PHI node at the loop exit block
62/// for values that exit the prolog and go around the loop.
63/// - Branch around the original loop if the trip count is less
64/// than the unroll factor.
65///
Sanjoy Das11b279a2015-02-18 19:32:25 +000066static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
Anna Thomas734ab3f2017-07-07 18:05:28 +000067 BasicBlock *PrologExit,
68 BasicBlock *OriginalLoopLatchExit,
69 BasicBlock *PreHeader, BasicBlock *NewPreHeader,
70 ValueToValueMapTy &VMap, DominatorTree *DT,
71 LoopInfo *LI, bool PreserveLCSSA) {
Anna Thomas18be3cb2018-12-21 19:45:05 +000072 // Loop structure should be the following:
73 // Preheader
Anna Thomas98743fa2018-12-28 18:52:16 +000074 // PrologHeader
Anna Thomas18be3cb2018-12-21 19:45:05 +000075 // ...
76 // PrologLatch
77 // PrologExit
78 // NewPreheader
79 // Header
80 // ...
81 // Latch
82 // LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +000083 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000084 assert(Latch && "Loop must have a latch");
David L Kreitzer188de5a2016-04-05 12:19:35 +000085 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
Andrew Trickd04d15292011-12-09 06:19:40 +000086
87 // Create a PHI node for each outgoing value from the original loop
88 // (which means it is an outgoing value from the prolog code too).
89 // The new PHI node is inserted in the prolog end basic block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000090 // The new PHI node value is added as an operand of a PHI node in either
Andrew Trickd04d15292011-12-09 06:19:40 +000091 // the loop header or the loop exit block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000092 for (BasicBlock *Succ : successors(Latch)) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000093 for (PHINode &PN : Succ->phis()) {
Andrew Trickd04d15292011-12-09 06:19:40 +000094 // Add a new PHI node to the prolog end block and add the
95 // appropriate incoming values.
Anna Thomas18be3cb2018-12-21 19:45:05 +000096 // TODO: This code assumes that the PrologExit (or the LatchExit block for
97 // prolog loop) contains only one predecessor from the loop, i.e. the
98 // PrologLatch. When supporting multiple-exiting block loops, we can have
99 // two or more blocks that have the LatchExit as the target in the
100 // original loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000101 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000102 PrologExit->getFirstNonPHI());
Andrew Trickd04d15292011-12-09 06:19:40 +0000103 // Adding a value to the new PHI node from the original loop preheader.
104 // This is the value that skips all the prolog code.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000105 if (L->contains(&PN)) {
Anna Thomas18be3cb2018-12-21 19:45:05 +0000106 // Succ is loop header.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000107 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
David L Kreitzer188de5a2016-04-05 12:19:35 +0000108 PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +0000109 } else {
Anna Thomas98743fa2018-12-28 18:52:16 +0000110 // Succ is LatchExit.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000111 NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +0000112 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000113
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000114 Value *V = PN.getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000115 if (Instruction *I = dyn_cast<Instruction>(V)) {
116 if (L->contains(I)) {
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000117 V = VMap.lookup(I);
Andrew Trickd04d15292011-12-09 06:19:40 +0000118 }
119 }
120 // Adding a value to the new PHI node from the last prolog block
121 // that was created.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000122 NewPN->addIncoming(V, PrologLatch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000123
124 // Update the existing PHI node operand with the value from the
125 // new PHI node. How this is done depends on if the existing
126 // PHI node is in the original loop block, or the exit block.
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000127 if (L->contains(&PN))
128 PN.setIncomingValueForBlock(NewPreHeader, NewPN);
129 else
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000130 PN.addIncoming(NewPN, PrologExit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000131 }
132 }
133
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000134 // Make sure that created prolog loop is in simplified form
135 SmallVector<BasicBlock *, 4> PrologExitPreds;
136 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
137 if (PrologLoop) {
138 for (BasicBlock *PredBB : predecessors(PrologExit))
139 if (PrologLoop->contains(PredBB))
140 PrologExitPreds.push_back(PredBB);
141
142 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000143 nullptr, PreserveLCSSA);
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000144 }
145
Sanjay Patele08381a2016-02-08 19:27:33 +0000146 // Create a branch around the original loop, which is taken if there are no
Sanjoy Das11b279a2015-02-18 19:32:25 +0000147 // iterations remaining to be executed after running the prologue.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000148 Instruction *InsertPt = PrologExit->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000149 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000150
151 assert(Count != 0 && "nonsensical Count!");
152
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000153 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
154 // This means %xtraiter is (BECount + 1) and all of the iterations of this
155 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
156 // then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000157 Value *BrLoopExit =
158 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000159 // Split the exit to maintain loop canonicalization guarantees
Anna Thomas734ab3f2017-07-07 18:05:28 +0000160 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
161 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000162 nullptr, PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000163 // Add the branch to the exit block (around the unrolled loop)
Anna Thomas734ab3f2017-07-07 18:05:28 +0000164 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000165 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000166 if (DT)
Anna Thomas734ab3f2017-07-07 18:05:28 +0000167 DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000168}
169
170/// Connect the unrolling epilog code to the original loop.
171/// The unrolling epilog code contains code to execute the
172/// 'extra' iterations if the run-time trip count modulo the
173/// unroll count is non-zero.
174///
175/// This function performs the following:
176/// - Update PHI nodes at the unrolling loop exit and epilog loop exit
177/// - Create PHI nodes at the unrolling loop exit to combine
178/// values that exit the unrolling loop code and jump around it.
179/// - Update PHI operands in the epilog loop by the new PHI nodes
180/// - Branch around the epilog loop if extra iters (ModVal) is zero.
181///
182static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
183 BasicBlock *Exit, BasicBlock *PreHeader,
184 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
185 ValueToValueMapTy &VMap, DominatorTree *DT,
186 LoopInfo *LI, bool PreserveLCSSA) {
187 BasicBlock *Latch = L->getLoopLatch();
188 assert(Latch && "Loop must have a latch");
189 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
190
191 // Loop structure should be the following:
192 //
193 // PreHeader
194 // NewPreHeader
195 // Header
196 // ...
197 // Latch
198 // NewExit (PN)
199 // EpilogPreHeader
200 // EpilogHeader
201 // ...
202 // EpilogLatch
203 // Exit (EpilogPN)
204
205 // Update PHI nodes at NewExit and Exit.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000206 for (PHINode &PN : NewExit->phis()) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000207 // PN should be used in another PHI located in Exit block as
208 // Exit was split by SplitBlockPredecessors into Exit and NewExit
209 // Basicaly it should look like:
210 // NewExit:
211 // PN = PHI [I, Latch]
212 // ...
213 // Exit:
214 // EpilogPN = PHI [PN, EpilogPreHeader]
215 //
216 // There is EpilogPreHeader incoming block instead of NewExit as
217 // NewExit was spilt 1 more time to get EpilogPreHeader.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000218 assert(PN.hasOneUse() && "The phi should have 1 use");
219 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
David L Kreitzer188de5a2016-04-05 12:19:35 +0000220 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
221
222 // Add incoming PreHeader from branch around the Loop
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000223 PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000224
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000225 Value *V = PN.getIncomingValueForBlock(Latch);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000226 Instruction *I = dyn_cast<Instruction>(V);
227 if (I && L->contains(I))
228 // If value comes from an instruction in the loop add VMap value.
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000229 V = VMap.lookup(I);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000230 // For the instruction out of the loop, constant or undefined value
231 // insert value itself.
232 EpilogPN->addIncoming(V, EpilogLatch);
233
234 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
235 "EpilogPN should have EpilogPreHeader incoming block");
236 // Change EpilogPreHeader incoming block to NewExit.
237 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
238 NewExit);
239 // Now PHIs should look like:
240 // NewExit:
241 // PN = PHI [I, Latch], [undef, PreHeader]
242 // ...
243 // Exit:
244 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
245 }
246
247 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
248 // Update corresponding PHI nodes in epilog loop.
249 for (BasicBlock *Succ : successors(Latch)) {
250 // Skip this as we already updated phis in exit blocks.
251 if (!L->contains(Succ))
252 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000253 for (PHINode &PN : Succ->phis()) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000254 // Add new PHI nodes to the loop exit block and update epilog
255 // PHIs with the new PHI values.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000256 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000257 NewExit->getFirstNonPHI());
258 // Adding a value to the new PHI node from the unrolling loop preheader.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000259 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000260 // Adding a value to the new PHI node from the unrolling loop latch.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000261 NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000262
263 // Update the existing PHI node operand with the value from the new PHI
264 // node. Corresponding instruction in epilog loop should be PHI.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000265 PHINode *VPN = cast<PHINode>(VMap[&PN]);
Whitney Tsang15b7f5b2019-06-17 14:38:56 +0000266 VPN->setIncomingValueForBlock(EpilogPreHeader, NewPN);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000267 }
268 }
269
270 Instruction *InsertPt = NewExit->getTerminator();
271 IRBuilder<> B(InsertPt);
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000272 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000273 assert(Exit && "Loop must have a single exit block only");
Eli Friedman0a217452017-01-18 23:26:37 +0000274 // Split the epilogue exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000275 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000276 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000277 PreserveLCSSA);
278 // Add the branch to the exit block (around the unrolling loop)
279 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000280 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000281 if (DT)
282 DT->changeImmediateDominator(Exit, NewExit);
283
284 // Split the main loop exit to maintain canonicalization guarantees.
285 SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000286 SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
Eli Friedman0a217452017-01-18 23:26:37 +0000287 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000288}
289
290/// Create a clone of the blocks in a loop and connect them together.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000291/// If CreateRemainderLoop is false, loop structure will not be cloned,
292/// otherwise a new loop will be created including all cloned blocks, and the
293/// iterator of it switches to count NewIter down to 0.
294/// The cloned blocks should be inserted between InsertTop and InsertBot.
295/// If loop structure is cloned InsertTop should be new preheader, InsertBot
296/// new loop exit.
Anna Thomase5e5e592017-06-30 17:57:07 +0000297/// Return the new cloned loop that is created when CreateRemainderLoop is true.
298static Loop *
299CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
Sam Parker718c8a62017-08-14 09:25:26 +0000300 const bool UseEpilogRemainder, const bool UnrollRemainder,
301 BasicBlock *InsertTop,
Anna Thomase5e5e592017-06-30 17:57:07 +0000302 BasicBlock *InsertBot, BasicBlock *Preheader,
303 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
304 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000305 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
Andrew Trickd04d15292011-12-09 06:19:40 +0000306 BasicBlock *Header = L->getHeader();
307 BasicBlock *Latch = L->getLoopLatch();
308 Function *F = Header->getParent();
309 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
310 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000311 Loop *ParentLoop = L->getParentLoop();
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000312 NewLoopsMap NewLoops;
Florian Hahn5364cf32017-01-31 11:13:44 +0000313 NewLoops[ParentLoop] = ParentLoop;
314 if (!CreateRemainderLoop)
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000315 NewLoops[L] = ParentLoop;
316
Andrew Trickd04d15292011-12-09 06:19:40 +0000317 // For each block in the original loop, create a new copy,
318 // and update the value map with the newly created values.
319 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000320 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000321 NewBlocks.push_back(NewBB);
Florian Hahn5364cf32017-01-31 11:13:44 +0000322
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000323 // If we're unrolling the outermost loop, there's no remainder loop,
324 // and this block isn't in a nested loop, then the new block is not
325 // in any loop. Otherwise, add it to loopinfo.
326 if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000327 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
Andrew Trickd04d15292011-12-09 06:19:40 +0000328
329 VMap[*BB] = NewBB;
330 if (Header == *BB) {
331 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000332 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000333 InsertTop->getTerminator()->setSuccessor(0, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000334 }
Junmo Park502ff662016-01-28 01:23:18 +0000335
Eli Friedman0a217452017-01-18 23:26:37 +0000336 if (DT) {
337 if (Header == *BB) {
338 // The header is dominated by the preheader.
339 DT->addNewBlock(NewBB, InsertTop);
340 } else {
341 // Copy information from original loop to unrolled loop.
342 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
343 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
344 }
345 }
346
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000347 if (Latch == *BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000348 // For the last block, if CreateRemainderLoop is false, create a direct
349 // jump to InsertBot. If not, create a loop back to cloned head.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000350 VMap.erase((*BB)->getTerminator());
351 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
352 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000353 IRBuilder<> Builder(LatchBR);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000354 if (!CreateRemainderLoop) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000355 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000356 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000357 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
358 suffix + ".iter",
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000359 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000360 Value *IdxSub =
361 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
362 NewIdx->getName() + ".sub");
363 Value *IdxCmp =
364 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000365 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000366 NewIdx->addIncoming(NewIter, InsertTop);
367 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000368 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000369 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000370 }
371 }
372
373 // Change the incoming values to the ones defined in the preheader or
374 // cloned loop.
375 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000376 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000377 if (!CreateRemainderLoop) {
378 if (UseEpilogRemainder) {
379 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
380 NewPHI->setIncomingBlock(idx, InsertTop);
381 NewPHI->removeIncomingValue(Latch, false);
382 } else {
383 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
384 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
385 }
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000386 } else {
387 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
388 NewPHI->setIncomingBlock(idx, InsertTop);
389 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
390 idx = NewPHI->getBasicBlockIndex(Latch);
391 Value *InVal = NewPHI->getIncomingValue(idx);
392 NewPHI->setIncomingBlock(idx, NewLatch);
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000393 if (Value *V = VMap.lookup(InVal))
394 NewPHI->setIncomingValue(idx, V);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000395 }
396 }
Florian Hahn5364cf32017-01-31 11:13:44 +0000397 if (CreateRemainderLoop) {
Dávid Bolvanský914128a2019-11-03 20:03:54 +0100398 Loop *NewLoop = NewLoops[L];
Florian Hahn5364cf32017-01-31 11:13:44 +0000399 assert(NewLoop && "L should have been cloned");
Dávid Bolvanský914128a2019-11-03 20:03:54 +0100400 MDNode *LoopID = NewLoop->getLoopID();
Sam Parker7cd826a2017-09-04 08:12:16 +0000401
402 // Only add loop metadata if the loop is not going to be completely
403 // unrolled.
404 if (UnrollRemainder)
405 return NewLoop;
406
Michael Kruse72448522018-12-12 17:32:52 +0000407 Optional<MDNode *> NewLoopID = makeFollowupLoopID(
408 LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
409 if (NewLoopID.hasValue()) {
410 NewLoop->setLoopID(NewLoopID.getValue());
411
412 // Do not setLoopAlreadyUnrolled if loop attributes have been defined
413 // explicitly.
414 return NewLoop;
415 }
416
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000417 // Add unroll disable metadata to disable future unrolling for this loop.
Hongbin Zheng73f65042017-10-15 07:31:02 +0000418 NewLoop->setLoopAlreadyUnrolled();
Anna Thomase5e5e592017-06-30 17:57:07 +0000419 return NewLoop;
Andrew Trickd04d15292011-12-09 06:19:40 +0000420 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000421 else
422 return nullptr;
Andrew Trickd04d15292011-12-09 06:19:40 +0000423}
424
Anna Thomas8e431a92017-07-12 20:55:43 +0000425/// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
426/// is populated with all the loop exit blocks other than the LatchExit block.
Serguei Katkovf1ee04c2019-07-15 05:51:10 +0000427static bool canSafelyUnrollMultiExitLoop(Loop *L, BasicBlock *LatchExit,
428 bool PreserveLCSSA,
429 bool UseEpilogRemainder) {
Anna Thomas8e431a92017-07-12 20:55:43 +0000430
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000431 // We currently have some correctness constrains in unrolling a multi-exit
432 // loop. Check for these below.
433
Anna Thomas8e431a92017-07-12 20:55:43 +0000434 // We rely on LCSSA form being preserved when the exit blocks are transformed.
435 if (!PreserveLCSSA)
436 return false;
Anna Thomas8e431a92017-07-12 20:55:43 +0000437
438 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
439 // UnrollRuntimeMultiExit is true. This will need updating the logic in
440 // connectEpilog/connectProlog.
441 if (!LatchExit->getSinglePredecessor()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000442 LLVM_DEBUG(
443 dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
444 "predecessor.\n");
Anna Thomas8e431a92017-07-12 20:55:43 +0000445 return false;
446 }
447 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
448 // and L is an inner loop. This is because in presence of multiple exits, the
449 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
450 // outer loop. This is automatically handled in the prolog case, so we do not
451 // have that bug in prolog generation.
452 if (UseEpilogRemainder && L->getParentLoop())
453 return false;
454
455 // All constraints have been satisfied.
456 return true;
457}
458
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000459/// Returns true if we can profitably unroll the multi-exit loop L. Currently,
460/// we return true only if UnrollRuntimeMultiExit is set to true.
461static bool canProfitablyUnrollMultiExitLoop(
462 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
463 bool PreserveLCSSA, bool UseEpilogRemainder) {
Anna Thomas8e431a92017-07-12 20:55:43 +0000464
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000465#if !defined(NDEBUG)
Serguei Katkovf1ee04c2019-07-15 05:51:10 +0000466 assert(canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA,
467 UseEpilogRemainder) &&
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000468 "Should be safe to unroll before checking profitability!");
469#endif
Anna Thomasf34537d2017-09-15 15:56:05 +0000470
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000471 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
Anna Thomasf34537d2017-09-15 15:56:05 +0000472 if (UnrollRuntimeMultiExit.getNumOccurrences())
473 return UnrollRuntimeMultiExit;
474
475 // The main pain point with multi-exit loop unrolling is that once unrolled,
476 // we will not be able to merge all blocks into a straight line code.
477 // There are branches within the unrolled loop that go to the OtherExits.
478 // The second point is the increase in code size, but this is true
479 // irrespective of multiple exits.
480
481 // Note: Both the heuristics below are coarse grained. We are essentially
482 // enabling unrolling of loops that have a single side exit other than the
483 // normal LatchExit (i.e. exiting into a deoptimize block).
484 // The heuristics considered are:
485 // 1. low number of branches in the unrolled version.
486 // 2. high predictability of these extra branches.
487 // We avoid unrolling loops that have more than two exiting blocks. This
488 // limits the total number of branches in the unrolled loop to be atmost
489 // the unroll factor (since one of the exiting blocks is the latch block).
490 SmallVector<BasicBlock*, 4> ExitingBlocks;
491 L->getExitingBlocks(ExitingBlocks);
492 if (ExitingBlocks.size() > 2)
493 return false;
494
495 // The second heuristic is that L has one exit other than the latchexit and
496 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
497 // taken, which also implies the branch leading to the deoptimize block is
498 // highly predictable.
499 return (OtherExits.size() == 1 &&
500 OtherExits[0]->getTerminatingDeoptimizeCall());
501 // TODO: These can be fine-tuned further to consider code size or deopt states
502 // that are captured by the deoptimize exit block.
503 // Also, we can extend this to support more cases, if we actually
504 // know of kinds of multiexit loops that would benefit from unrolling.
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000505}
Anna Thomas8e431a92017-07-12 20:55:43 +0000506
David L Kreitzer188de5a2016-04-05 12:19:35 +0000507/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000508/// run-time trip-count.
509///
510/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000511/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000512/// to the unroll factor as the number of *extra* copies added).
513/// We assume also that the loop unroll factor is a power-of-two. So, after
514/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000515/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000516/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
517/// the switch instruction is generated.
518///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000519/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000520/// extraiters = tripcount % loopfactor
521/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000522/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000523/// Prol: LoopBody;
524/// extraiters -= 1 // Omitted if unroll factor is 2.
525/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000526/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000527/// Loop:
528/// ...
529/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000530///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000531/// ***Epilog case***
532/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000533/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000534/// unroll_iters = tripcount - extraiters
535/// Loop: LoopBody; (executes unroll_iter times);
536/// unroll_iter -= 1
537/// if (unroll_iter != 0) jump Loop:
538/// LoopExit:
539/// if (extraiters == 0) jump EpilExit:
540/// Epil: LoopBody; (executes extraiters times)
541/// extraiters -= 1 // Omitted if unroll factor is 2.
542/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
543/// EpilExit:
544
545bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
546 bool AllowExpensiveTripCount,
547 bool UseEpilogRemainder,
Alina Sbirlea2312a062019-04-12 19:16:07 +0000548 bool UnrollRemainder, bool ForgetAllSCEV,
549 LoopInfo *LI, ScalarEvolution *SE,
550 DominatorTree *DT, AssumptionCache *AC,
551 bool PreserveLCSSA, Loop **ResultLoop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000552 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
553 LLVM_DEBUG(L->dump());
554 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
555 : dbgs() << "Using prolog remainder.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000556
Anna Thomase5e5e592017-06-30 17:57:07 +0000557 // Make sure the loop is in canonical form.
Anna Thomasbafe7662017-07-11 20:44:37 +0000558 if (!L->isLoopSimplifyForm()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000559 LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000560 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000561 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000562
Anna Thomas91eed9a2017-06-23 14:28:01 +0000563 // Guaranteed by LoopSimplifyForm.
564 BasicBlock *Latch = L->getLoopLatch();
Anna Thomase5e5e592017-06-30 17:57:07 +0000565 BasicBlock *Header = L->getHeader();
Anna Thomas91eed9a2017-06-23 14:28:01 +0000566
Anna Thomas91eed9a2017-06-23 14:28:01 +0000567 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
David Green9108c2b2018-09-25 10:08:47 +0000568
569 if (!LatchBR || LatchBR->isUnconditional()) {
570 // The loop-rotate pass can be helpful to avoid this in many cases.
571 LLVM_DEBUG(
572 dbgs()
573 << "Loop latch not terminated by a conditional branch.\n");
574 return false;
575 }
576
Anna Thomas8e431a92017-07-12 20:55:43 +0000577 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
578 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
David Green9108c2b2018-09-25 10:08:47 +0000579
580 if (L->contains(LatchExit)) {
581 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
582 // targets of the Latch be an exit block out of the loop.
583 LLVM_DEBUG(
584 dbgs()
585 << "One of the loop latch successors must be the exit block.\n");
586 return false;
587 }
588
Anna Thomas8e431a92017-07-12 20:55:43 +0000589 // These are exit blocks other than the target of the latch exiting block.
590 SmallVector<BasicBlock *, 4> OtherExits;
Serguei Katkovf1ee04c2019-07-15 05:51:10 +0000591 L->getUniqueNonLatchExitBlocks(OtherExits);
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000592 bool isMultiExitUnrollingEnabled =
Serguei Katkovf1ee04c2019-07-15 05:51:10 +0000593 canSafelyUnrollMultiExitLoop(L, LatchExit, PreserveLCSSA,
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000594 UseEpilogRemainder) &&
595 canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
596 UseEpilogRemainder);
Anna Thomas8e431a92017-07-12 20:55:43 +0000597 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
598 if (!isMultiExitUnrollingEnabled &&
599 (!L->getExitingBlock() || OtherExits.size())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000600 LLVM_DEBUG(
Anna Thomas8e431a92017-07-12 20:55:43 +0000601 dbgs()
602 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
603 "enabled!\n");
Anna Thomaseb6d5d12017-07-06 18:39:26 +0000604 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000605 }
Sanjay Patele08381a2016-02-08 19:27:33 +0000606 // Use Scalar Evolution to compute the trip count. This allows more loops to
607 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000608 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000609 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000610
Sanjay Patele08381a2016-02-08 19:27:33 +0000611 // Only unroll loops with a computable trip count, and the trip count needs
612 // to be an int value (allowing a pointer type is a TODO item).
Anna Thomasdc935a62017-06-27 14:14:35 +0000613 // We calculate the backedge count by using getExitCount on the Latch block,
614 // which is proven to be the only exiting block in this loop. This is same as
615 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
616 // exiting blocks).
617 const SCEV *BECountSC = SE->getExitCount(L, Latch);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000618 if (isa<SCEVCouldNotCompute>(BECountSC) ||
Anna Thomasbafe7662017-07-11 20:44:37 +0000619 !BECountSC->getType()->isIntegerTy()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000620 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000621 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000622 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000623
Sanjoy Das11b279a2015-02-18 19:32:25 +0000624 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000625
Sanjay Patele08381a2016-02-08 19:27:33 +0000626 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000627 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000628 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Anna Thomasbafe7662017-07-11 20:44:37 +0000629 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000630 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000631 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000632 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000633
David L Kreitzer188de5a2016-04-05 12:19:35 +0000634 BasicBlock *PreHeader = L->getLoopPreheader();
635 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000636 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000637 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000638 if (!AllowExpensiveTripCount &&
Anna Thomasbafe7662017-07-11 20:44:37 +0000639 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000640 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
Sanjoy Dase178f462015-04-14 03:20:38 +0000641 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000642 }
Sanjoy Dase178f462015-04-14 03:20:38 +0000643
Sanjoy Das11b279a2015-02-18 19:32:25 +0000644 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000645 // comment on ModVal below.
Anna Thomasbafe7662017-07-11 20:44:37 +0000646 if (Log2_32(Count) > BEWidth) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000647 LLVM_DEBUG(
648 dbgs()
649 << "Count failed constraint on overflow trip count calculation.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000650 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000651 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000652
David L Kreitzer188de5a2016-04-05 12:19:35 +0000653 // Loop structure is the following:
654 //
655 // PreHeader
656 // Header
657 // ...
658 // Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000659 // LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000660
661 BasicBlock *NewPreHeader;
662 BasicBlock *NewExit = nullptr;
663 BasicBlock *PrologExit = nullptr;
664 BasicBlock *EpilogPreHeader = nullptr;
665 BasicBlock *PrologPreHeader = nullptr;
666
667 if (UseEpilogRemainder) {
668 // If epilog remainder
669 // Split PreHeader to insert a branch around loop for unrolling.
670 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
671 NewPreHeader->setName(PreHeader->getName() + ".new");
Anna Thomas91eed9a2017-06-23 14:28:01 +0000672 // Split LatchExit to create phi nodes from branch above.
673 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000674 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI,
675 nullptr, PreserveLCSSA);
Zhaoshi Zheng8af1e1c2017-12-26 23:31:21 +0000676 // NewExit gets its DebugLoc from LatchExit, which is not part of the
677 // original Loop.
678 // Fix this by setting Loop's DebugLoc to NewExit.
679 auto *NewExitTerminator = NewExit->getTerminator();
680 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
David L Kreitzer188de5a2016-04-05 12:19:35 +0000681 // Split NewExit to insert epilog remainder loop.
Zhaoshi Zheng8af1e1c2017-12-26 23:31:21 +0000682 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000683 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
684 } else {
685 // If prolog remainder
686 // Split the original preheader twice to insert prolog remainder loop
687 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
688 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
689 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
690 DT, LI);
691 PrologExit->setName(Header->getName() + ".prol.loopexit");
692 // Split PrologExit to get NewPreHeader.
693 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
694 NewPreHeader->setName(PreHeader->getName() + ".new");
695 }
696 // Loop structure should be the following:
697 // Epilog Prolog
698 //
699 // PreHeader PreHeader
700 // *NewPreHeader *PrologPreHeader
701 // Header *PrologExit
702 // ... *NewPreHeader
703 // Latch Header
704 // *NewExit ...
705 // *EpilogPreHeader Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000706 // LatchExit LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000707
708 // Calculate conditions for branch around loop for unrolling
709 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000710 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000711 // extra iterations = run-time trip count % loop unroll factor
712 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000713 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
714 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000715 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
716 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000717 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000718 Value *ModVal;
719 // Calculate ModVal = (BECount + 1) % Count.
720 // Note that TripCount is BECount + 1.
721 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000722 // When Count is power of 2 we don't BECount for epilog case, however we'll
723 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000724 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000725 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000726 // OR
727 // 2. The addition computing TripCount overflowed.
728 //
729 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
730 // the number of iterations that remain to be run in the original loop is a
731 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
732 // explicitly check this above).
733 } else {
734 // As (BECount + 1) can potentially unsigned overflow we count
735 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
736 Value *ModValTmp = B.CreateURem(BECount,
737 ConstantInt::get(BECount->getType(),
738 Count));
739 Value *ModValAdd = B.CreateAdd(ModValTmp,
740 ConstantInt::get(ModValTmp->getType(), 1));
741 // At that point (BECount % Count) + 1 could be equal to Count.
742 // To handle this case we need to take mod by Count one more time.
743 ModVal = B.CreateURem(ModValAdd,
744 ConstantInt::get(BECount->getType(), Count),
745 "xtraiter");
746 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000747 Value *BranchVal =
748 UseEpilogRemainder ? B.CreateICmpULT(BECount,
749 ConstantInt::get(BECount->getType(),
750 Count - 1)) :
751 B.CreateIsNotNull(ModVal, "lcmp.mod");
752 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
753 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000754 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000755 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000756 PreHeaderBR->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000757 if (DT) {
758 if (UseEpilogRemainder)
759 DT->changeImmediateDominator(NewExit, PreHeader);
760 else
761 DT->changeImmediateDominator(PrologExit, PreHeader);
762 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000763 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000764 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000765 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000766 LoopBlocksDFS LoopBlocks(L);
767 LoopBlocks.perform(LI);
768
769 //
770 // For each extra loop iteration, create a copy of the loop's basic blocks
771 // and generate a condition that branches to the copy depending on the
772 // number of 'left over' iterations.
773 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000774 std::vector<BasicBlock *> NewBlocks;
775 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000776
David L Kreitzer188de5a2016-04-05 12:19:35 +0000777 // For unroll factor 2 remainder loop will have 1 iterations.
778 // Do not create 1 iteration loop.
779 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000780
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000781 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
782 // the loop, otherwise we create a cloned loop to execute the extra
783 // iterations. This function adds the appropriate CFG connections.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000784 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000785 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
Anna Thomase5e5e592017-06-30 17:57:07 +0000786 Loop *remainderLoop = CloneLoopBlocks(
Sam Parker718c8a62017-08-14 09:25:26 +0000787 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
788 InsertTop, InsertBot,
Anna Thomase5e5e592017-06-30 17:57:07 +0000789 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000790
David L Kreitzer188de5a2016-04-05 12:19:35 +0000791 // Insert the cloned blocks into the function.
792 F->getBasicBlockList().splice(InsertBot->getIterator(),
793 F->getBasicBlockList(),
794 NewBlocks[0]->getIterator(),
795 F->end());
796
Anna Thomase5e5e592017-06-30 17:57:07 +0000797 // Now the loop blocks are cloned and the other exiting blocks from the
798 // remainder are connected to the original Loop's exit blocks. The remaining
799 // work is to update the phi nodes in the original loop, and take in the
Anna Thomas2dfa4122019-01-08 17:16:25 +0000800 // values from the cloned region.
Anna Thomase5e5e592017-06-30 17:57:07 +0000801 for (auto *BB : OtherExits) {
802 for (auto &II : *BB) {
803
804 // Given we preserve LCSSA form, we know that the values used outside the
805 // loop will be used through these phi nodes at the exit blocks that are
806 // transformed below.
807 if (!isa<PHINode>(II))
808 break;
809 PHINode *Phi = cast<PHINode>(&II);
810 unsigned oldNumOperands = Phi->getNumIncomingValues();
811 // Add the incoming values from the remainder code to the end of the phi
812 // node.
813 for (unsigned i =0; i < oldNumOperands; i++){
Anna Thomas512dde72017-09-15 13:29:33 +0000814 Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
Anna Thomas70ffd652017-07-10 15:29:38 +0000815 // newVal can be a constant or derived from values outside the loop, and
Anna Thomas512dde72017-09-15 13:29:33 +0000816 // hence need not have a VMap value. Also, since lookup already generated
817 // a default "null" VMap entry for this value, we need to populate that
818 // VMap entry correctly, with the mapped entry being itself.
819 if (!newVal) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000820 newVal = Phi->getIncomingValue(i);
Anna Thomas512dde72017-09-15 13:29:33 +0000821 VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
822 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000823 Phi->addIncoming(newVal,
824 cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
825 }
826 }
Simon Pilgrimf32f4be2017-07-13 17:10:12 +0000827#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
Anna Thomasec9b3262017-07-13 13:21:23 +0000828 for (BasicBlock *SuccBB : successors(BB)) {
829 assert(!(any_of(OtherExits,
830 [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
831 SuccBB == LatchExit) &&
832 "Breaks the definition of dedicated exits!");
833 }
834#endif
Anna Thomas2dfa4122019-01-08 17:16:25 +0000835 }
836
837 // Update the immediate dominator of the exit blocks and blocks that are
838 // reachable from the exit blocks. This is needed because we now have paths
839 // from both the original loop and the remainder code reaching the exit
840 // blocks. While the IDom of these exit blocks were from the original loop,
841 // now the IDom is the preheader (which decides whether the original loop or
842 // remainder code should run).
843 if (DT && !L->getExitingBlock()) {
844 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
845 // NB! We have to examine the dom children of all loop blocks, not just
846 // those which are the IDom of the exit blocks. This is because blocks
847 // reachable from the exit blocks can have their IDom as the nearest common
848 // dominator of the exit blocks.
849 for (auto *BB : L->blocks()) {
850 auto *DomNodeBB = DT->getNode(BB);
851 for (auto *DomChild : DomNodeBB->getChildren()) {
852 auto *DomChildBB = DomChild->getBlock();
853 if (!L->contains(LI->getLoopFor(DomChildBB)))
854 ChildrenToUpdate.push_back(DomChildBB);
855 }
Anna Thomasec9b3262017-07-13 13:21:23 +0000856 }
Anna Thomas2dfa4122019-01-08 17:16:25 +0000857 for (auto *BB : ChildrenToUpdate)
858 DT->changeImmediateDominator(BB, PreHeader);
Anna Thomase5e5e592017-06-30 17:57:07 +0000859 }
860
David L Kreitzer188de5a2016-04-05 12:19:35 +0000861 // Loop structure should be the following:
862 // Epilog Prolog
863 //
864 // PreHeader PreHeader
865 // NewPreHeader PrologPreHeader
866 // Header PrologHeader
867 // ... ...
868 // Latch PrologLatch
869 // NewExit PrologExit
870 // EpilogPreHeader NewPreHeader
871 // EpilogHeader Header
872 // ... ...
873 // EpilogLatch Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000874 // LatchExit LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +0000875
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000876 // Rewrite the cloned instruction operands to use the values created when the
877 // clone is created.
878 for (BasicBlock *BB : NewBlocks) {
879 for (Instruction &I : *BB) {
880 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000881 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000882 }
883 }
884
David L Kreitzer188de5a2016-04-05 12:19:35 +0000885 if (UseEpilogRemainder) {
886 // Connect the epilog code to the original loop and update the
887 // PHI functions.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000888 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000889 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
890 PreserveLCSSA);
891
892 // Update counter in loop for unrolling.
893 // I should be multiply of Count.
894 IRBuilder<> B2(NewPreHeader->getTerminator());
895 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
896 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
897 B2.SetInsertPoint(LatchBR);
898 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
899 Header->getFirstNonPHI());
900 Value *IdxSub =
901 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
902 NewIdx->getName() + ".nsub");
903 Value *IdxCmp;
904 if (LatchBR->getSuccessor(0) == Header)
905 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
906 else
907 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
908 NewIdx->addIncoming(TestVal, NewPreHeader);
909 NewIdx->addIncoming(IdxSub, Latch);
910 LatchBR->setCondition(IdxCmp);
911 } else {
912 // Connect the prolog code to the original loop and update the
913 // PHI functions.
Anna Thomas734ab3f2017-07-07 18:05:28 +0000914 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
915 NewPreHeader, VMap, DT, LI, PreserveLCSSA);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000916 }
Wei Mi59ca9662016-08-25 16:17:18 +0000917
Max Kazantsevacda4c02018-04-23 10:39:38 +0000918 // If this loop is nested, then the loop unroller changes the code in the any
919 // of its parent loops, so the Scalar Evolution pass needs to be run again.
920 SE->forgetTopmostLoop(L);
Wei Mi59ca9662016-08-25 16:17:18 +0000921
Anna Thomas0785e732019-01-03 17:44:44 +0000922 // Verify that the Dom Tree is correct.
Anna Thomasa470aa62019-01-03 19:43:33 +0000923#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
Anna Thomas0785e732019-01-03 17:44:44 +0000924 if (DT)
925 assert(DT->verify(DominatorTree::VerificationLevel::Full));
926#endif
927
Anna Thomase5e5e592017-06-30 17:57:07 +0000928 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
929 // cannot rely on the LoopUnrollPass to do this because it only does
930 // canonicalization for parent/subloops and not the sibling loops.
931 if (OtherExits.size() > 0) {
932 // Generate dedicated exit blocks for the original loop, to preserve
933 // LoopSimplifyForm.
Alina Sbirlea97468e92019-02-21 21:13:34 +0000934 formDedicatedExitBlocks(L, DT, LI, nullptr, PreserveLCSSA);
Anna Thomase5e5e592017-06-30 17:57:07 +0000935 // Generate dedicated exit blocks for the remainder loop if one exists, to
936 // preserve LoopSimplifyForm.
937 if (remainderLoop)
Alina Sbirlea97468e92019-02-21 21:13:34 +0000938 formDedicatedExitBlocks(remainderLoop, DT, LI, nullptr, PreserveLCSSA);
Anna Thomase5e5e592017-06-30 17:57:07 +0000939 }
940
Michael Kruse72448522018-12-12 17:32:52 +0000941 auto UnrollResult = LoopUnrollResult::Unmodified;
Sam Parker718c8a62017-08-14 09:25:26 +0000942 if (remainderLoop && UnrollRemainder) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000943 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
Michael Kruse72448522018-12-12 17:32:52 +0000944 UnrollResult =
Alina Sbirleada0f71a2019-04-18 23:43:49 +0000945 UnrollLoop(remainderLoop,
946 {/*Count*/ Count - 1, /*TripCount*/ Count - 1,
947 /*Force*/ false, /*AllowRuntime*/ false,
948 /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true,
949 /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1,
950 /*PeelCount*/ 0, /*UnrollRemainder*/ false, ForgetAllSCEV},
Alina Sbirlea2312a062019-04-12 19:16:07 +0000951 LI, SE, DT, AC, /*ORE*/ nullptr, PreserveLCSSA);
Sam Parker718c8a62017-08-14 09:25:26 +0000952 }
953
Michael Kruse72448522018-12-12 17:32:52 +0000954 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
955 *ResultLoop = remainderLoop;
Andrew Trickd04d15292011-12-09 06:19:40 +0000956 NumRuntimeUnrolled++;
957 return true;
958}