blob: 1ff3811e23648a8fb537b6bc51af862d14fa9e3d [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
Anna Thomasf34537d2017-09-15 15:56:05 +0000490
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000491 // Priority goes to UnrollRuntimeMultiExit if it's supplied.
Anna Thomasf34537d2017-09-15 15:56:05 +0000492 if (UnrollRuntimeMultiExit.getNumOccurrences())
493 return UnrollRuntimeMultiExit;
494
495 // The main pain point with multi-exit loop unrolling is that once unrolled,
496 // we will not be able to merge all blocks into a straight line code.
497 // There are branches within the unrolled loop that go to the OtherExits.
498 // The second point is the increase in code size, but this is true
499 // irrespective of multiple exits.
500
501 // Note: Both the heuristics below are coarse grained. We are essentially
502 // enabling unrolling of loops that have a single side exit other than the
503 // normal LatchExit (i.e. exiting into a deoptimize block).
504 // The heuristics considered are:
505 // 1. low number of branches in the unrolled version.
506 // 2. high predictability of these extra branches.
507 // We avoid unrolling loops that have more than two exiting blocks. This
508 // limits the total number of branches in the unrolled loop to be atmost
509 // the unroll factor (since one of the exiting blocks is the latch block).
510 SmallVector<BasicBlock*, 4> ExitingBlocks;
511 L->getExitingBlocks(ExitingBlocks);
512 if (ExitingBlocks.size() > 2)
513 return false;
514
515 // The second heuristic is that L has one exit other than the latchexit and
516 // that exit is a deoptimize block. We know that deoptimize blocks are rarely
517 // taken, which also implies the branch leading to the deoptimize block is
518 // highly predictable.
519 return (OtherExits.size() == 1 &&
520 OtherExits[0]->getTerminatingDeoptimizeCall());
521 // TODO: These can be fine-tuned further to consider code size or deopt states
522 // that are captured by the deoptimize exit block.
523 // Also, we can extend this to support more cases, if we actually
524 // know of kinds of multiexit loops that would benefit from unrolling.
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000525}
Anna Thomas8e431a92017-07-12 20:55:43 +0000526
David L Kreitzer188de5a2016-04-05 12:19:35 +0000527/// Insert code in the prolog/epilog code when unrolling a loop with a
Andrew Trickd04d15292011-12-09 06:19:40 +0000528/// run-time trip-count.
529///
530/// This method assumes that the loop unroll factor is total number
Justin Lebar6086c6a2016-02-12 21:01:37 +0000531/// of loop bodies in the loop after unrolling. (Some folks refer
Andrew Trickd04d15292011-12-09 06:19:40 +0000532/// to the unroll factor as the number of *extra* copies added).
533/// We assume also that the loop unroll factor is a power-of-two. So, after
534/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000535/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000536/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
537/// the switch instruction is generated.
538///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000539/// ***Prolog case***
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000540/// extraiters = tripcount % loopfactor
541/// if (extraiters == 0) jump Loop:
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000542/// else jump Prol:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000543/// Prol: LoopBody;
544/// extraiters -= 1 // Omitted if unroll factor is 2.
545/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
Evgeny Stupachenko87880482016-04-08 20:20:38 +0000546/// if (tripcount < loopfactor) jump End:
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000547/// Loop:
548/// ...
549/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000550///
David L Kreitzer188de5a2016-04-05 12:19:35 +0000551/// ***Epilog case***
552/// extraiters = tripcount % loopfactor
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000553/// if (tripcount < loopfactor) jump LoopExit:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000554/// unroll_iters = tripcount - extraiters
555/// Loop: LoopBody; (executes unroll_iter times);
556/// unroll_iter -= 1
557/// if (unroll_iter != 0) jump Loop:
558/// LoopExit:
559/// if (extraiters == 0) jump EpilExit:
560/// Epil: LoopBody; (executes extraiters times)
561/// extraiters -= 1 // Omitted if unroll factor is 2.
562/// if (extraiters != 0) jump Epil: // Omitted if unroll factor is 2.
563/// EpilExit:
564
565bool llvm::UnrollRuntimeLoopRemainder(Loop *L, unsigned Count,
566 bool AllowExpensiveTripCount,
567 bool UseEpilogRemainder,
Sam Parker718c8a62017-08-14 09:25:26 +0000568 bool UnrollRemainder,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000569 LoopInfo *LI, ScalarEvolution *SE,
Sam Parker718c8a62017-08-14 09:25:26 +0000570 DominatorTree *DT, AssumptionCache *AC,
571 OptimizationRemarkEmitter *ORE,
572 bool PreserveLCSSA) {
Anna Thomasbafe7662017-07-11 20:44:37 +0000573 DEBUG(dbgs() << "Trying runtime unrolling on Loop: \n");
574 DEBUG(L->dump());
Sam Parker7cd826a2017-09-04 08:12:16 +0000575 DEBUG(UseEpilogRemainder ? dbgs() << "Using epilog remainder.\n" :
576 dbgs() << "Using prolog remainder.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000577
Anna Thomase5e5e592017-06-30 17:57:07 +0000578 // Make sure the loop is in canonical form.
Anna Thomasbafe7662017-07-11 20:44:37 +0000579 if (!L->isLoopSimplifyForm()) {
580 DEBUG(dbgs() << "Not in simplify form!\n");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000581 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000582 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000583
Anna Thomas91eed9a2017-06-23 14:28:01 +0000584 // Guaranteed by LoopSimplifyForm.
585 BasicBlock *Latch = L->getLoopLatch();
Anna Thomase5e5e592017-06-30 17:57:07 +0000586 BasicBlock *Header = L->getHeader();
Anna Thomas91eed9a2017-06-23 14:28:01 +0000587
Anna Thomas91eed9a2017-06-23 14:28:01 +0000588 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
Anna Thomas8e431a92017-07-12 20:55:43 +0000589 unsigned ExitIndex = LatchBR->getSuccessor(0) == Header ? 1 : 0;
590 BasicBlock *LatchExit = LatchBR->getSuccessor(ExitIndex);
Anna Thomase5e5e592017-06-30 17:57:07 +0000591 // Cloning the loop basic blocks (`CloneLoopBlocks`) requires that one of the
592 // targets of the Latch be an exit block out of the loop. This needs
593 // to be guaranteed by the callers of UnrollRuntimeLoopRemainder.
Anna Thomas8e431a92017-07-12 20:55:43 +0000594 assert(!L->contains(LatchExit) &&
Anna Thomase5e5e592017-06-30 17:57:07 +0000595 "one of the loop latch successors should be the exit block!");
Anna Thomas8e431a92017-07-12 20:55:43 +0000596 // These are exit blocks other than the target of the latch exiting block.
597 SmallVector<BasicBlock *, 4> OtherExits;
Anna Thomas5c07a4c2017-07-21 16:30:38 +0000598 bool isMultiExitUnrollingEnabled =
599 canSafelyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
600 UseEpilogRemainder) &&
601 canProfitablyUnrollMultiExitLoop(L, OtherExits, LatchExit, PreserveLCSSA,
602 UseEpilogRemainder);
Anna Thomas8e431a92017-07-12 20:55:43 +0000603 // Support only single exit and exiting block unless multi-exit loop unrolling is enabled.
604 if (!isMultiExitUnrollingEnabled &&
605 (!L->getExitingBlock() || OtherExits.size())) {
606 DEBUG(
607 dbgs()
608 << "Multiple exit/exiting blocks in loop and multi-exit unrolling not "
609 "enabled!\n");
Anna Thomaseb6d5d12017-07-06 18:39:26 +0000610 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000611 }
Sanjay Patele08381a2016-02-08 19:27:33 +0000612 // Use Scalar Evolution to compute the trip count. This allows more loops to
613 // be unrolled than relying on induction var simplification.
Justin Bogner843fb202015-12-15 19:40:57 +0000614 if (!SE)
Andrew Trickd29cd732012-05-08 02:52:09 +0000615 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000616
Sanjay Patele08381a2016-02-08 19:27:33 +0000617 // Only unroll loops with a computable trip count, and the trip count needs
618 // to be an int value (allowing a pointer type is a TODO item).
Anna Thomasdc935a62017-06-27 14:14:35 +0000619 // We calculate the backedge count by using getExitCount on the Latch block,
620 // which is proven to be the only exiting block in this loop. This is same as
621 // calculating getBackedgeTakenCount on the loop (which computes SCEV for all
622 // exiting blocks).
623 const SCEV *BECountSC = SE->getExitCount(L, Latch);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000624 if (isa<SCEVCouldNotCompute>(BECountSC) ||
Anna Thomasbafe7662017-07-11 20:44:37 +0000625 !BECountSC->getType()->isIntegerTy()) {
626 DEBUG(dbgs() << "Could not compute exit block SCEV\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000627 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000628 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000629
Sanjoy Das11b279a2015-02-18 19:32:25 +0000630 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000631
Sanjay Patele08381a2016-02-08 19:27:33 +0000632 // Add 1 since the backedge count doesn't include the first loop iteration.
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000633 const SCEV *TripCountSC =
Justin Bogner843fb202015-12-15 19:40:57 +0000634 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
Anna Thomasbafe7662017-07-11 20:44:37 +0000635 if (isa<SCEVCouldNotCompute>(TripCountSC)) {
636 DEBUG(dbgs() << "Could not compute trip count SCEV.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000637 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000638 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000639
David L Kreitzer188de5a2016-04-05 12:19:35 +0000640 BasicBlock *PreHeader = L->getLoopPreheader();
641 BranchInst *PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Sanjoy Dase178f462015-04-14 03:20:38 +0000642 const DataLayout &DL = Header->getModule()->getDataLayout();
Justin Bogner843fb202015-12-15 19:40:57 +0000643 SCEVExpander Expander(*SE, DL, "loop-unroll");
Junmo Park6ebdc142016-02-16 06:46:58 +0000644 if (!AllowExpensiveTripCount &&
Anna Thomasbafe7662017-07-11 20:44:37 +0000645 Expander.isHighCostExpansion(TripCountSC, L, PreHeaderBR)) {
646 DEBUG(dbgs() << "High cost for expanding trip count scev!\n");
Sanjoy Dase178f462015-04-14 03:20:38 +0000647 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000648 }
Sanjoy Dase178f462015-04-14 03:20:38 +0000649
Sanjoy Das11b279a2015-02-18 19:32:25 +0000650 // This constraint lets us deal with an overflowing trip count easily; see the
Sanjoy Das71190fe2015-04-12 01:24:01 +0000651 // comment on ModVal below.
Anna Thomasbafe7662017-07-11 20:44:37 +0000652 if (Log2_32(Count) > BEWidth) {
653 DEBUG(dbgs()
654 << "Count failed constraint on overflow trip count calculation.\n");
Andrew Trickd04d15292011-12-09 06:19:40 +0000655 return false;
Anna Thomasbafe7662017-07-11 20:44:37 +0000656 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000657
David L Kreitzer188de5a2016-04-05 12:19:35 +0000658 // Loop structure is the following:
659 //
660 // PreHeader
661 // Header
662 // ...
663 // Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000664 // LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000665
666 BasicBlock *NewPreHeader;
667 BasicBlock *NewExit = nullptr;
668 BasicBlock *PrologExit = nullptr;
669 BasicBlock *EpilogPreHeader = nullptr;
670 BasicBlock *PrologPreHeader = nullptr;
671
672 if (UseEpilogRemainder) {
673 // If epilog remainder
674 // Split PreHeader to insert a branch around loop for unrolling.
675 NewPreHeader = SplitBlock(PreHeader, PreHeader->getTerminator(), DT, LI);
676 NewPreHeader->setName(PreHeader->getName() + ".new");
Anna Thomas91eed9a2017-06-23 14:28:01 +0000677 // Split LatchExit to create phi nodes from branch above.
678 SmallVector<BasicBlock*, 4> Preds(predecessors(LatchExit));
679 NewExit = SplitBlockPredecessors(LatchExit, Preds, ".unr-lcssa",
David L Kreitzer188de5a2016-04-05 12:19:35 +0000680 DT, LI, PreserveLCSSA);
681 // Split NewExit to insert epilog remainder loop.
682 EpilogPreHeader = SplitBlock(NewExit, NewExit->getTerminator(), DT, LI);
683 EpilogPreHeader->setName(Header->getName() + ".epil.preheader");
684 } else {
685 // If prolog remainder
686 // Split the original preheader twice to insert prolog remainder loop
687 PrologPreHeader = SplitEdge(PreHeader, Header, DT, LI);
688 PrologPreHeader->setName(Header->getName() + ".prol.preheader");
689 PrologExit = SplitBlock(PrologPreHeader, PrologPreHeader->getTerminator(),
690 DT, LI);
691 PrologExit->setName(Header->getName() + ".prol.loopexit");
692 // Split PrologExit to get NewPreHeader.
693 NewPreHeader = SplitBlock(PrologExit, PrologExit->getTerminator(), DT, LI);
694 NewPreHeader->setName(PreHeader->getName() + ".new");
695 }
696 // Loop structure should be the following:
697 // Epilog Prolog
698 //
699 // PreHeader PreHeader
700 // *NewPreHeader *PrologPreHeader
701 // Header *PrologExit
702 // ... *NewPreHeader
703 // Latch Header
704 // *NewExit ...
705 // *EpilogPreHeader Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000706 // LatchExit LatchExit
David L Kreitzer188de5a2016-04-05 12:19:35 +0000707
708 // Calculate conditions for branch around loop for unrolling
709 // in epilog case and around prolog remainder loop in prolog case.
Andrew Trickd04d15292011-12-09 06:19:40 +0000710 // Compute the number of extra iterations required, which is:
David L Kreitzer188de5a2016-04-05 12:19:35 +0000711 // extra iterations = run-time trip count % loop unroll factor
712 PreHeaderBR = cast<BranchInst>(PreHeader->getTerminator());
Andrew Trickd04d15292011-12-09 06:19:40 +0000713 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
714 PreHeaderBR);
Sanjoy Das11b279a2015-02-18 19:32:25 +0000715 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
716 PreHeaderBR);
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000717 IRBuilder<> B(PreHeaderBR);
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000718 Value *ModVal;
719 // Calculate ModVal = (BECount + 1) % Count.
720 // Note that TripCount is BECount + 1.
721 if (isPowerOf2_32(Count)) {
David L Kreitzer188de5a2016-04-05 12:19:35 +0000722 // When Count is power of 2 we don't BECount for epilog case, however we'll
723 // need it for a branch around unrolling loop for prolog case.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000724 ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
David L Kreitzer188de5a2016-04-05 12:19:35 +0000725 // 1. There are no iterations to be run in the prolog/epilog loop.
David L Kreitzer8d441eb2016-03-25 14:24:52 +0000726 // OR
727 // 2. The addition computing TripCount overflowed.
728 //
729 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so
730 // the number of iterations that remain to be run in the original loop is a
731 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
732 // explicitly check this above).
733 } else {
734 // As (BECount + 1) can potentially unsigned overflow we count
735 // (BECount % Count) + 1 which is overflow safe as BECount % Count < Count.
736 Value *ModValTmp = B.CreateURem(BECount,
737 ConstantInt::get(BECount->getType(),
738 Count));
739 Value *ModValAdd = B.CreateAdd(ModValTmp,
740 ConstantInt::get(ModValTmp->getType(), 1));
741 // At that point (BECount % Count) + 1 could be equal to Count.
742 // To handle this case we need to take mod by Count one more time.
743 ModVal = B.CreateURem(ModValAdd,
744 ConstantInt::get(BECount->getType(), Count),
745 "xtraiter");
746 }
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000747 Value *BranchVal =
748 UseEpilogRemainder ? B.CreateICmpULT(BECount,
749 ConstantInt::get(BECount->getType(),
750 Count - 1)) :
751 B.CreateIsNotNull(ModVal, "lcmp.mod");
752 BasicBlock *RemainderLoop = UseEpilogRemainder ? NewExit : PrologPreHeader;
753 BasicBlock *UnrollingLoop = UseEpilogRemainder ? NewPreHeader : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000754 // Branch to either remainder (extra iterations) loop or unrolling loop.
Evgeny Stupachenko23ce61b2016-04-27 03:04:54 +0000755 B.CreateCondBr(BranchVal, RemainderLoop, UnrollingLoop);
Andrew Trickd04d15292011-12-09 06:19:40 +0000756 PreHeaderBR->eraseFromParent();
Eli Friedman0a217452017-01-18 23:26:37 +0000757 if (DT) {
758 if (UseEpilogRemainder)
759 DT->changeImmediateDominator(NewExit, PreHeader);
760 else
761 DT->changeImmediateDominator(PrologExit, PreHeader);
762 }
Andrew Trickd04d15292011-12-09 06:19:40 +0000763 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000764 // Get an ordered list of blocks in the loop to help with the ordering of the
David L Kreitzer188de5a2016-04-05 12:19:35 +0000765 // cloned blocks in the prolog/epilog code
Andrew Trickd04d15292011-12-09 06:19:40 +0000766 LoopBlocksDFS LoopBlocks(L);
767 LoopBlocks.perform(LI);
768
769 //
770 // For each extra loop iteration, create a copy of the loop's basic blocks
771 // and generate a condition that branches to the copy depending on the
772 // number of 'left over' iterations.
773 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000774 std::vector<BasicBlock *> NewBlocks;
775 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000776
David L Kreitzer188de5a2016-04-05 12:19:35 +0000777 // For unroll factor 2 remainder loop will have 1 iterations.
778 // Do not create 1 iteration loop.
779 bool CreateRemainderLoop = (Count != 2);
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000780
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000781 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
782 // the loop, otherwise we create a cloned loop to execute the extra
783 // iterations. This function adds the appropriate CFG connections.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000784 BasicBlock *InsertBot = UseEpilogRemainder ? LatchExit : PrologExit;
David L Kreitzer188de5a2016-04-05 12:19:35 +0000785 BasicBlock *InsertTop = UseEpilogRemainder ? EpilogPreHeader : PrologPreHeader;
Anna Thomase5e5e592017-06-30 17:57:07 +0000786 Loop *remainderLoop = CloneLoopBlocks(
Sam Parker718c8a62017-08-14 09:25:26 +0000787 L, ModVal, CreateRemainderLoop, UseEpilogRemainder, UnrollRemainder,
788 InsertTop, InsertBot,
Anna Thomase5e5e592017-06-30 17:57:07 +0000789 NewPreHeader, NewBlocks, LoopBlocks, VMap, DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000790
David L Kreitzer188de5a2016-04-05 12:19:35 +0000791 // Insert the cloned blocks into the function.
792 F->getBasicBlockList().splice(InsertBot->getIterator(),
793 F->getBasicBlockList(),
794 NewBlocks[0]->getIterator(),
795 F->end());
796
Anna Thomase5e5e592017-06-30 17:57:07 +0000797 // Now the loop blocks are cloned and the other exiting blocks from the
798 // remainder are connected to the original Loop's exit blocks. The remaining
799 // work is to update the phi nodes in the original loop, and take in the
800 // values from the cloned region. Also update the dominator info for
Anna Thomasec9b3262017-07-13 13:21:23 +0000801 // OtherExits and their immediate successors, since we have new edges into
802 // OtherExits.
803 SmallSet<BasicBlock*, 8> ImmediateSuccessorsOfExitBlocks;
Anna Thomase5e5e592017-06-30 17:57:07 +0000804 for (auto *BB : OtherExits) {
805 for (auto &II : *BB) {
806
807 // Given we preserve LCSSA form, we know that the values used outside the
808 // loop will be used through these phi nodes at the exit blocks that are
809 // transformed below.
810 if (!isa<PHINode>(II))
811 break;
812 PHINode *Phi = cast<PHINode>(&II);
813 unsigned oldNumOperands = Phi->getNumIncomingValues();
814 // Add the incoming values from the remainder code to the end of the phi
815 // node.
816 for (unsigned i =0; i < oldNumOperands; i++){
Anna Thomas512dde72017-09-15 13:29:33 +0000817 Value *newVal = VMap.lookup(Phi->getIncomingValue(i));
Anna Thomas70ffd652017-07-10 15:29:38 +0000818 // newVal can be a constant or derived from values outside the loop, and
Anna Thomas512dde72017-09-15 13:29:33 +0000819 // hence need not have a VMap value. Also, since lookup already generated
820 // a default "null" VMap entry for this value, we need to populate that
821 // VMap entry correctly, with the mapped entry being itself.
822 if (!newVal) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000823 newVal = Phi->getIncomingValue(i);
Anna Thomas512dde72017-09-15 13:29:33 +0000824 VMap[Phi->getIncomingValue(i)] = Phi->getIncomingValue(i);
825 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000826 Phi->addIncoming(newVal,
827 cast<BasicBlock>(VMap[Phi->getIncomingBlock(i)]));
828 }
829 }
Simon Pilgrimf32f4be2017-07-13 17:10:12 +0000830#if defined(EXPENSIVE_CHECKS) && !defined(NDEBUG)
Anna Thomasec9b3262017-07-13 13:21:23 +0000831 for (BasicBlock *SuccBB : successors(BB)) {
832 assert(!(any_of(OtherExits,
833 [SuccBB](BasicBlock *EB) { return EB == SuccBB; }) ||
834 SuccBB == LatchExit) &&
835 "Breaks the definition of dedicated exits!");
836 }
837#endif
Anna Thomase5e5e592017-06-30 17:57:07 +0000838 // Update the dominator info because the immediate dominator is no longer the
839 // header of the original Loop. BB has edges both from L and remainder code.
840 // Since the preheader determines which loop is run (L or directly jump to
841 // the remainder code), we set the immediate dominator as the preheader.
Anna Thomasec9b3262017-07-13 13:21:23 +0000842 if (DT) {
Anna Thomase5e5e592017-06-30 17:57:07 +0000843 DT->changeImmediateDominator(BB, PreHeader);
Anna Thomasec9b3262017-07-13 13:21:23 +0000844 // Also update the IDom for immediate successors of BB. If the current
845 // IDom is the header, update the IDom to be the preheader because that is
846 // the nearest common dominator of all predecessors of SuccBB. We need to
847 // check for IDom being the header because successors of exit blocks can
848 // have edges from outside the loop, and we should not incorrectly update
849 // the IDom in that case.
850 for (BasicBlock *SuccBB: successors(BB))
851 if (ImmediateSuccessorsOfExitBlocks.insert(SuccBB).second) {
852 if (DT->getNode(SuccBB)->getIDom()->getBlock() == Header) {
853 assert(!SuccBB->getSinglePredecessor() &&
854 "BB should be the IDom then!");
855 DT->changeImmediateDominator(SuccBB, PreHeader);
856 }
857 }
858 }
Anna Thomase5e5e592017-06-30 17:57:07 +0000859 }
860
David L Kreitzer188de5a2016-04-05 12:19:35 +0000861 // Loop structure should be the following:
862 // Epilog Prolog
863 //
864 // PreHeader PreHeader
865 // NewPreHeader PrologPreHeader
866 // Header PrologHeader
867 // ... ...
868 // Latch PrologLatch
869 // NewExit PrologExit
870 // EpilogPreHeader NewPreHeader
871 // EpilogHeader Header
872 // ... ...
873 // EpilogLatch Latch
Anna Thomas91eed9a2017-06-23 14:28:01 +0000874 // LatchExit LatchExit
Andrew Trickd04d15292011-12-09 06:19:40 +0000875
Sanjay Patel4d36bba2016-02-08 21:32:43 +0000876 // Rewrite the cloned instruction operands to use the values created when the
877 // clone is created.
878 for (BasicBlock *BB : NewBlocks) {
879 for (Instruction &I : *BB) {
880 RemapInstruction(&I, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000881 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Andrew Trickd04d15292011-12-09 06:19:40 +0000882 }
883 }
884
David L Kreitzer188de5a2016-04-05 12:19:35 +0000885 if (UseEpilogRemainder) {
886 // Connect the epilog code to the original loop and update the
887 // PHI functions.
Anna Thomas91eed9a2017-06-23 14:28:01 +0000888 ConnectEpilog(L, ModVal, NewExit, LatchExit, PreHeader,
David L Kreitzer188de5a2016-04-05 12:19:35 +0000889 EpilogPreHeader, NewPreHeader, VMap, DT, LI,
890 PreserveLCSSA);
891
892 // Update counter in loop for unrolling.
893 // I should be multiply of Count.
894 IRBuilder<> B2(NewPreHeader->getTerminator());
895 Value *TestVal = B2.CreateSub(TripCount, ModVal, "unroll_iter");
896 BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
897 B2.SetInsertPoint(LatchBR);
898 PHINode *NewIdx = PHINode::Create(TestVal->getType(), 2, "niter",
899 Header->getFirstNonPHI());
900 Value *IdxSub =
901 B2.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
902 NewIdx->getName() + ".nsub");
903 Value *IdxCmp;
904 if (LatchBR->getSuccessor(0) == Header)
905 IdxCmp = B2.CreateIsNotNull(IdxSub, NewIdx->getName() + ".ncmp");
906 else
907 IdxCmp = B2.CreateIsNull(IdxSub, NewIdx->getName() + ".ncmp");
908 NewIdx->addIncoming(TestVal, NewPreHeader);
909 NewIdx->addIncoming(IdxSub, Latch);
910 LatchBR->setCondition(IdxCmp);
911 } else {
912 // Connect the prolog code to the original loop and update the
913 // PHI functions.
Anna Thomas734ab3f2017-07-07 18:05:28 +0000914 ConnectProlog(L, BECount, Count, PrologExit, LatchExit, PreHeader,
915 NewPreHeader, VMap, DT, LI, PreserveLCSSA);
David L Kreitzer188de5a2016-04-05 12:19:35 +0000916 }
Wei Mi59ca9662016-08-25 16:17:18 +0000917
918 // If this loop is nested, then the loop unroller changes the code in the
919 // parent loop, so the Scalar Evolution pass needs to be run again.
920 if (Loop *ParentLoop = L->getParentLoop())
921 SE->forgetLoop(ParentLoop);
922
Anna Thomase5e5e592017-06-30 17:57:07 +0000923 // Canonicalize to LoopSimplifyForm both original and remainder loops. We
924 // cannot rely on the LoopUnrollPass to do this because it only does
925 // canonicalization for parent/subloops and not the sibling loops.
926 if (OtherExits.size() > 0) {
927 // Generate dedicated exit blocks for the original loop, to preserve
928 // LoopSimplifyForm.
929 formDedicatedExitBlocks(L, DT, LI, PreserveLCSSA);
930 // Generate dedicated exit blocks for the remainder loop if one exists, to
931 // preserve LoopSimplifyForm.
932 if (remainderLoop)
933 formDedicatedExitBlocks(remainderLoop, DT, LI, PreserveLCSSA);
934 }
935
Sam Parker718c8a62017-08-14 09:25:26 +0000936 if (remainderLoop && UnrollRemainder) {
Sam Parker7cd826a2017-09-04 08:12:16 +0000937 DEBUG(dbgs() << "Unrolling remainder loop\n");
Sam Parker718c8a62017-08-14 09:25:26 +0000938 UnrollLoop(remainderLoop, /*Count*/Count - 1, /*TripCount*/Count - 1,
939 /*Force*/false, /*AllowRuntime*/false,
940 /*AllowExpensiveTripCount*/false, /*PreserveCondBr*/true,
941 /*PreserveOnlyFirst*/false, /*TripMultiple*/1,
942 /*PeelCount*/0, /*UnrollRemainder*/false, LI, SE, DT, AC, ORE,
943 PreserveLCSSA);
944 }
945
Andrew Trickd04d15292011-12-09 06:19:40 +0000946 NumRuntimeUnrolled++;
947 return true;
948}