blob: c03fa153678a3f33d2bc691b30af96afe1e29942 [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
Andrew Trickd04d15292011-12-09 06:19:40 +000024#include "llvm/ADT/Statistic.h"
Anna Thomasec9b3262017-07-13 13:21:23 +000025#include "llvm/ADT/SmallSet.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"
28#include "llvm/Analysis/LoopPass.h"
29#include "llvm/Analysis/ScalarEvolution.h"
30#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/BasicBlock.h"
Chandler Carruth32c52c72015-01-18 02:39:37 +000032#include "llvm/IR/Dominators.h"
Kevin Qinfc02e3c2014-09-29 11:15:00 +000033#include "llvm/IR/Metadata.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000034#include "llvm/IR/Module.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000035#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000037#include "llvm/Transforms/Scalar.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/Cloning.h"
Anna Thomase5e5e592017-06-30 17:57:07 +000040#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include "llvm/Transforms/Utils/UnrollLoop.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000042#include <algorithm>
43
44using namespace llvm;
45
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "loop-unroll"
47
Jakub Staszak1b1d5232011-12-18 21:52:30 +000048STATISTIC(NumRuntimeUnrolled,
Andrew Trickd04d15292011-12-09 06:19:40 +000049 "Number of loops unrolled with run-time trip counts");
Anna Thomase5e5e592017-06-30 17:57:07 +000050static cl::opt<bool> UnrollRuntimeMultiExit(
51 "unroll-runtime-multi-exit", cl::init(false), cl::Hidden,
52 cl::desc("Allow runtime unrolling for loops with multiple exits, when "
53 "epilog is generated"));
Andrew Trickd04d15292011-12-09 06:19:40 +000054
55/// Connect the unrolling prolog code to the original loop.
56/// The unrolling prolog code contains code to execute the
57/// 'extra' iterations if the run-time trip count modulo the
58/// unroll count is non-zero.
59///
60/// This function performs the following:
61/// - Create PHI nodes at prolog end block to combine values
62/// that exit the prolog code and jump around the prolog.
63/// - Add a PHI operand to a PHI node at the loop exit block
64/// for values that exit the prolog and go around the loop.
65/// - Branch around the original loop if the trip count is less
66/// than the unroll factor.
67///
Sanjoy Das11b279a2015-02-18 19:32:25 +000068static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
Anna Thomas734ab3f2017-07-07 18:05:28 +000069 BasicBlock *PrologExit,
70 BasicBlock *OriginalLoopLatchExit,
71 BasicBlock *PreHeader, BasicBlock *NewPreHeader,
72 ValueToValueMapTy &VMap, DominatorTree *DT,
73 LoopInfo *LI, bool PreserveLCSSA) {
Andrew Trickd04d15292011-12-09 06:19:40 +000074 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000075 assert(Latch && "Loop must have a latch");
David L Kreitzer188de5a2016-04-05 12:19:35 +000076 BasicBlock *PrologLatch = cast<BasicBlock>(VMap[Latch]);
Andrew Trickd04d15292011-12-09 06:19:40 +000077
78 // Create a PHI node for each outgoing value from the original loop
79 // (which means it is an outgoing value from the prolog code too).
80 // The new PHI node is inserted in the prolog end basic block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000081 // The new PHI node value is added as an operand of a PHI node in either
Andrew Trickd04d15292011-12-09 06:19:40 +000082 // the loop header or the loop exit block.
David L Kreitzer188de5a2016-04-05 12:19:35 +000083 for (BasicBlock *Succ : successors(Latch)) {
84 for (Instruction &BBI : *Succ) {
85 PHINode *PN = dyn_cast<PHINode>(&BBI);
86 // Exit when we passed all PHI nodes.
87 if (!PN)
88 break;
Andrew Trickd04d15292011-12-09 06:19:40 +000089 // Add a new PHI node to the prolog end block and add the
90 // appropriate incoming values.
David L Kreitzer188de5a2016-04-05 12:19:35 +000091 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
92 PrologExit->getFirstNonPHI());
Andrew Trickd04d15292011-12-09 06:19:40 +000093 // Adding a value to the new PHI node from the original loop preheader.
94 // This is the value that skips all the prolog code.
95 if (L->contains(PN)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +000096 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader),
97 PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +000098 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +000099 NewPN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
Andrew Trickd04d15292011-12-09 06:19:40 +0000100 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000101
102 Value *V = PN->getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000103 if (Instruction *I = dyn_cast<Instruction>(V)) {
104 if (L->contains(I)) {
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000105 V = VMap.lookup(I);
Andrew Trickd04d15292011-12-09 06:19:40 +0000106 }
107 }
108 // Adding a value to the new PHI node from the last prolog block
109 // that was created.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000110 NewPN->addIncoming(V, PrologLatch);
Andrew Trickd04d15292011-12-09 06:19:40 +0000111
112 // Update the existing PHI node operand with the value from the
113 // new PHI node. How this is done depends on if the existing
114 // PHI node is in the original loop block, or the exit block.
115 if (L->contains(PN)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000116 PN->setIncomingValue(PN->getBasicBlockIndex(NewPreHeader), NewPN);
Andrew Trickd04d15292011-12-09 06:19:40 +0000117 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000118 PN->addIncoming(NewPN, PrologExit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000119 }
120 }
121 }
122
Michael Zolotukhind9b6ad32016-08-02 19:19:31 +0000123 // Make sure that created prolog loop is in simplified form
124 SmallVector<BasicBlock *, 4> PrologExitPreds;
125 Loop *PrologLoop = LI->getLoopFor(PrologLatch);
126 if (PrologLoop) {
127 for (BasicBlock *PredBB : predecessors(PrologExit))
128 if (PrologLoop->contains(PredBB))
129 PrologExitPreds.push_back(PredBB);
130
131 SplitBlockPredecessors(PrologExit, PrologExitPreds, ".unr-lcssa", DT, LI,
132 PreserveLCSSA);
133 }
134
Sanjay Patele08381a2016-02-08 19:27:33 +0000135 // Create a branch around the original loop, which is taken if there are no
Sanjoy Das11b279a2015-02-18 19:32:25 +0000136 // iterations remaining to be executed after running the prologue.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000137 Instruction *InsertPt = PrologExit->getTerminator();
Alexey Samsonovea201992015-06-11 18:25:44 +0000138 IRBuilder<> B(InsertPt);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000139
140 assert(Count != 0 && "nonsensical Count!");
141
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000142 // If BECount <u (Count - 1) then (BECount + 1) % Count == (BECount + 1)
143 // This means %xtraiter is (BECount + 1) and all of the iterations of this
144 // loop were executed by the prologue. Note that if BECount <u (Count - 1)
145 // then (BECount + 1) cannot unsigned-overflow.
Alexey Samsonovea201992015-06-11 18:25:44 +0000146 Value *BrLoopExit =
147 B.CreateICmpULT(BECount, ConstantInt::get(BECount->getType(), Count - 1));
Andrew Trickd04d15292011-12-09 06:19:40 +0000148 // Split the exit to maintain loop canonicalization guarantees
Anna Thomas734ab3f2017-07-07 18:05:28 +0000149 SmallVector<BasicBlock *, 4> Preds(predecessors(OriginalLoopLatchExit));
150 SplitBlockPredecessors(OriginalLoopLatchExit, Preds, ".unr-lcssa", DT, LI,
Justin Bogner843fb202015-12-15 19:40:57 +0000151 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000152 // Add the branch to the exit block (around the unrolled loop)
Anna Thomas734ab3f2017-07-07 18:05:28 +0000153 B.CreateCondBr(BrLoopExit, OriginalLoopLatchExit, NewPreHeader);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000154 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000155 if (DT)
Anna Thomas734ab3f2017-07-07 18:05:28 +0000156 DT->changeImmediateDominator(OriginalLoopLatchExit, PrologExit);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000157}
158
159/// Connect the unrolling epilog code to the original loop.
160/// The unrolling epilog code contains code to execute the
161/// 'extra' iterations if the run-time trip count modulo the
162/// unroll count is non-zero.
163///
164/// This function performs the following:
165/// - Update PHI nodes at the unrolling loop exit and epilog loop exit
166/// - Create PHI nodes at the unrolling loop exit to combine
167/// values that exit the unrolling loop code and jump around it.
168/// - Update PHI operands in the epilog loop by the new PHI nodes
169/// - Branch around the epilog loop if extra iters (ModVal) is zero.
170///
171static void ConnectEpilog(Loop *L, Value *ModVal, BasicBlock *NewExit,
172 BasicBlock *Exit, BasicBlock *PreHeader,
173 BasicBlock *EpilogPreHeader, BasicBlock *NewPreHeader,
174 ValueToValueMapTy &VMap, DominatorTree *DT,
175 LoopInfo *LI, bool PreserveLCSSA) {
176 BasicBlock *Latch = L->getLoopLatch();
177 assert(Latch && "Loop must have a latch");
178 BasicBlock *EpilogLatch = cast<BasicBlock>(VMap[Latch]);
179
180 // Loop structure should be the following:
181 //
182 // PreHeader
183 // NewPreHeader
184 // Header
185 // ...
186 // Latch
187 // NewExit (PN)
188 // EpilogPreHeader
189 // EpilogHeader
190 // ...
191 // EpilogLatch
192 // Exit (EpilogPN)
193
194 // Update PHI nodes at NewExit and Exit.
195 for (Instruction &BBI : *NewExit) {
196 PHINode *PN = dyn_cast<PHINode>(&BBI);
197 // Exit when we passed all PHI nodes.
198 if (!PN)
199 break;
200 // PN should be used in another PHI located in Exit block as
201 // Exit was split by SplitBlockPredecessors into Exit and NewExit
202 // Basicaly it should look like:
203 // NewExit:
204 // PN = PHI [I, Latch]
205 // ...
206 // Exit:
207 // EpilogPN = PHI [PN, EpilogPreHeader]
208 //
209 // There is EpilogPreHeader incoming block instead of NewExit as
210 // NewExit was spilt 1 more time to get EpilogPreHeader.
211 assert(PN->hasOneUse() && "The phi should have 1 use");
212 PHINode *EpilogPN = cast<PHINode> (PN->use_begin()->getUser());
213 assert(EpilogPN->getParent() == Exit && "EpilogPN should be in Exit block");
214
215 // Add incoming PreHeader from branch around the Loop
216 PN->addIncoming(UndefValue::get(PN->getType()), PreHeader);
217
218 Value *V = PN->getIncomingValueForBlock(Latch);
219 Instruction *I = dyn_cast<Instruction>(V);
220 if (I && L->contains(I))
221 // If value comes from an instruction in the loop add VMap value.
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000222 V = VMap.lookup(I);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000223 // For the instruction out of the loop, constant or undefined value
224 // insert value itself.
225 EpilogPN->addIncoming(V, EpilogLatch);
226
227 assert(EpilogPN->getBasicBlockIndex(EpilogPreHeader) >= 0 &&
228 "EpilogPN should have EpilogPreHeader incoming block");
229 // Change EpilogPreHeader incoming block to NewExit.
230 EpilogPN->setIncomingBlock(EpilogPN->getBasicBlockIndex(EpilogPreHeader),
231 NewExit);
232 // Now PHIs should look like:
233 // NewExit:
234 // PN = PHI [I, Latch], [undef, PreHeader]
235 // ...
236 // Exit:
237 // EpilogPN = PHI [PN, NewExit], [VMap[I], EpilogLatch]
238 }
239
240 // Create PHI nodes at NewExit (from the unrolling loop Latch and PreHeader).
241 // Update corresponding PHI nodes in epilog loop.
242 for (BasicBlock *Succ : successors(Latch)) {
243 // Skip this as we already updated phis in exit blocks.
244 if (!L->contains(Succ))
245 continue;
246 for (Instruction &BBI : *Succ) {
247 PHINode *PN = dyn_cast<PHINode>(&BBI);
248 // Exit when we passed all PHI nodes.
249 if (!PN)
250 break;
251 // Add new PHI nodes to the loop exit block and update epilog
252 // PHIs with the new PHI values.
253 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName() + ".unr",
254 NewExit->getFirstNonPHI());
255 // Adding a value to the new PHI node from the unrolling loop preheader.
256 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPreHeader), PreHeader);
257 // Adding a value to the new PHI node from the unrolling loop latch.
258 NewPN->addIncoming(PN->getIncomingValueForBlock(Latch), Latch);
259
260 // Update the existing PHI node operand with the value from the new PHI
261 // node. Corresponding instruction in epilog loop should be PHI.
262 PHINode *VPN = cast<PHINode>(VMap[&BBI]);
263 VPN->setIncomingValue(VPN->getBasicBlockIndex(EpilogPreHeader), NewPN);
264 }
265 }
266
267 Instruction *InsertPt = NewExit->getTerminator();
268 IRBuilder<> B(InsertPt);
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000269 Value *BrLoopExit = B.CreateIsNotNull(ModVal, "lcmp.mod");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000270 assert(Exit && "Loop must have a single exit block only");
Eli Friedman0a217452017-01-18 23:26:37 +0000271 // Split the epilogue exit to maintain loop canonicalization guarantees
David L Kreitzer188de5a2016-04-05 12:19:35 +0000272 SmallVector<BasicBlock*, 4> Preds(predecessors(Exit));
273 SplitBlockPredecessors(Exit, Preds, ".epilog-lcssa", DT, LI,
274 PreserveLCSSA);
275 // Add the branch to the exit block (around the unrolling loop)
276 B.CreateCondBr(BrLoopExit, EpilogPreHeader, Exit);
Andrew Trickd04d15292011-12-09 06:19:40 +0000277 InsertPt->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000278 if (DT)
279 DT->changeImmediateDominator(Exit, NewExit);
280
281 // Split the main loop exit to maintain canonicalization guarantees.
282 SmallVector<BasicBlock*, 4> NewExitPreds{Latch};
283 SplitBlockPredecessors(NewExit, NewExitPreds, ".loopexit", DT, LI,
284 PreserveLCSSA);
Andrew Trickd04d15292011-12-09 06:19:40 +0000285}
286
287/// Create a clone of the blocks in a loop and connect them together.
David L Kreitzer188de5a2016-04-05 12:19:35 +0000288/// If CreateRemainderLoop is false, loop structure will not be cloned,
289/// otherwise a new loop will be created including all cloned blocks, and the
290/// iterator of it switches to count NewIter down to 0.
291/// The cloned blocks should be inserted between InsertTop and InsertBot.
292/// If loop structure is cloned InsertTop should be new preheader, InsertBot
293/// new loop exit.
Anna Thomase5e5e592017-06-30 17:57:07 +0000294/// Return the new cloned loop that is created when CreateRemainderLoop is true.
295static Loop *
296CloneLoopBlocks(Loop *L, Value *NewIter, const bool CreateRemainderLoop,
Sam Parker718c8a62017-08-14 09:25:26 +0000297 const bool UseEpilogRemainder, const bool UnrollRemainder,
298 BasicBlock *InsertTop,
Anna Thomase5e5e592017-06-30 17:57:07 +0000299 BasicBlock *InsertBot, BasicBlock *Preheader,
300 std::vector<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks,
301 ValueToValueMapTy &VMap, DominatorTree *DT, LoopInfo *LI) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000302 StringRef suffix = UseEpilogRemainder ? "epil" : "prol";
Andrew Trickd04d15292011-12-09 06:19:40 +0000303 BasicBlock *Header = L->getHeader();
304 BasicBlock *Latch = L->getLoopLatch();
305 Function *F = Header->getParent();
306 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
307 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000308 Loop *ParentLoop = L->getParentLoop();
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000309 NewLoopsMap NewLoops;
Florian Hahn5364cf32017-01-31 11:13:44 +0000310 NewLoops[ParentLoop] = ParentLoop;
311 if (!CreateRemainderLoop)
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000312 NewLoops[L] = ParentLoop;
313
Andrew Trickd04d15292011-12-09 06:19:40 +0000314 // For each block in the original loop, create a new copy,
315 // and update the value map with the newly created values.
316 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000317 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, "." + suffix, F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000318 NewBlocks.push_back(NewBB);
Florian Hahn5364cf32017-01-31 11:13:44 +0000319
Michael Kuperstein5dd55e82017-01-26 01:04:11 +0000320 // If we're unrolling the outermost loop, there's no remainder loop,
321 // and this block isn't in a nested loop, then the new block is not
322 // in any loop. Otherwise, add it to loopinfo.
323 if (CreateRemainderLoop || LI->getLoopFor(*BB) != L || ParentLoop)
Florian Hahn4f9d6d52017-01-10 23:43:35 +0000324 addClonedBlockToLoopInfo(*BB, NewBB, LI, NewLoops);
Andrew Trickd04d15292011-12-09 06:19:40 +0000325
326 VMap[*BB] = NewBB;
327 if (Header == *BB) {
328 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000329 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000330 InsertTop->getTerminator()->setSuccessor(0, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000331 }
Junmo Park502ff662016-01-28 01:23:18 +0000332
Eli Friedman0a217452017-01-18 23:26:37 +0000333 if (DT) {
334 if (Header == *BB) {
335 // The header is dominated by the preheader.
336 DT->addNewBlock(NewBB, InsertTop);
337 } else {
338 // Copy information from original loop to unrolled loop.
339 BasicBlock *IDomBB = DT->getNode(*BB)->getIDom()->getBlock();
340 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDomBB]));
341 }
342 }
343
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000344 if (Latch == *BB) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000345 // For the last block, if CreateRemainderLoop is false, create a direct
346 // jump to InsertBot. If not, create a loop back to cloned head.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000347 VMap.erase((*BB)->getTerminator());
348 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
349 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
Alexey Samsonovea201992015-06-11 18:25:44 +0000350 IRBuilder<> Builder(LatchBR);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000351 if (!CreateRemainderLoop) {
Alexey Samsonovea201992015-06-11 18:25:44 +0000352 Builder.CreateBr(InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000353 } else {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000354 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2,
355 suffix + ".iter",
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000356 FirstLoopBB->getFirstNonPHI());
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000357 Value *IdxSub =
358 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
359 NewIdx->getName() + ".sub");
360 Value *IdxCmp =
361 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
Alexey Samsonovea201992015-06-11 18:25:44 +0000362 Builder.CreateCondBr(IdxCmp, FirstLoopBB, InsertBot);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000363 NewIdx->addIncoming(NewIter, InsertTop);
364 NewIdx->addIncoming(IdxSub, NewBB);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000365 }
Alexey Samsonovea201992015-06-11 18:25:44 +0000366 LatchBR->eraseFromParent();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000367 }
368 }
369
370 // Change the incoming values to the ones defined in the preheader or
371 // cloned loop.
372 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000373 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000374 if (!CreateRemainderLoop) {
375 if (UseEpilogRemainder) {
376 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
377 NewPHI->setIncomingBlock(idx, InsertTop);
378 NewPHI->removeIncomingValue(Latch, false);
379 } else {
380 VMap[&*I] = NewPHI->getIncomingValueForBlock(Preheader);
381 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
382 }
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000383 } else {
384 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
385 NewPHI->setIncomingBlock(idx, InsertTop);
386 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
387 idx = NewPHI->getBasicBlockIndex(Latch);
388 Value *InVal = NewPHI->getIncomingValue(idx);
389 NewPHI->setIncomingBlock(idx, NewLatch);
Duncan P. N. Exon Smitha71301b2016-04-17 19:26:49 +0000390 if (Value *V = VMap.lookup(InVal))
391 NewPHI->setIncomingValue(idx, V);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000392 }
393 }
Florian Hahn5364cf32017-01-31 11:13:44 +0000394 if (CreateRemainderLoop) {
395 Loop *NewLoop = NewLoops[L];
396 assert(NewLoop && "L should have been cloned");
Sam Parker7cd826a2017-09-04 08:12:16 +0000397
398 // Only add loop metadata if the loop is not going to be completely
399 // unrolled.
400 if (UnrollRemainder)
401 return NewLoop;
402
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000403 // Add unroll disable metadata to disable future unrolling for this loop.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000404 SmallVector<Metadata *, 4> MDs;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000405 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000406 MDs.push_back(nullptr);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000407 MDNode *LoopID = NewLoop->getLoopID();
408 if (LoopID) {
409 // First remove any existing loop unrolling metadata.
410 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
411 bool IsUnrollMetadata = false;
412 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
413 if (MD) {
414 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
415 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
Andrew Trickd04d15292011-12-09 06:19:40 +0000416 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000417 if (!IsUnrollMetadata)
418 MDs.push_back(LoopID->getOperand(i));
Andrew Trickd04d15292011-12-09 06:19:40 +0000419 }
420 }
421
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000422 LLVMContext &Context = NewLoop->getHeader()->getContext();
Sam Parker7cd826a2017-09-04 08:12:16 +0000423 SmallVector<Metadata *, 1> DisableOperands;
424 DisableOperands.push_back(MDString::get(Context,
425 "llvm.loop.unroll.disable"));
426 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
427 MDs.push_back(DisableNode);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000428
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000429 MDNode *NewLoopID = MDNode::get(Context, MDs);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000430 // Set operand 0 to refer to the loop id itself.
431 NewLoopID->replaceOperandWith(0, NewLoopID);
432 NewLoop->setLoopID(NewLoopID);
Anna Thomase5e5e592017-06-30 17:57:07 +0000433 return NewLoop;
Andrew Trickd04d15292011-12-09 06:19:40 +0000434 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000435 else
436 return nullptr;
Andrew Trickd04d15292011-12-09 06:19:40 +0000437}
438
Anna Thomas8e431a92017-07-12 20:55:43 +0000439/// Returns true if we can safely unroll a multi-exit/exiting loop. OtherExits
440/// is populated with all the loop exit blocks other than the LatchExit block.
441static bool
442canSafelyUnrollMultiExitLoop(Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits,
443 BasicBlock *LatchExit, bool PreserveLCSSA,
444 bool UseEpilogRemainder) {
445
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000446 // We currently have some correctness constrains in unrolling a multi-exit
447 // loop. Check for these below.
448
Anna Thomas8e431a92017-07-12 20:55:43 +0000449 // We rely on LCSSA form being preserved when the exit blocks are transformed.
450 if (!PreserveLCSSA)
451 return false;
452 SmallVector<BasicBlock *, 4> Exits;
453 L->getUniqueExitBlocks(Exits);
454 for (auto *BB : Exits)
455 if (BB != LatchExit)
456 OtherExits.push_back(BB);
457
458 // TODO: Support multiple exiting blocks jumping to the `LatchExit` when
459 // UnrollRuntimeMultiExit is true. This will need updating the logic in
460 // connectEpilog/connectProlog.
461 if (!LatchExit->getSinglePredecessor()) {
462 DEBUG(dbgs() << "Bailout for multi-exit handling when latch exit has >1 "
463 "predecessor.\n");
464 return false;
465 }
466 // FIXME: We bail out of multi-exit unrolling when epilog loop is generated
467 // and L is an inner loop. This is because in presence of multiple exits, the
468 // outer loop is incorrect: we do not add the EpilogPreheader and exit to the
469 // outer loop. This is automatically handled in the prolog case, so we do not
470 // have that bug in prolog generation.
471 if (UseEpilogRemainder && L->getParentLoop())
472 return false;
473
474 // All constraints have been satisfied.
475 return true;
476}
477
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000478/// Returns true if we can profitably unroll the multi-exit loop L. Currently,
479/// we return true only if UnrollRuntimeMultiExit is set to true.
480static bool canProfitablyUnrollMultiExitLoop(
481 Loop *L, SmallVectorImpl<BasicBlock *> &OtherExits, BasicBlock *LatchExit,
482 bool PreserveLCSSA, bool UseEpilogRemainder) {
Anna Thomas8e431a92017-07-12 20:55:43 +0000483
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000484#if !defined(NDEBUG)
485 SmallVector<BasicBlock *, 8> OtherExitsDummyCheck;
486 assert(canSafelyUnrollMultiExitLoop(L, OtherExitsDummyCheck, LatchExit,
487 PreserveLCSSA, UseEpilogRemainder) &&
488 "Should be safe to unroll before checking profitability!");
489#endif
490 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
491 return UnrollRuntimeMultiExit.getNumOccurrences() ? UnrollRuntimeMultiExit
492 : false;
493}
Anna Thomas8e431a92017-07-12 20:55:43 +0000494
David L Kreitzer188de5a2016-04-05 12:19:35 +0000495/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000496/// run-time trip-count.
497///
498/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000499/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000500/// to the unroll factor as the number of *extra* copies added).
501/// We assume also that the loop unroll factor is a power-of-two. So, after
502/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000503/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000504/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
505/// the switch instruction is generated.
506///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000507/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000508/// extraiters = tripcount % loopfactor
509/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000510/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000511/// Prol: LoopBody;
512/// extraiters -= 1 // Omitted if unroll factor is 2.
513/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000514/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000515/// Loop:
516/// ...
517/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000518///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000519/// ***Epilog case***
520/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000521/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000522/// unroll_iters = tripcount - extraiters
523/// Loop: LoopBody; (executes unroll_iter times);
524/// unroll_iter -= 1
525/// if (unroll_iter != 0) jump Loop:
526/// LoopExit:
527/// if (extraiters == 0) jump EpilExit:
528/// Epil: LoopBody; (executes extraiters times)
529/// extraiters -= 1 // Omitted if unroll factor is 2.
530/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
531/// EpilExit:
532
533bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
534 bool AllowExpensiveTripCount,
535 bool UseEpilogRemainder,
Sam Parker718c8a62017-08-14 09:25:26 +0000536 bool UnrollRemainder,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000537 LoopInfo *LI, ScalarEvolution *SE,
Sam Parker718c8a62017-08-14 09:25:26 +0000538 DominatorTree *DT, AssumptionCache *AC,
539 OptimizationRemarkEmitter *ORE,
540 bool PreserveLCSSA) {
Anna Thomasbafe7662017-07-11 20:44:37 +0000541 DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
542 DEBUG(L->dump());
Sam Parker7cd826a2017-09-04 08:12:16 +0000543 DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n" :
544 dbgs() << "Using prolog remainder.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000545
Anna Thomase5e5e592017-06-30 17:57:07 +0000546 // Make sure the loop is in canonical form.
Anna Thomasbafe7662017-07-11 20:44:37 +0000547 if (!L->isLoopSimplifyForm()) {
548 DEBUG(dbgs() << "Not in simplify form!\n");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000549 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000550 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000551
Anna Thomas91eed9a2017-06-23 14:28:01 +0000552 // Guaranteed by LoopSimplifyForm.
553 BasicBlock *Latch = L->getLoopLatch();
Anna Thomase5e5e592017-06-30 17:57:07 +0000554 BasicBlock *Header = L->getHeader();
Anna Thomas91eed9a2017-06-23 14:28:01 +0000555
Anna Thomas91eed9a2017-06-23 14:28:01 +0000556 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
Anna Thomas8e431a92017-07-12 20:55:43 +0000557 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
558 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
Anna Thomase5e5e592017-06-30 17:57:07 +0000559 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
560 // targets of the Latch be an exit block out of the loop. This needs
561 // to be guaranteed by the callers of UnrollRuntimeLoopRemainder.
Anna Thomas8e431a92017-07-12 20:55:43 +0000562 assert(!L->contains(LatchExit) &&
Anna Thomase5e5e592017-06-30 17:57:07 +0000563 "one of the loop latch successors should be the exit block!");
Anna Thomas8e431a92017-07-12 20:55:43 +0000564 // These are exit blocks other than the target of the latch exiting block.
565 SmallVector<BasicBlock *, 4> OtherExits;
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000566 bool isMultiExitUnrollingEnabled =
567 canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
568 UseEpilogRemainder) &&
569 canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
570 UseEpilogRemainder);
Anna Thomas8e431a92017-07-12 20:55:43 +0000571 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
572 if (!isMultiExitUnrollingEnabled &&
573 (!L->getExitingBlock() || OtherExits.size())) {
574 DEBUG(
575 dbgs()
576 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
577 "enabled!\n");
Anna Thomaseb6d5d12017-07-06 18:39:26 +0000578 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000579 }
Sanjay Patele08381a2016-02-08 19:27:33 +0000580 // Use Scalar Evolution to compute the trip count. This allows more loops to
581 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000582 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000583 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000584
Sanjay Patele08381a2016-02-08 19:27:33 +0000585 // Only unroll loops with a computable trip count, and the trip count needs
586 // to be an int value (allowing a pointer type is a TODO item).
Anna Thomasdc935a62017-06-27 14:14:35 +0000587 // We calculate the backedge count by using getExitCount on the Latch block,
588 // which is proven to be the only exiting block in this loop. This is same as
589 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
590 // exiting blocks).
591 const SCEV *BECountSC = SE->getExitCount(L, Latch);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000592 if (isa<SCEVCouldNotCompute>(BECountSC) ||
Anna Thomasbafe7662017-07-11 20:44:37 +0000593 !BECountSC->getType()->isIntegerTy()) {
594 DEBUG(dbgs() << "Could not compute exit block SCEV\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000595 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000596 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000597
Sanjoy Das11b279a2015-02-18 19:32:25 +0000598 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000599
Sanjay Patele08381a2016-02-08 19:27:33 +0000600 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000601 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000602 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Anna Thomasbafe7662017-07-11 20:44:37 +0000603 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
604 DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000605 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000606 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000607
David L Kreitzer188de5a2016-04-05 12:19:35 +0000608 BasicBlock *PreHeader = L->getLoopPreheader();
609 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000610 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000611 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000612 if (!AllowExpensiveTripCount &&
Anna Thomasbafe7662017-07-11 20:44:37 +0000613 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
614 DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
Sanjoy Dase178f462015-04-14 03:20:38 +0000615 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000616 }
Sanjoy Dase178f462015-04-14 03:20:38 +0000617
Sanjoy Das11b279a2015-02-18 19:32:25 +0000618 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000619 // comment on ModVal below.
Anna Thomasbafe7662017-07-11 20:44:37 +0000620 if (Log2_32(Count) > BEWidth) {
621 DEBUG(dbgs()
622 << "Count failed constraint on overflow trip count calculation.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000623 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000624 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000625
David L Kreitzer188de5a2016-04-05 12:19:35 +0000626 // Loop structure is the following:
627 //
628 // PreHeader
629 // Header
630 // ...
631 // Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000632 // LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000633
634 BasicBlock *NewPreHeader;
635 BasicBlock *NewExit = nullptr;
636 BasicBlock *PrologExit = nullptr;
637 BasicBlock *EpilogPreHeader = nullptr;
638 BasicBlock *PrologPreHeader = nullptr;
639
640 if (UseEpilogRemainder) {
641 // If epilog remainder
642 // Split PreHeader to insert a branch around loop for unrolling.
643 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
644 NewPreHeader->setName(PreHeader->getName() + ".new");
Anna Thomas91eed9a2017-06-23 14:28:01 +0000645 // Split LatchExit to create phi nodes from branch above.
646 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
647 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000648 DT, LI, PreserveLCSSA);
649 // Split NewExit to insert epilog remainder loop.
650 EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
651 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
652 } else {
653 // If prolog remainder
654 // Split the original preheader twice to insert prolog remainder loop
655 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
656 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
657 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
658 DT, LI);
659 PrologExit->setName(Header->getName() + ".prol.loopexit");
660 // Split PrologExit to get NewPreHeader.
661 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
662 NewPreHeader->setName(PreHeader->getName() + ".new");
663 }
664 // Loop structure should be the following:
665 // Epilog Prolog
666 //
667 // PreHeader PreHeader
668 // *NewPreHeader *PrologPreHeader
669 // Header *PrologExit
670 // ... *NewPreHeader
671 // Latch Header
672 // *NewExit ...
673 // *EpilogPreHeader Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000674 // LatchExit LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000675
676 // Calculate conditions for branch around loop for unrolling
677 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000678 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000679 // extra iterations = run-time trip count % loop unroll factor
680 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000681 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
682 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000683 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
684 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000685 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000686 Value *ModVal;
687 // Calculate ModVal = (BECount + 1) % Count.
688 // Note that TripCount is BECount + 1.
689 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000690 // When Count is power of 2 we don't BECount for epilog case, however we'll
691 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000692 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000693 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000694 // OR
695 // 2. The addition computing TripCount overflowed.
696 //
697 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
698 // the number of iterations that remain to be run in the original loop is a
699 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
700 // explicitly check this above).
701 } else {
702 // As (BECount + 1) can potentially unsigned overflow we count
703 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
704 Value *ModValTmp = B.CreateURem(BECount,
705 ConstantInt::get(BECount->getType(),
706 Count));
707 Value *ModValAdd = B.CreateAdd(ModValTmp,
708 ConstantInt::get(ModValTmp->getType(), 1));
709 // At that point (BECount % Count) + 1 could be equal to Count.
710 // To handle this case we need to take mod by Count one more time.
711 ModVal = B.CreateURem(ModValAdd,
712 ConstantInt::get(BECount->getType(), Count),
713 "xtraiter");
714 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000715 Value *BranchVal =
716 UseEpilogRemainder ? B.CreateICmpULT(BECount,
717 ConstantInt::get(BECount->getType(),
718 Count - 1)) :
719 B.CreateIsNotNull(ModVal, "lcmp.mod");
720 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
721 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000722 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000723 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000724 PreHeaderBR->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000725 if (DT) {
726 if (UseEpilogRemainder)
727 DT->changeImmediateDominator(NewExit, PreHeader);
728 else
729 DT->changeImmediateDominator(PrologExit, PreHeader);
730 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000731 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000732 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000733 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000734 LoopBlocksDFS LoopBlocks(L);
735 LoopBlocks.perform(LI);
736
737 //
738 // For each extra loop iteration, create a copy of the loop's basic blocks
739 // and generate a condition that branches to the copy depending on the
740 // number of 'left over' iterations.
741 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000742 std::vector<BasicBlock *> NewBlocks;
743 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000744
David L Kreitzer188de5a2016-04-05 12:19:35 +0000745 // For unroll factor 2 remainder loop will have 1 iterations.
746 // Do not create 1 iteration loop.
747 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000748
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000749 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
750 // the loop, otherwise we create a cloned loop to execute the extra
751 // iterations. This function adds the appropriate CFG connections.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000752 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000753 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
Anna Thomase5e5e592017-06-30 17:57:07 +0000754 Loop *remainderLoop = CloneLoopBlocks(
Sam Parker718c8a62017-08-14 09:25:26 +0000755 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
756 InsertTop, InsertBot,
Anna Thomase5e5e592017-06-30 17:57:07 +0000757 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000758
David L Kreitzer188de5a2016-04-05 12:19:35 +0000759 // Insert the cloned blocks into the function.
760 F->getBasicBlockList().splice(InsertBot->getIterator(),
761 F->getBasicBlockList(),
762 NewBlocks[0]->getIterator(),
763 F->end());
764
Anna Thomase5e5e592017-06-30 17:57:07 +0000765 // Now the loop blocks are cloned and the other exiting blocks from the
766 // remainder are connected to the original Loop's exit blocks. The remaining
767 // work is to update the phi nodes in the original loop, and take in the
768 // values from the cloned region. Also update the dominator info for
Anna Thomasec9b3262017-07-13 13:21:23 +0000769 // OtherExits and their immediate successors, since we have new edges into
770 // OtherExits.
771 SmallSet<BasicBlock*, 8> ImmediateSuccessorsOfExitBlocks;
Anna Thomase5e5e592017-06-30 17:57:07 +0000772 for (auto *BB : OtherExits) {
773 for (auto &II : *BB) {
774
775 // Given we preserve LCSSA form, we know that the values used outside the
776 // loop will be used through these phi nodes at the exit blocks that are
777 // transformed below.
778 if (!isa<PHINode>(II))
779 break;
780 PHINode *Phi = cast<PHINode>(&II);
781 unsigned oldNumOperands = Phi->getNumIncomingValues();
782 // Add the incoming values from the remainder code to the end of the phi
783 // node.
784 for (unsigned i =0; i < oldNumOperands; i++){
Anna Thomas512dde72017-09-15 13:29:33 +0000785 Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
Anna Thomas70ffd652017-07-10 15:29:38 +0000786 // newVal can be a constant or derived from values outside the loop, and
Anna Thomas512dde72017-09-15 13:29:33 +0000787 // hence need not have a VMap value. Also, since lookup already generated
788 // a default "null" VMap entry for this value, we need to populate that
789 // VMap entry correctly, with the mapped entry being itself.
790 if (!newVal) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000791 newVal = Phi->getIncomingValue(i);
Anna Thomas512dde72017-09-15 13:29:33 +0000792 VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
793 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000794 Phi->addIncoming(newVal,
795 cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
796 }
797 }
Simon Pilgrimf32f4be2017-07-13 17:10:12 +0000798#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
Anna Thomasec9b3262017-07-13 13:21:23 +0000799 for (BasicBlock *SuccBB : successors(BB)) {
800 assert(!(any_of(OtherExits,
801 [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
802 SuccBB == LatchExit) &&
803 "Breaks the definition of dedicated exits!");
804 }
805#endif
Anna Thomase5e5e592017-06-30 17:57:07 +0000806 // Update the dominator info because the immediate dominator is no longer the
807 // header of the original Loop. BB has edges both from L and remainder code.
808 // Since the preheader determines which loop is run (L or directly jump to
809 // the remainder code), we set the immediate dominator as the preheader.
Anna Thomasec9b3262017-07-13 13:21:23 +0000810 if (DT) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000811 DT->changeImmediateDominator(BB, PreHeader);
Anna Thomasec9b3262017-07-13 13:21:23 +0000812 // Also update the IDom for immediate successors of BB. If the current
813 // IDom is the header, update the IDom to be the preheader because that is
814 // the nearest common dominator of all predecessors of SuccBB. We need to
815 // check for IDom being the header because successors of exit blocks can
816 // have edges from outside the loop, and we should not incorrectly update
817 // the IDom in that case.
818 for (BasicBlock *SuccBB: successors(BB))
819 if (ImmediateSuccessorsOfExitBlocks.insert(SuccBB).second) {
820 if (DT->getNode(SuccBB)->getIDom()->getBlock() == Header) {
821 assert(!SuccBB->getSinglePredecessor() &&
822 "BB should be the IDom then!");
823 DT->changeImmediateDominator(SuccBB, PreHeader);
824 }
825 }
826 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000827 }
828
David L Kreitzer188de5a2016-04-05 12:19:35 +0000829 // Loop structure should be the following:
830 // Epilog Prolog
831 //
832 // PreHeader PreHeader
833 // NewPreHeader PrologPreHeader
834 // Header PrologHeader
835 // ... ...
836 // Latch PrologLatch
837 // NewExit PrologExit
838 // EpilogPreHeader NewPreHeader
839 // EpilogHeader Header
840 // ... ...
841 // EpilogLatch Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000842 // LatchExit LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +0000843
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000844 // Rewrite the cloned instruction operands to use the values created when the
845 // clone is created.
846 for (BasicBlock *BB : NewBlocks) {
847 for (Instruction &I : *BB) {
848 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000849 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000850 }
851 }
852
David L Kreitzer188de5a2016-04-05 12:19:35 +0000853 if (UseEpilogRemainder) {
854 // Connect the epilog code to the original loop and update the
855 // PHI functions.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000856 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000857 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
858 PreserveLCSSA);
859
860 // Update counter in loop for unrolling.
861 // I should be multiply of Count.
862 IRBuilder<> B2(NewPreHeader->getTerminator());
863 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
864 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
865 B2.SetInsertPoint(LatchBR);
866 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
867 Header->getFirstNonPHI());
868 Value *IdxSub =
869 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
870 NewIdx->getName() + ".nsub");
871 Value *IdxCmp;
872 if (LatchBR->getSuccessor(0) == Header)
873 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
874 else
875 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
876 NewIdx->addIncoming(TestVal, NewPreHeader);
877 NewIdx->addIncoming(IdxSub, Latch);
878 LatchBR->setCondition(IdxCmp);
879 } else {
880 // Connect the prolog code to the original loop and update the
881 // PHI functions.
Anna Thomas734ab3f2017-07-07 18:05:28 +0000882 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
883 NewPreHeader, VMap, DT, LI, PreserveLCSSA);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000884 }
Wei Mi59ca9662016-08-25 16:17:18 +0000885
886 // If this loop is nested, then the loop unroller changes the code in the
887 // parent loop, so the Scalar Evolution pass needs to be run again.
888 if (Loop *ParentLoop = L->getParentLoop())
889 SE->forgetLoop(ParentLoop);
890
Anna Thomase5e5e592017-06-30 17:57:07 +0000891 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
892 // cannot rely on the LoopUnrollPass to do this because it only does
893 // canonicalization for parent/subloops and not the sibling loops.
894 if (OtherExits.size() > 0) {
895 // Generate dedicated exit blocks for the original loop, to preserve
896 // LoopSimplifyForm.
897 formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
898 // Generate dedicated exit blocks for the remainder loop if one exists, to
899 // preserve LoopSimplifyForm.
900 if (remainderLoop)
901 formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
902 }
903
Sam Parker718c8a62017-08-14 09:25:26 +0000904 if (remainderLoop && UnrollRemainder) {
Sam Parker7cd826a2017-09-04 08:12:16 +0000905 DEBUG(dbgs() << "Unrolling remainder loop\n");
Sam Parker718c8a62017-08-14 09:25:26 +0000906 UnrollLoop(remainderLoop, /*Count*/Count - 1, /*TripCount*/Count - 1,
907 /*Force*/false, /*AllowRuntime*/false,
908 /*AllowExpensiveTripCount*/false, /*PreserveCondBr*/true,
909 /*PreserveOnlyFirst*/false, /*TripMultiple*/1,
910 /*PeelCount*/0, /*UnrollRemainder*/false, LI, SE, DT, AC, ORE,
911 PreserveLCSSA);
912 }
913
Andrew Trickd04d15292011-12-09 06:19:40 +0000914 NumRuntimeUnrolled++;
915 return true;
916}