blob: 386ec891ec1db95fa316512427ec1333c0826931 [file] [log] [blame]
Andrew Trickd04d15292011-12-09 06:19:40 +00001//===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements some loop unrolling utilities for loops with run-time
11// trip counts. See LoopUnroll.cpp for unrolling loops with compile-time
12// trip counts.
13//
Jakub Staszak1b1d5232011-12-18 21:52:30 +000014// The functions in this file are used to generate extra code when the
Andrew Trickd04d15292011-12-09 06:19:40 +000015// run-time trip count modulo the unroll factor is not 0. When this is the
16// case, we need to generate code to execute these 'left over' iterations.
17//
Jakub Staszak1b1d5232011-12-18 21:52:30 +000018// The current strategy generates an if-then-else sequence prior to the
David L Kreitzer188de5a2016-04-05 12:19:35 +000019// unrolled loop to execute the 'left over' iterations before or after the
20// unrolled loop.
Andrew Trickd04d15292011-12-09 06:19:40 +000021//
22//===----------------------------------------------------------------------===//
23
Florian Hahna1cc8482018-06-12 11:16:56 +000024#include "llvm/ADT/SmallPtrSet.h"
David Blaikiea373d182018-03-28 17:44:36 +000025#include "llvm/ADT/Statistic.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000026#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000027#include "llvm/Analysis/LoopIterator.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000028#include "llvm/Analysis/ScalarEvolution.h"
29#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/BasicBlock.h"
Chandler Carruth32c52c72015-01-18 02:39:37 +000031#include "llvm/IR/Dominators.h"
Kevin Qinfc02e3c2014-09-29 11:15:00 +000032#include "llvm/IR/Metadata.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000033#include "llvm/IR/Module.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
David Blaikiea373d182018-03-28 17:44:36 +000036#include "llvm/Transforms/Utils.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Cloning.h"
Anna Thomase5e5e592017-06-30 17:57:07 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000040#include "llvm/Transforms/Utils/UnrollLoop.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000041#include <algorithm>
42
43using namespace llvm;
44
Chandler Carruth964daaa2014-04-22 02:55:47 +000045#define DEBUG_TYPE "loop-unroll"
46
Jakub Staszak1b1d5232011-12-18 21:52:30 +000047STATISTIC(NumRuntimeUnrolled,
Andrew Trickd04d15292011-12-09 06:19:40 +000048 "Number of loops unrolled with run-time trip counts");
Anna Thomase5e5e592017-06-30 17:57:07 +000049static 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"));
Andrew Trickd04d15292011-12-09 06:19:40 +000053
54/// Connect the unrolling prolog code to the original loop.
55/// The unrolling prolog code contains code to execute the
56/// 'extra' iterations if the run-time trip count modulo the
57/// unroll count is non-zero.
58///
59/// This function performs the following:
60/// - Create PHI nodes at prolog end block to combine values
61/// that exit the prolog code and jump around the prolog.
62/// - Add a PHI operand to a PHI node at the loop exit block
63/// for values that exit the prolog and go around the loop.
64/// - Branch around the original loop if the trip count is less
65/// than the unroll factor.
66///
Sanjoy Das11b279a2015-02-18 19:32:25 +000067static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
Anna Thomas734ab3f2017-07-07 18:05:28 +000068 BasicBlock *PrologExit,
69 BasicBlock *OriginalLoopLatchExit,
70 BasicBlock *PreHeader, BasicBlock *NewPreHeader,
71 ValueToValueMapTy &VMap, DominatorTree *DT,
72 LoopInfo *LI, bool PreserveLCSSA) {
Anna Thomas18be3cb2018-12-21 19:45:05 +000073 // Loop structure should be the following:
74 // Preheader
Anna Thomas98743fa2018-12-28 18:52:16 +000075 // PrologHeader
Anna Thomas18be3cb2018-12-21 19:45:05 +000076 // ...
77 // PrologLatch
78 // PrologExit
79 // NewPreheader
80 // Header
81 // ...
82 // Latch
83 // LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +000084 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000085 assert(Latch && "Loop must have a latch");
David L Kreitzer188de5a2016-04-05 12:19:35 +000086 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
Andrew Trickd04d15292011-12-09 06:19:40 +000087
88 // Create a PHI node for each outgoing value from the original loop
89 // (which means it is an outgoing value from the prolog code too).
90 // The new PHI node is inserted in the prolog end basic block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000091 // The new PHI node value is added as an operand of a PHI node in either
Andrew Trickd04d15292011-12-09 06:19:40 +000092 // the loop header or the loop exit block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000093 for (BasicBlock *Succ : successors(Latch)) {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +000094 for (PHINode &PN : Succ->phis()) {
Andrew Trickd04d15292011-12-09 06:19:40 +000095 // Add a new PHI node to the prolog end block and add the
96 // appropriate incoming values.
Anna Thomas18be3cb2018-12-21 19:45:05 +000097 // TODO: This code assumes that the PrologExit (or the LatchExit block for
98 // prolog loop) contains only one predecessor from the loop, i.e. the
99 // PrologLatch. When supporting multiple-exiting block loops, we can have
100 // two or more blocks that have the LatchExit as the target in the
101 // original loop.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000102 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000103 PrologExit->getFirstNonPHI());
Andrew Trickd04d15292011-12-09 06:19:40 +0000104 // Adding a value to the new PHI node from the original loop preheader.
105 // This is the value that skips all the prolog code.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000106 if (L->contains(&PN)) {
Anna Thomas18be3cb2018-12-21 19:45:05 +0000107 // Succ is loop header.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000108 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader),
David L Kreitzer188de5a2016-04-05 12:19:35 +0000109 PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +0000110 } else {
Anna Thomas98743fa2018-12-28 18:52:16 +0000111 // Succ is LatchExit.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000112 NewPN->addIncoming(UndefValue::get(PN.getType()), PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +0000113 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000114
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000115 Value *V = PN.getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000116 if (Instruction *I = dyn_cast<Instruction>(V)) {
117 if (L->contains(I)) {
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000118 V = VMap.lookup(I);
Andrew Trickd04d15292011-12-09 06:19:40 +0000119 }
120 }
121 // Adding a value to the new PHI node from the last prolog block
122 // that was created.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000123 NewPN->addIncoming(V, PrologLatch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000124
125 // Update the existing PHI node operand with the value from the
126 // new PHI node. How this is done depends on if the existing
127 // PHI node is in the original loop block, or the exit block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000128 if (L->contains(&PN)) {
129 PN.setIncomingValue(PN.getBasicBlockIndex(NewPreHeader), NewPN);
Andrew Trickd04d15292011-12-09 06:19:40 +0000130 } else {
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000131 PN.addIncoming(NewPN, PrologExit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000132 }
133 }
134 }
135
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000136 // Make sure that created prolog loop is in simplified form
137 SmallVector<BasicBlock *, 4> PrologExitPreds;
138 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
139 if (PrologLoop) {
140 for (BasicBlock *PredBB : predecessors(PrologExit))
141 if (PrologLoop->contains(PredBB))
142 PrologExitPreds.push_back(PredBB);
143
144 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000145 nullptr, PreserveLCSSA);
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000146 }
147
Sanjay Patele08381a2016-02-08 19:27:33 +0000148 // Create a branch around the original loop, which is taken if there are no
Sanjoy Das11b279a2015-02-18 19:32:25 +0000149 // iterations remaining to be executed after running the prologue.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000150 Instruction *InsertPt = PrologExit->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000151 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000152
153 assert(Count != 0 && "nonsensical Count!");
154
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000155 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
156 // This means %xtraiter is (BECount + 1) and all of the iterations of this
157 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
158 // then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000159 Value *BrLoopExit =
160 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000161 // Split the exit to maintain loop canonicalization guarantees
Anna Thomas734ab3f2017-07-07 18:05:28 +0000162 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
163 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000164 nullptr, PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000165 // Add the branch to the exit block (around the unrolled loop)
Anna Thomas734ab3f2017-07-07 18:05:28 +0000166 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000167 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000168 if (DT)
Anna Thomas734ab3f2017-07-07 18:05:28 +0000169 DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000170}
171
172/// Connect the unrolling epilog code to the original loop.
173/// The unrolling epilog code contains code to execute the
174/// 'extra' iterations if the run-time trip count modulo the
175/// unroll count is non-zero.
176///
177/// This function performs the following:
178/// - Update PHI nodes at the unrolling loop exit and epilog loop exit
179/// - Create PHI nodes at the unrolling loop exit to combine
180/// values that exit the unrolling loop code and jump around it.
181/// - Update PHI operands in the epilog loop by the new PHI nodes
182/// - Branch around the epilog loop if extra iters (ModVal) is zero.
183///
184static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
185 BasicBlock *Exit, BasicBlock *PreHeader,
186 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
187 ValueToValueMapTy &VMap, DominatorTree *DT,
188 LoopInfo *LI, bool PreserveLCSSA) {
189 BasicBlock *Latch = L->getLoopLatch();
190 assert(Latch && "Loop must have a latch");
191 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
192
193 // Loop structure should be the following:
194 //
195 // PreHeader
196 // NewPreHeader
197 // Header
198 // ...
199 // Latch
200 // NewExit (PN)
201 // EpilogPreHeader
202 // EpilogHeader
203 // ...
204 // EpilogLatch
205 // Exit (EpilogPN)
206
207 // Update PHI nodes at NewExit and Exit.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000208 for (PHINode &PN : NewExit->phis()) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000209 // PN should be used in another PHI located in Exit block as
210 // Exit was split by SplitBlockPredecessors into Exit and NewExit
211 // Basicaly it should look like:
212 // NewExit:
213 // PN = PHI [I, Latch]
214 // ...
215 // Exit:
216 // EpilogPN = PHI [PN, EpilogPreHeader]
217 //
218 // There is EpilogPreHeader incoming block instead of NewExit as
219 // NewExit was spilt 1 more time to get EpilogPreHeader.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000220 assert(PN.hasOneUse() && "The phi should have 1 use");
221 PHINode *EpilogPN = cast<PHINode>(PN.use_begin()->getUser());
David L Kreitzer188de5a2016-04-05 12:19:35 +0000222 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
223
224 // Add incoming PreHeader from branch around the Loop
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000225 PN.addIncoming(UndefValue::get(PN.getType()), PreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000226
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000227 Value *V = PN.getIncomingValueForBlock(Latch);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000228 Instruction *I = dyn_cast<Instruction>(V);
229 if (I && L->contains(I))
230 // If value comes from an instruction in the loop add VMap value.
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000231 V = VMap.lookup(I);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000232 // For the instruction out of the loop, constant or undefined value
233 // insert value itself.
234 EpilogPN->addIncoming(V, EpilogLatch);
235
236 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
237 "EpilogPN should have EpilogPreHeader incoming block");
238 // Change EpilogPreHeader incoming block to NewExit.
239 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
240 NewExit);
241 // Now PHIs should look like:
242 // NewExit:
243 // PN = PHI [I, Latch], [undef, PreHeader]
244 // ...
245 // Exit:
246 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
247 }
248
249 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
250 // Update corresponding PHI nodes in epilog loop.
251 for (BasicBlock *Succ : successors(Latch)) {
252 // Skip this as we already updated phis in exit blocks.
253 if (!L->contains(Succ))
254 continue;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000255 for (PHINode &PN : Succ->phis()) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000256 // Add new PHI nodes to the loop exit block and update epilog
257 // PHIs with the new PHI values.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000258 PHINode *NewPN = PHINode::Create(PN.getType(), 2, PN.getName() + ".unr",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000259 NewExit->getFirstNonPHI());
260 // Adding a value to the new PHI node from the unrolling loop preheader.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000261 NewPN->addIncoming(PN.getIncomingValueForBlock(NewPreHeader), PreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000262 // Adding a value to the new PHI node from the unrolling loop latch.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000263 NewPN->addIncoming(PN.getIncomingValueForBlock(Latch), Latch);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000264
265 // Update the existing PHI node operand with the value from the new PHI
266 // node. Corresponding instruction in epilog loop should be PHI.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000267 PHINode *VPN = cast<PHINode>(VMap[&PN]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000268 VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
269 }
270 }
271
272 Instruction *InsertPt = NewExit->getTerminator();
273 IRBuilder<> B(InsertPt);
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000274 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000275 assert(Exit && "Loop must have a single exit block only");
Eli Friedman0a217452017-01-18 23:26:37 +0000276 // Split the epilogue exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000277 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000278 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI, nullptr,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000279 PreserveLCSSA);
280 // Add the branch to the exit block (around the unrolling loop)
281 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000282 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000283 if (DT)
284 DT->changeImmediateDominator(Exit, NewExit);
285
286 // Split the main loop exit to maintain canonicalization guarantees.
287 SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000288 SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI, nullptr,
Eli Friedman0a217452017-01-18 23:26:37 +0000289 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000290}
291
292/// Create a clone of the blocks in a loop and connect them together.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000293/// If CreateRemainderLoop is false, loop structure will not be cloned,
294/// otherwise a new loop will be created including all cloned blocks, and the
295/// iterator of it switches to count NewIter down to 0.
296/// The cloned blocks should be inserted between InsertTop and InsertBot.
297/// If loop structure is cloned InsertTop should be new preheader, InsertBot
298/// new loop exit.
Anna Thomase5e5e592017-06-30 17:57:07 +0000299/// Return the new cloned loop that is created when CreateRemainderLoop is true.
300static Loop *
301CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
Sam Parker718c8a62017-08-14 09:25:26 +0000302 const bool UseEpilogRemainder, const bool UnrollRemainder,
303 BasicBlock *InsertTop,
Anna Thomase5e5e592017-06-30 17:57:07 +0000304 BasicBlock *InsertBot, BasicBlock *Preheader,
305 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
306 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000307 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
Andrew Trickd04d15292011-12-09 06:19:40 +0000308 BasicBlock *Header = L->getHeader();
309 BasicBlock *Latch = L->getLoopLatch();
310 Function *F = Header->getParent();
311 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
312 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000313 Loop *ParentLoop = L->getParentLoop();
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000314 NewLoopsMap NewLoops;
Florian Hahn5364cf32017-01-31 11:13:44 +0000315 NewLoops[ParentLoop] = ParentLoop;
316 if (!CreateRemainderLoop)
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000317 NewLoops[L] = ParentLoop;
318
Andrew Trickd04d15292011-12-09 06:19:40 +0000319 // For each block in the original loop, create a new copy,
320 // and update the value map with the newly created values.
321 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000322 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000323 NewBlocks.push_back(NewBB);
Florian Hahn5364cf32017-01-31 11:13:44 +0000324
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000325 // If we're unrolling the outermost loop, there's no remainder loop,
326 // and this block isn't in a nested loop, then the new block is not
327 // in any loop. Otherwise, add it to loopinfo.
328 if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000329 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
Andrew Trickd04d15292011-12-09 06:19:40 +0000330
331 VMap[*BB] = NewBB;
332 if (Header == *BB) {
333 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000334 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000335 InsertTop->getTerminator()->setSuccessor(0, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000336 }
Junmo Park502ff662016-01-28 01:23:18 +0000337
Eli Friedman0a217452017-01-18 23:26:37 +0000338 if (DT) {
339 if (Header == *BB) {
340 // The header is dominated by the preheader.
341 DT->addNewBlock(NewBB, InsertTop);
342 } else {
343 // Copy information from original loop to unrolled loop.
344 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
345 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
346 }
347 }
348
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000349 if (Latch == *BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000350 // For the last block, if CreateRemainderLoop is false, create a direct
351 // jump to InsertBot. If not, create a loop back to cloned head.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000352 VMap.erase((*BB)->getTerminator());
353 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
354 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000355 IRBuilder<> Builder(LatchBR);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000356 if (!CreateRemainderLoop) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000357 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000358 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000359 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
360 suffix + ".iter",
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000361 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000362 Value *IdxSub =
363 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
364 NewIdx->getName() + ".sub");
365 Value *IdxCmp =
366 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000367 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000368 NewIdx->addIncoming(NewIter, InsertTop);
369 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000370 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000371 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000372 }
373 }
374
375 // Change the incoming values to the ones defined in the preheader or
376 // cloned loop.
377 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000378 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000379 if (!CreateRemainderLoop) {
380 if (UseEpilogRemainder) {
381 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
382 NewPHI->setIncomingBlock(idx, InsertTop);
383 NewPHI->removeIncomingValue(Latch, false);
384 } else {
385 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
386 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
387 }
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000388 } else {
389 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
390 NewPHI->setIncomingBlock(idx, InsertTop);
391 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
392 idx = NewPHI->getBasicBlockIndex(Latch);
393 Value *InVal = NewPHI->getIncomingValue(idx);
394 NewPHI->setIncomingBlock(idx, NewLatch);
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000395 if (Value *V = VMap.lookup(InVal))
396 NewPHI->setIncomingValue(idx, V);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000397 }
398 }
Florian Hahn5364cf32017-01-31 11:13:44 +0000399 if (CreateRemainderLoop) {
400 Loop *NewLoop = NewLoops[L];
Michael Kruse72448522018-12-12 17:32:52 +0000401 MDNode *LoopID = NewLoop->getLoopID();
Florian Hahn5364cf32017-01-31 11:13:44 +0000402 assert(NewLoop && "L should have been cloned");
Sam Parker7cd826a2017-09-04 08:12:16 +0000403
404 // Only add loop metadata if the loop is not going to be completely
405 // unrolled.
406 if (UnrollRemainder)
407 return NewLoop;
408
Michael Kruse72448522018-12-12 17:32:52 +0000409 Optional<MDNode *> NewLoopID = makeFollowupLoopID(
410 LoopID, {LLVMLoopUnrollFollowupAll, LLVMLoopUnrollFollowupRemainder});
411 if (NewLoopID.hasValue()) {
412 NewLoop->setLoopID(NewLoopID.getValue());
413
414 // Do not setLoopAlreadyUnrolled if loop attributes have been defined
415 // explicitly.
416 return NewLoop;
417 }
418
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000419 // Add unroll disable metadata to disable future unrolling for this loop.
Hongbin Zheng73f65042017-10-15 07:31:02 +0000420 NewLoop->setLoopAlreadyUnrolled();
Anna Thomase5e5e592017-06-30 17:57:07 +0000421 return NewLoop;
Andrew Trickd04d15292011-12-09 06:19:40 +0000422 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000423 else
424 return nullptr;
Andrew Trickd04d15292011-12-09 06:19:40 +0000425}
426
Anna Thomas8e431a92017-07-12 20:55:43 +0000427/// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
428/// is populated with all the loop exit blocks other than the LatchExit block.
429static bool
430canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits,
431 BasicBlock *LatchExit, bool PreserveLCSSA,
432 bool UseEpilogRemainder) {
433
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000434 // We currently have some correctness constrains in unrolling a multi-exit
435 // loop. Check for these below.
436
Anna Thomas8e431a92017-07-12 20:55:43 +0000437 // We rely on LCSSA form being preserved when the exit blocks are transformed.
438 if (!PreserveLCSSA)
439 return false;
440 SmallVector<BasicBlock *, 4> Exits;
441 L->getUniqueExitBlocks(Exits);
442 for (auto *BB : Exits)
443 if (BB != LatchExit)
444 OtherExits.push_back(BB);
445
446 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
447 // UnrollRuntimeMultiExit is true. This will need updating the logic in
448 // connectEpilog/connectProlog.
449 if (!LatchExit->getSinglePredecessor()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000450 LLVM_DEBUG(
451 dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
452 "predecessor.\n");
Anna Thomas8e431a92017-07-12 20:55:43 +0000453 return false;
454 }
455 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
456 // and L is an inner loop. This is because in presence of multiple exits, the
457 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
458 // outer loop. This is automatically handled in the prolog case, so we do not
459 // have that bug in prolog generation.
460 if (UseEpilogRemainder && L->getParentLoop())
461 return false;
462
463 // All constraints have been satisfied.
464 return true;
465}
466
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000467/// Returns true if we can profitably unroll the multi-exit loop L. Currently,
468/// we return true only if UnrollRuntimeMultiExit is set to true.
469static bool canProfitablyUnrollMultiExitLoop(
470 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
471 bool PreserveLCSSA, bool UseEpilogRemainder) {
Anna Thomas8e431a92017-07-12 20:55:43 +0000472
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000473#if !defined(NDEBUG)
474 SmallVector<BasicBlock *, 8> OtherExitsDummyCheck;
475 assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit,
476 PreserveLCSSA, UseEpilogRemainder) &&
477 "Should be safe to unroll before checking profitability!");
478#endif
Anna Thomasf34537d2017-09-15 15:56:05 +0000479
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000480 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
Anna Thomasf34537d2017-09-15 15:56:05 +0000481 if (UnrollRuntimeMultiExit.getNumOccurrences())
482 return UnrollRuntimeMultiExit;
483
484 // The main pain point with multi-exit loop unrolling is that once unrolled,
485 // we will not be able to merge all blocks into a straight line code.
486 // There are branches within the unrolled loop that go to the OtherExits.
487 // The second point is the increase in code size, but this is true
488 // irrespective of multiple exits.
489
490 // Note: Both the heuristics below are coarse grained. We are essentially
491 // enabling unrolling of loops that have a single side exit other than the
492 // normal LatchExit (i.e. exiting into a deoptimize block).
493 // The heuristics considered are:
494 // 1. low number of branches in the unrolled version.
495 // 2. high predictability of these extra branches.
496 // We avoid unrolling loops that have more than two exiting blocks. This
497 // limits the total number of branches in the unrolled loop to be atmost
498 // the unroll factor (since one of the exiting blocks is the latch block).
499 SmallVector<BasicBlock*, 4> ExitingBlocks;
500 L->getExitingBlocks(ExitingBlocks);
501 if (ExitingBlocks.size() > 2)
502 return false;
503
504 // The second heuristic is that L has one exit other than the latchexit and
505 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
506 // taken, which also implies the branch leading to the deoptimize block is
507 // highly predictable.
508 return (OtherExits.size() == 1 &&
509 OtherExits[0]->getTerminatingDeoptimizeCall());
510 // TODO: These can be fine-tuned further to consider code size or deopt states
511 // that are captured by the deoptimize exit block.
512 // Also, we can extend this to support more cases, if we actually
513 // know of kinds of multiexit loops that would benefit from unrolling.
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000514}
Anna Thomas8e431a92017-07-12 20:55:43 +0000515
David L Kreitzer188de5a2016-04-05 12:19:35 +0000516/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000517/// run-time trip-count.
518///
519/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000520/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000521/// to the unroll factor as the number of *extra* copies added).
522/// We assume also that the loop unroll factor is a power-of-two. So, after
523/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000524/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000525/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
526/// the switch instruction is generated.
527///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000528/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000529/// extraiters = tripcount % loopfactor
530/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000531/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000532/// Prol: LoopBody;
533/// extraiters -= 1 // Omitted if unroll factor is 2.
534/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000535/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000536/// Loop:
537/// ...
538/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000539///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000540/// ***Epilog case***
541/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000542/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000543/// unroll_iters = tripcount - extraiters
544/// Loop: LoopBody; (executes unroll_iter times);
545/// unroll_iter -= 1
546/// if (unroll_iter != 0) jump Loop:
547/// LoopExit:
548/// if (extraiters == 0) jump EpilExit:
549/// Epil: LoopBody; (executes extraiters times)
550/// extraiters -= 1 // Omitted if unroll factor is 2.
551/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
552/// EpilExit:
553
554bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
555 bool AllowExpensiveTripCount,
556 bool UseEpilogRemainder,
Michael Kruse72448522018-12-12 17:32:52 +0000557 bool UnrollRemainder, LoopInfo *LI,
558 ScalarEvolution *SE, DominatorTree *DT,
559 AssumptionCache *AC, bool PreserveLCSSA,
560 Loop **ResultLoop) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
562 LLVM_DEBUG(L->dump());
563 LLVM_DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n"
564 : dbgs() << "Using prolog remainder.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000565
Anna Thomase5e5e592017-06-30 17:57:07 +0000566 // Make sure the loop is in canonical form.
Anna Thomasbafe7662017-07-11 20:44:37 +0000567 if (!L->isLoopSimplifyForm()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000568 LLVM_DEBUG(dbgs() << "Not in simplify form!\n");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000569 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000570 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000571
Anna Thomas91eed9a2017-06-23 14:28:01 +0000572 // Guaranteed by LoopSimplifyForm.
573 BasicBlock *Latch = L->getLoopLatch();
Anna Thomase5e5e592017-06-30 17:57:07 +0000574 BasicBlock *Header = L->getHeader();
Anna Thomas91eed9a2017-06-23 14:28:01 +0000575
Anna Thomas91eed9a2017-06-23 14:28:01 +0000576 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
David Green9108c2b2018-09-25 10:08:47 +0000577
578 if (!LatchBR || LatchBR->isUnconditional()) {
579 // The loop-rotate pass can be helpful to avoid this in many cases.
580 LLVM_DEBUG(
581 dbgs()
582 << "Loop latch not terminated by a conditional branch.\n");
583 return false;
584 }
585
Anna Thomas8e431a92017-07-12 20:55:43 +0000586 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
587 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
David Green9108c2b2018-09-25 10:08:47 +0000588
589 if (L->contains(LatchExit)) {
590 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
591 // targets of the Latch be an exit block out of the loop.
592 LLVM_DEBUG(
593 dbgs()
594 << "One of the loop latch successors must be the exit block.\n");
595 return false;
596 }
597
Anna Thomas8e431a92017-07-12 20:55:43 +0000598 // These are exit blocks other than the target of the latch exiting block.
599 SmallVector<BasicBlock *, 4> OtherExits;
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000600 bool isMultiExitUnrollingEnabled =
601 canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
602 UseEpilogRemainder) &&
603 canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
604 UseEpilogRemainder);
Anna Thomas8e431a92017-07-12 20:55:43 +0000605 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
606 if (!isMultiExitUnrollingEnabled &&
607 (!L->getExitingBlock() || OtherExits.size())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000608 LLVM_DEBUG(
Anna Thomas8e431a92017-07-12 20:55:43 +0000609 dbgs()
610 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
611 "enabled!\n");
Anna Thomaseb6d5d12017-07-06 18:39:26 +0000612 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000613 }
Sanjay Patele08381a2016-02-08 19:27:33 +0000614 // Use Scalar Evolution to compute the trip count. This allows more loops to
615 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000616 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000617 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000618
Sanjay Patele08381a2016-02-08 19:27:33 +0000619 // Only unroll loops with a computable trip count, and the trip count needs
620 // to be an int value (allowing a pointer type is a TODO item).
Anna Thomasdc935a62017-06-27 14:14:35 +0000621 // We calculate the backedge count by using getExitCount on the Latch block,
622 // which is proven to be the only exiting block in this loop. This is same as
623 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
624 // exiting blocks).
625 const SCEV *BECountSC = SE->getExitCount(L, Latch);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000626 if (isa<SCEVCouldNotCompute>(BECountSC) ||
Anna Thomasbafe7662017-07-11 20:44:37 +0000627 !BECountSC->getType()->isIntegerTy()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000628 LLVM_DEBUG(dbgs() << "Could not compute exit block SCEV\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000629 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000630 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000631
Sanjoy Das11b279a2015-02-18 19:32:25 +0000632 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000633
Sanjay Patele08381a2016-02-08 19:27:33 +0000634 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000635 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000636 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Anna Thomasbafe7662017-07-11 20:44:37 +0000637 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000638 LLVM_DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000639 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000640 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000641
David L Kreitzer188de5a2016-04-05 12:19:35 +0000642 BasicBlock *PreHeader = L->getLoopPreheader();
643 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000644 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000645 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000646 if (!AllowExpensiveTripCount &&
Anna Thomasbafe7662017-07-11 20:44:37 +0000647 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000648 LLVM_DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
Sanjoy Dase178f462015-04-14 03:20:38 +0000649 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000650 }
Sanjoy Dase178f462015-04-14 03:20:38 +0000651
Sanjoy Das11b279a2015-02-18 19:32:25 +0000652 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000653 // comment on ModVal below.
Anna Thomasbafe7662017-07-11 20:44:37 +0000654 if (Log2_32(Count) > BEWidth) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000655 LLVM_DEBUG(
656 dbgs()
657 << "Count failed constraint on overflow trip count calculation.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000658 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000659 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000660
David L Kreitzer188de5a2016-04-05 12:19:35 +0000661 // Loop structure is the following:
662 //
663 // PreHeader
664 // Header
665 // ...
666 // Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000667 // LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000668
669 BasicBlock *NewPreHeader;
670 BasicBlock *NewExit = nullptr;
671 BasicBlock *PrologExit = nullptr;
672 BasicBlock *EpilogPreHeader = nullptr;
673 BasicBlock *PrologPreHeader = nullptr;
674
675 if (UseEpilogRemainder) {
676 // If epilog remainder
677 // Split PreHeader to insert a branch around loop for unrolling.
678 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
679 NewPreHeader->setName(PreHeader->getName() + ".new");
Anna Thomas91eed9a2017-06-23 14:28:01 +0000680 // Split LatchExit to create phi nodes from branch above.
681 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
Alina Sbirleaab6f84f72018-08-21 23:32:03 +0000682 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa", DT, LI,
683 nullptr, PreserveLCSSA);
Zhaoshi Zheng8af1e1c2017-12-26 23:31:21 +0000684 // NewExit gets its DebugLoc from LatchExit, which is not part of the
685 // original Loop.
686 // Fix this by setting Loop's DebugLoc to NewExit.
687 auto *NewExitTerminator = NewExit->getTerminator();
688 NewExitTerminator->setDebugLoc(Header->getTerminator()->getDebugLoc());
David L Kreitzer188de5a2016-04-05 12:19:35 +0000689 // Split NewExit to insert epilog remainder loop.
Zhaoshi Zheng8af1e1c2017-12-26 23:31:21 +0000690 EpilogPreHeader = SplitBlock(NewExit, NewExitTerminator, DT, LI);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000691 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
692 } else {
693 // If prolog remainder
694 // Split the original preheader twice to insert prolog remainder loop
695 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
696 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
697 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
698 DT, LI);
699 PrologExit->setName(Header->getName() + ".prol.loopexit");
700 // Split PrologExit to get NewPreHeader.
701 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
702 NewPreHeader->setName(PreHeader->getName() + ".new");
703 }
704 // Loop structure should be the following:
705 // Epilog Prolog
706 //
707 // PreHeader PreHeader
708 // *NewPreHeader *PrologPreHeader
709 // Header *PrologExit
710 // ... *NewPreHeader
711 // Latch Header
712 // *NewExit ...
713 // *EpilogPreHeader Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000714 // LatchExit LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000715
716 // Calculate conditions for branch around loop for unrolling
717 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000718 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000719 // extra iterations = run-time trip count % loop unroll factor
720 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000721 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
722 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000723 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
724 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000725 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000726 Value *ModVal;
727 // Calculate ModVal = (BECount + 1) % Count.
728 // Note that TripCount is BECount + 1.
729 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000730 // When Count is power of 2 we don't BECount for epilog case, however we'll
731 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000732 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000733 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000734 // OR
735 // 2. The addition computing TripCount overflowed.
736 //
737 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
738 // the number of iterations that remain to be run in the original loop is a
739 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
740 // explicitly check this above).
741 } else {
742 // As (BECount + 1) can potentially unsigned overflow we count
743 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
744 Value *ModValTmp = B.CreateURem(BECount,
745 ConstantInt::get(BECount->getType(),
746 Count));
747 Value *ModValAdd = B.CreateAdd(ModValTmp,
748 ConstantInt::get(ModValTmp->getType(), 1));
749 // At that point (BECount % Count) + 1 could be equal to Count.
750 // To handle this case we need to take mod by Count one more time.
751 ModVal = B.CreateURem(ModValAdd,
752 ConstantInt::get(BECount->getType(), Count),
753 "xtraiter");
754 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000755 Value *BranchVal =
756 UseEpilogRemainder ? B.CreateICmpULT(BECount,
757 ConstantInt::get(BECount->getType(),
758 Count - 1)) :
759 B.CreateIsNotNull(ModVal, "lcmp.mod");
760 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
761 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000762 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000763 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000764 PreHeaderBR->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000765 if (DT) {
766 if (UseEpilogRemainder)
767 DT->changeImmediateDominator(NewExit, PreHeader);
768 else
769 DT->changeImmediateDominator(PrologExit, PreHeader);
770 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000771 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000772 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000773 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000774 LoopBlocksDFS LoopBlocks(L);
775 LoopBlocks.perform(LI);
776
777 //
778 // For each extra loop iteration, create a copy of the loop's basic blocks
779 // and generate a condition that branches to the copy depending on the
780 // number of 'left over' iterations.
781 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000782 std::vector<BasicBlock *> NewBlocks;
783 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000784
David L Kreitzer188de5a2016-04-05 12:19:35 +0000785 // For unroll factor 2 remainder loop will have 1 iterations.
786 // Do not create 1 iteration loop.
787 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000788
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000789 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
790 // the loop, otherwise we create a cloned loop to execute the extra
791 // iterations. This function adds the appropriate CFG connections.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000792 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000793 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
Anna Thomase5e5e592017-06-30 17:57:07 +0000794 Loop *remainderLoop = CloneLoopBlocks(
Sam Parker718c8a62017-08-14 09:25:26 +0000795 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
796 InsertTop, InsertBot,
Anna Thomase5e5e592017-06-30 17:57:07 +0000797 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000798
David L Kreitzer188de5a2016-04-05 12:19:35 +0000799 // Insert the cloned blocks into the function.
800 F->getBasicBlockList().splice(InsertBot->getIterator(),
801 F->getBasicBlockList(),
802 NewBlocks[0]->getIterator(),
803 F->end());
804
Anna Thomase5e5e592017-06-30 17:57:07 +0000805 // Now the loop blocks are cloned and the other exiting blocks from the
806 // remainder are connected to the original Loop's exit blocks. The remaining
807 // work is to update the phi nodes in the original loop, and take in the
808 // values from the cloned region. Also update the dominator info for
Anna Thomasec9b3262017-07-13 13:21:23 +0000809 // OtherExits and their immediate successors, since we have new edges into
810 // OtherExits.
Florian Hahna1cc8482018-06-12 11:16:56 +0000811 SmallPtrSet<BasicBlock*, 8> ImmediateSuccessorsOfExitBlocks;
Anna Thomase5e5e592017-06-30 17:57:07 +0000812 for (auto *BB : OtherExits) {
813 for (auto &II : *BB) {
814
815 // Given we preserve LCSSA form, we know that the values used outside the
816 // loop will be used through these phi nodes at the exit blocks that are
817 // transformed below.
818 if (!isa<PHINode>(II))
819 break;
820 PHINode *Phi = cast<PHINode>(&II);
821 unsigned oldNumOperands = Phi->getNumIncomingValues();
822 // Add the incoming values from the remainder code to the end of the phi
823 // node.
824 for (unsigned i =0; i < oldNumOperands; i++){
Anna Thomas512dde72017-09-15 13:29:33 +0000825 Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
Anna Thomas70ffd652017-07-10 15:29:38 +0000826 // newVal can be a constant or derived from values outside the loop, and
Anna Thomas512dde72017-09-15 13:29:33 +0000827 // hence need not have a VMap value. Also, since lookup already generated
828 // a default "null" VMap entry for this value, we need to populate that
829 // VMap entry correctly, with the mapped entry being itself.
830 if (!newVal) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000831 newVal = Phi->getIncomingValue(i);
Anna Thomas512dde72017-09-15 13:29:33 +0000832 VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
833 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000834 Phi->addIncoming(newVal,
835 cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
836 }
837 }
Simon Pilgrimf32f4be2017-07-13 17:10:12 +0000838#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
Anna Thomasec9b3262017-07-13 13:21:23 +0000839 for (BasicBlock *SuccBB : successors(BB)) {
840 assert(!(any_of(OtherExits,
841 [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
842 SuccBB == LatchExit) &&
843 "Breaks the definition of dedicated exits!");
844 }
845#endif
Anna Thomase5e5e592017-06-30 17:57:07 +0000846 // Update the dominator info because the immediate dominator is no longer the
847 // header of the original Loop. BB has edges both from L and remainder code.
848 // Since the preheader determines which loop is run (L or directly jump to
849 // the remainder code), we set the immediate dominator as the preheader.
Anna Thomasec9b3262017-07-13 13:21:23 +0000850 if (DT) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000851 DT->changeImmediateDominator(BB, PreHeader);
Anna Thomasec9b3262017-07-13 13:21:23 +0000852 // Also update the IDom for immediate successors of BB. If the current
853 // IDom is the header, update the IDom to be the preheader because that is
854 // the nearest common dominator of all predecessors of SuccBB. We need to
855 // check for IDom being the header because successors of exit blocks can
856 // have edges from outside the loop, and we should not incorrectly update
857 // the IDom in that case.
858 for (BasicBlock *SuccBB: successors(BB))
859 if (ImmediateSuccessorsOfExitBlocks.insert(SuccBB).second) {
860 if (DT->getNode(SuccBB)->getIDom()->getBlock() == Header) {
861 assert(!SuccBB->getSinglePredecessor() &&
862 "BB should be the IDom then!");
863 DT->changeImmediateDominator(SuccBB, PreHeader);
864 }
865 }
866 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000867 }
868
David L Kreitzer188de5a2016-04-05 12:19:35 +0000869 // Loop structure should be the following:
870 // Epilog Prolog
871 //
872 // PreHeader PreHeader
873 // NewPreHeader PrologPreHeader
874 // Header PrologHeader
875 // ... ...
876 // Latch PrologLatch
877 // NewExit PrologExit
878 // EpilogPreHeader NewPreHeader
879 // EpilogHeader Header
880 // ... ...
881 // EpilogLatch Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000882 // LatchExit LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +0000883
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000884 // Rewrite the cloned instruction operands to use the values created when the
885 // clone is created.
886 for (BasicBlock *BB : NewBlocks) {
887 for (Instruction &I : *BB) {
888 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000889 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000890 }
891 }
892
David L Kreitzer188de5a2016-04-05 12:19:35 +0000893 if (UseEpilogRemainder) {
894 // Connect the epilog code to the original loop and update the
895 // PHI functions.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000896 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000897 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
898 PreserveLCSSA);
899
900 // Update counter in loop for unrolling.
901 // I should be multiply of Count.
902 IRBuilder<> B2(NewPreHeader->getTerminator());
903 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
904 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
905 B2.SetInsertPoint(LatchBR);
906 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
907 Header->getFirstNonPHI());
908 Value *IdxSub =
909 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
910 NewIdx->getName() + ".nsub");
911 Value *IdxCmp;
912 if (LatchBR->getSuccessor(0) == Header)
913 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
914 else
915 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
916 NewIdx->addIncoming(TestVal, NewPreHeader);
917 NewIdx->addIncoming(IdxSub, Latch);
918 LatchBR->setCondition(IdxCmp);
919 } else {
920 // Connect the prolog code to the original loop and update the
921 // PHI functions.
Anna Thomas734ab3f2017-07-07 18:05:28 +0000922 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
923 NewPreHeader, VMap, DT, LI, PreserveLCSSA);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000924 }
Wei Mi59ca9662016-08-25 16:17:18 +0000925
Max Kazantsevacda4c02018-04-23 10:39:38 +0000926 // If this loop is nested, then the loop unroller changes the code in the any
927 // of its parent loops, so the Scalar Evolution pass needs to be run again.
928 SE->forgetTopmostLoop(L);
Wei Mi59ca9662016-08-25 16:17:18 +0000929
Anna Thomas0785e732019-01-03 17:44:44 +0000930 // Verify that the Dom Tree is correct.
Anna Thomasa470aa62019-01-03 19:43:33 +0000931#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
Anna Thomas0785e732019-01-03 17:44:44 +0000932 if (DT)
933 assert(DT->verify(DominatorTree::VerificationLevel::Full));
934#endif
935
Anna Thomase5e5e592017-06-30 17:57:07 +0000936 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
937 // cannot rely on the LoopUnrollPass to do this because it only does
938 // canonicalization for parent/subloops and not the sibling loops.
939 if (OtherExits.size() > 0) {
940 // Generate dedicated exit blocks for the original loop, to preserve
941 // LoopSimplifyForm.
942 formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
943 // Generate dedicated exit blocks for the remainder loop if one exists, to
944 // preserve LoopSimplifyForm.
945 if (remainderLoop)
946 formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
947 }
948
Michael Kruse72448522018-12-12 17:32:52 +0000949 auto UnrollResult = LoopUnrollResult::Unmodified;
Sam Parker718c8a62017-08-14 09:25:26 +0000950 if (remainderLoop && UnrollRemainder) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000951 LLVM_DEBUG(dbgs() << "Unrolling remainder loop\n");
Michael Kruse72448522018-12-12 17:32:52 +0000952 UnrollResult =
953 UnrollLoop(remainderLoop, /*Count*/ Count - 1, /*TripCount*/ Count - 1,
954 /*Force*/ false, /*AllowRuntime*/ false,
955 /*AllowExpensiveTripCount*/ false, /*PreserveCondBr*/ true,
956 /*PreserveOnlyFirst*/ false, /*TripMultiple*/ 1,
957 /*PeelCount*/ 0, /*UnrollRemainder*/ false, LI, SE, DT, AC,
958 /*ORE*/ nullptr, PreserveLCSSA);
Sam Parker718c8a62017-08-14 09:25:26 +0000959 }
960
Michael Kruse72448522018-12-12 17:32:52 +0000961 if (ResultLoop && UnrollResult != LoopUnrollResult::FullyUnrolled)
962 *ResultLoop = remainderLoop;
Andrew Trickd04d15292011-12-09 06:19:40 +0000963 NumRuntimeUnrolled++;
964 return true;
965}