blob: 82b4f0922a2786dce27694cbd1daa5a1efcb5459 [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
Andrew Trickd04d15292011-12-09 06:19:40 +000019// unrolled loop to execute the 'left over' iterations. Other strategies
20// include generate a loop before or after the unrolled loop.
21//
22//===----------------------------------------------------------------------===//
23
Andrew Trickd04d15292011-12-09 06:19:40 +000024#include "llvm/Transforms/Utils/UnrollLoop.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000025#include "llvm/ADT/Statistic.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000026#include "llvm/Analysis/AliasAnalysis.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000027#include "llvm/Analysis/LoopIterator.h"
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"
Andrew Trickd04d15292011-12-09 06:19:40 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthb5797b62015-01-18 09:21:15 +000036#include "llvm/Transforms/Scalar.h"
Andrew Trickd04d15292011-12-09 06:19:40 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Cloning.h"
39#include <algorithm>
40
41using namespace llvm;
42
Chandler Carruth964daaa2014-04-22 02:55:47 +000043#define DEBUG_TYPE "loop-unroll"
44
Jakub Staszak1b1d5232011-12-18 21:52:30 +000045STATISTIC(NumRuntimeUnrolled,
Andrew Trickd04d15292011-12-09 06:19:40 +000046 "Number of loops unrolled with run-time trip counts");
47
48/// Connect the unrolling prolog code to the original loop.
49/// The unrolling prolog code contains code to execute the
50/// 'extra' iterations if the run-time trip count modulo the
51/// unroll count is non-zero.
52///
53/// This function performs the following:
54/// - Create PHI nodes at prolog end block to combine values
55/// that exit the prolog code and jump around the prolog.
56/// - Add a PHI operand to a PHI node at the loop exit block
57/// for values that exit the prolog and go around the loop.
58/// - Branch around the original loop if the trip count is less
59/// than the unroll factor.
60///
61static void ConnectProlog(Loop *L, Value *TripCount, unsigned Count,
62 BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
63 BasicBlock *OrigPH, BasicBlock *NewPH,
Chandler Carruthb5797b62015-01-18 09:21:15 +000064 ValueToValueMapTy &VMap, AliasAnalysis *AA,
65 DominatorTree *DT, LoopInfo *LI, Pass *P) {
Andrew Trickd04d15292011-12-09 06:19:40 +000066 BasicBlock *Latch = L->getLoopLatch();
Craig Toppere73658d2014-04-28 04:05:08 +000067 assert(Latch && "Loop must have a latch");
Andrew Trickd04d15292011-12-09 06:19:40 +000068
69 // Create a PHI node for each outgoing value from the original loop
70 // (which means it is an outgoing value from the prolog code too).
71 // The new PHI node is inserted in the prolog end basic block.
72 // The new PHI name is added as an operand of a PHI node in either
73 // the loop header or the loop exit block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +000074 for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
75 SBI != SBE; ++SBI) {
76 for (BasicBlock::iterator BBI = (*SBI)->begin();
Andrew Trickd04d15292011-12-09 06:19:40 +000077 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
78
79 // Add a new PHI node to the prolog end block and add the
80 // appropriate incoming values.
81 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
82 PrologEnd->getTerminator());
83 // Adding a value to the new PHI node from the original loop preheader.
84 // This is the value that skips all the prolog code.
85 if (L->contains(PN)) {
86 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
87 } else {
88 NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
89 }
Jakub Staszak1b1d5232011-12-18 21:52:30 +000090
91 Value *V = PN->getIncomingValueForBlock(Latch);
Andrew Trickd04d15292011-12-09 06:19:40 +000092 if (Instruction *I = dyn_cast<Instruction>(V)) {
93 if (L->contains(I)) {
Kevin Qinfc02e3c2014-09-29 11:15:00 +000094 V = VMap[I];
Andrew Trickd04d15292011-12-09 06:19:40 +000095 }
96 }
97 // Adding a value to the new PHI node from the last prolog block
98 // that was created.
99 NewPN->addIncoming(V, LastPrologBB);
100
101 // Update the existing PHI node operand with the value from the
102 // new PHI node. How this is done depends on if the existing
103 // PHI node is in the original loop block, or the exit block.
104 if (L->contains(PN)) {
105 PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
106 } else {
107 PN->addIncoming(NewPN, PrologEnd);
108 }
109 }
110 }
111
112 // Create a branch around the orignal loop, which is taken if the
113 // trip count is less than the unroll factor.
114 Instruction *InsertPt = PrologEnd->getTerminator();
115 Instruction *BrLoopExit =
116 new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, TripCount,
117 ConstantInt::get(TripCount->getType(), Count));
118 BasicBlock *Exit = L->getUniqueExitBlock();
Craig Toppere73658d2014-04-28 04:05:08 +0000119 assert(Exit && "Loop must have a single exit block only");
Andrew Trickd04d15292011-12-09 06:19:40 +0000120 // Split the exit to maintain loop canonicalization guarantees
121 SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
122 if (!Exit->isLandingPad()) {
Chandler Carruthb5797b62015-01-18 09:21:15 +0000123 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI,
124 P->mustPreserveAnalysisID(LCSSAID));
Andrew Trickd04d15292011-12-09 06:19:40 +0000125 } else {
126 SmallVector<BasicBlock*, 2> NewBBs;
127 SplitLandingPadPredecessors(Exit, Preds, ".unr1-lcssa", ".unr2-lcssa",
128 P, NewBBs);
129 }
130 // Add the branch to the exit block (around the unrolled loop)
131 BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
132 InsertPt->eraseFromParent();
133}
134
135/// Create a clone of the blocks in a loop and connect them together.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000136/// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
137/// loop will be created including all cloned blocks, and the iterator of it
138/// switches to count NewIter down to 0.
Andrew Trickd04d15292011-12-09 06:19:40 +0000139///
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000140static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
141 BasicBlock *InsertTop, BasicBlock *InsertBot,
Andrew Trickd04d15292011-12-09 06:19:40 +0000142 std::vector<BasicBlock *> &NewBlocks,
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000143 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Andrew Trickd04d15292011-12-09 06:19:40 +0000144 LoopInfo *LI) {
Andrew Trickd04d15292011-12-09 06:19:40 +0000145 BasicBlock *Preheader = L->getLoopPreheader();
146 BasicBlock *Header = L->getHeader();
147 BasicBlock *Latch = L->getLoopLatch();
148 Function *F = Header->getParent();
149 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
150 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000151 Loop *NewLoop = 0;
152 Loop *ParentLoop = L->getParentLoop();
153 if (!UnrollProlog) {
154 NewLoop = new Loop();
155 if (ParentLoop)
156 ParentLoop->addChildLoop(NewLoop);
157 else
158 LI->addTopLevelLoop(NewLoop);
159 }
160
Andrew Trickd04d15292011-12-09 06:19:40 +0000161 // For each block in the original loop, create a new copy,
162 // and update the value map with the newly created values.
163 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000164 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
Andrew Trickd04d15292011-12-09 06:19:40 +0000165 NewBlocks.push_back(NewBB);
166
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000167 if (NewLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000168 NewLoop->addBasicBlockToLoop(NewBB, *LI);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000169 else if (ParentLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000170 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000171
172 VMap[*BB] = NewBB;
173 if (Header == *BB) {
174 // For the first block, add a CFG connection to this newly
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000175 // created block.
Andrew Trickd04d15292011-12-09 06:19:40 +0000176 InsertTop->getTerminator()->setSuccessor(0, NewBB);
177
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000178 }
179 if (Latch == *BB) {
180 // For the last block, if UnrollProlog is true, create a direct jump to
181 // InsertBot. If not, create a loop back to cloned head.
182 VMap.erase((*BB)->getTerminator());
183 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
184 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
185 if (UnrollProlog) {
186 LatchBR->eraseFromParent();
187 BranchInst::Create(InsertBot, NewBB);
188 } else {
189 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
190 FirstLoopBB->getFirstNonPHI());
191 IRBuilder<> Builder(LatchBR);
192 Value *IdxSub =
193 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
194 NewIdx->getName() + ".sub");
195 Value *IdxCmp =
196 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
197 BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB);
198 NewIdx->addIncoming(NewIter, InsertTop);
199 NewIdx->addIncoming(IdxSub, NewBB);
200 LatchBR->eraseFromParent();
201 }
202 }
203 }
204
205 // Change the incoming values to the ones defined in the preheader or
206 // cloned loop.
207 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
208 PHINode *NewPHI = cast<PHINode>(VMap[I]);
209 if (UnrollProlog) {
210 VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
211 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
212 } else {
213 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
214 NewPHI->setIncomingBlock(idx, InsertTop);
215 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
216 idx = NewPHI->getBasicBlockIndex(Latch);
217 Value *InVal = NewPHI->getIncomingValue(idx);
218 NewPHI->setIncomingBlock(idx, NewLatch);
219 if (VMap[InVal])
220 NewPHI->setIncomingValue(idx, VMap[InVal]);
221 }
222 }
223 if (NewLoop) {
224 // Add unroll disable metadata to disable future unrolling for this loop.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000225 SmallVector<Metadata *, 4> MDs;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000226 // Reserve first location for self reference to the LoopID metadata node.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000227 MDs.push_back(nullptr);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000228 MDNode *LoopID = NewLoop->getLoopID();
229 if (LoopID) {
230 // First remove any existing loop unrolling metadata.
231 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
232 bool IsUnrollMetadata = false;
233 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
234 if (MD) {
235 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
236 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
Andrew Trickd04d15292011-12-09 06:19:40 +0000237 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000238 if (!IsUnrollMetadata)
239 MDs.push_back(LoopID->getOperand(i));
Andrew Trickd04d15292011-12-09 06:19:40 +0000240 }
241 }
242
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000243 LLVMContext &Context = NewLoop->getHeader()->getContext();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000244 SmallVector<Metadata *, 1> DisableOperands;
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000245 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
246 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000247 MDs.push_back(DisableNode);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000248
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000249 MDNode *NewLoopID = MDNode::get(Context, MDs);
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000250 // Set operand 0 to refer to the loop id itself.
251 NewLoopID->replaceOperandWith(0, NewLoopID);
252 NewLoop->setLoopID(NewLoopID);
Andrew Trickd04d15292011-12-09 06:19:40 +0000253 }
254}
255
256/// Insert code in the prolog code when unrolling a loop with a
257/// run-time trip-count.
258///
259/// This method assumes that the loop unroll factor is total number
260/// of loop bodes in the loop after unrolling. (Some folks refer
261/// to the unroll factor as the number of *extra* copies added).
262/// We assume also that the loop unroll factor is a power-of-two. So, after
263/// unrolling the loop, the number of loop bodies executed is 2,
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000264/// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
Andrew Trickd04d15292011-12-09 06:19:40 +0000265/// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
266/// the switch instruction is generated.
267///
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000268/// extraiters = tripcount % loopfactor
269/// if (extraiters == 0) jump Loop:
270/// else jump Prol
271/// Prol: LoopBody;
272/// extraiters -= 1 // Omitted if unroll factor is 2.
273/// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
274/// if (tripcount < loopfactor) jump End
275/// Loop:
276/// ...
277/// End:
Andrew Trickd04d15292011-12-09 06:19:40 +0000278///
279bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
280 LPPassManager *LPM) {
281 // for now, only unroll loops that contain a single exit
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000282 if (!L->getExitingBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000283 return false;
284
285 // Make sure the loop is in canonical form, and there is a single
286 // exit block only.
Craig Topperf40110f2014-04-25 05:29:35 +0000287 if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
Andrew Trickd04d15292011-12-09 06:19:40 +0000288 return false;
289
290 // Use Scalar Evolution to compute the trip count. This allows more
291 // loops to be unrolled than relying on induction var simplification
Andrew Trickd29cd732012-05-08 02:52:09 +0000292 if (!LPM)
293 return false;
Andrew Trickd04d15292011-12-09 06:19:40 +0000294 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
Craig Topperf40110f2014-04-25 05:29:35 +0000295 if (!SE)
Andrew Trickd04d15292011-12-09 06:19:40 +0000296 return false;
297
298 // Only unroll loops with a computable trip count and the trip count needs
299 // to be an int value (allowing a pointer type is a TODO item)
300 const SCEV *BECount = SE->getBackedgeTakenCount(L);
301 if (isa<SCEVCouldNotCompute>(BECount) || !BECount->getType()->isIntegerTy())
302 return false;
303
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000304 // If BECount is INT_MAX, we can't compute trip-count without overflow.
305 if (BECount->isAllOnesValue())
306 return false;
307
Andrew Trickd04d15292011-12-09 06:19:40 +0000308 // Add 1 since the backedge count doesn't include the first loop iteration
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000309 const SCEV *TripCountSC =
Andrew Trickd04d15292011-12-09 06:19:40 +0000310 SE->getAddExpr(BECount, SE->getConstant(BECount->getType(), 1));
311 if (isa<SCEVCouldNotCompute>(TripCountSC))
312 return false;
313
314 // We only handle cases when the unroll factor is a power of 2.
315 // Count is the loop unroll factor, the number of extra copies added + 1.
316 if ((Count & (Count-1)) != 0)
317 return false;
318
319 // If this loop is nested, then the loop unroller changes the code in
320 // parent loop, so the Scalar Evolution pass needs to be run again
321 if (Loop *ParentLoop = L->getParentLoop())
322 SE->forgetLoop(ParentLoop);
323
Chandler Carruthb5797b62015-01-18 09:21:15 +0000324 // Grab analyses that we preserve.
325 auto *AA = LPM->getAnalysisIfAvailable<AliasAnalysis>();
Chandler Carruth32c52c72015-01-18 02:39:37 +0000326 auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
327 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
328
Andrew Trickd04d15292011-12-09 06:19:40 +0000329 BasicBlock *PH = L->getLoopPreheader();
330 BasicBlock *Header = L->getHeader();
331 BasicBlock *Latch = L->getLoopLatch();
332 // It helps to splits the original preheader twice, one for the end of the
333 // prolog code and one for a new loop preheader
334 BasicBlock *PEnd = SplitEdge(PH, Header, LPM->getAsPass());
Chandler Carruth32c52c72015-01-18 02:39:37 +0000335 BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000336 BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
337
338 // Compute the number of extra iterations required, which is:
339 // extra iterations = run-time trip count % (loop unroll factor + 1)
340 SCEVExpander Expander(*SE, "loop-unroll");
341 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
342 PreHeaderBR);
Andrew Trickd04d15292011-12-09 06:19:40 +0000343
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000344 IRBuilder<> B(PreHeaderBR);
345 Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
346
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000347 // Check if for no extra iterations, then jump to cloned/unrolled loop.
348 // We have to check that the trip count computation didn't overflow when
349 // adding one to the backedge taken count.
Benjamin Kramer0bf086f2014-06-21 13:46:25 +0000350 Value *LCmp = B.CreateIsNotNull(ModVal, "lcmp.mod");
351 Value *OverflowCheck = B.CreateIsNull(TripCount, "lcmp.overflow");
352 Value *BranchVal = B.CreateOr(OverflowCheck, LCmp, "lcmp.or");
353
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000354 // Branch to either the extra iterations or the cloned/unrolled loop
Andrew Trickd04d15292011-12-09 06:19:40 +0000355 // We will fix up the true branch label when adding loop body copies
356 BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
Jakub Staszak1b1d5232011-12-18 21:52:30 +0000357 assert(PreHeaderBR->isUnconditional() &&
358 PreHeaderBR->getSuccessor(0) == PEnd &&
Andrew Trickd04d15292011-12-09 06:19:40 +0000359 "CFG edges in Preheader are not correct");
360 PreHeaderBR->eraseFromParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000361 Function *F = Header->getParent();
Andrew Trickd04d15292011-12-09 06:19:40 +0000362 // Get an ordered list of blocks in the loop to help with the ordering of the
363 // cloned blocks in the prolog code
364 LoopBlocksDFS LoopBlocks(L);
365 LoopBlocks.perform(LI);
366
367 //
368 // For each extra loop iteration, create a copy of the loop's basic blocks
369 // and generate a condition that branches to the copy depending on the
370 // number of 'left over' iterations.
371 //
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000372 std::vector<BasicBlock *> NewBlocks;
373 ValueToValueMapTy VMap;
Andrew Trickd04d15292011-12-09 06:19:40 +0000374
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000375 // If unroll count is 2 and we can't overflow in tripcount computation (which
376 // is BECount + 1), then we don't need a loop for prologue, and we can unroll
377 // it. We can be sure that we don't overflow only if tripcount is a constant.
378 bool UnrollPrologue = (Count == 2 && isa<ConstantInt>(TripCount));
379
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000380 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
381 // the loop, otherwise we create a cloned loop to execute the extra
382 // iterations. This function adds the appropriate CFG connections.
Michael Zolotukhin0dcae712014-11-20 20:19:55 +0000383 CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
384 VMap, LI);
Andrew Trickd04d15292011-12-09 06:19:40 +0000385
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000386 // Insert the cloned blocks into function just before the original loop
387 F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
388 F->end());
Andrew Trickd04d15292011-12-09 06:19:40 +0000389
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000390 // Rewrite the cloned instruction operands to use the values
391 // created when the clone is created.
392 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
393 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
394 E = NewBlocks[i]->end();
395 I != E; ++I) {
396 RemapInstruction(I, VMap,
397 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Andrew Trickd04d15292011-12-09 06:19:40 +0000398 }
399 }
400
401 // Connect the prolog code to the original loop and update the
402 // PHI functions.
Kevin Qinfc02e3c2014-09-29 11:15:00 +0000403 BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
404 ConnectProlog(L, TripCount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000405 AA, DT, LI, LPM->getAsPass());
Andrew Trickd04d15292011-12-09 06:19:40 +0000406 NumRuntimeUnrolled++;
407 return true;
408}