1 //===-- UnrollLoopRuntime.cpp - Runtime Loop unrolling utilities ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 // The functions in this file are used to generate extra code when the
15 // 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.
18 // The current strategy generates an if-then-else sequence prior to the
19 // unrolled loop to execute the 'left over' iterations. Other strategies
20 // include generate a loop before or after the unrolled loop.
22 //===----------------------------------------------------------------------===//
24 #include "llvm/Transforms/Utils/UnrollLoop.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/LoopIterator.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Analysis/ScalarEvolution.h"
30 #include "llvm/Analysis/ScalarEvolutionExpander.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/IR/Metadata.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Cloning.h"
44 #define DEBUG_TYPE "loop-unroll"
46 STATISTIC(NumRuntimeUnrolled,
47 "Number of loops unrolled with run-time trip counts");
49 /// Connect the unrolling prolog code to the original loop.
50 /// The unrolling prolog code contains code to execute the
51 /// 'extra' iterations if the run-time trip count modulo the
52 /// unroll count is non-zero.
54 /// This function performs the following:
55 /// - Create PHI nodes at prolog end block to combine values
56 /// that exit the prolog code and jump around the prolog.
57 /// - Add a PHI operand to a PHI node at the loop exit block
58 /// for values that exit the prolog and go around the loop.
59 /// - Branch around the original loop if the trip count is less
60 /// than the unroll factor.
62 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
63 BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
64 BasicBlock *OrigPH, BasicBlock *NewPH,
65 ValueToValueMapTy &VMap, AliasAnalysis *AA,
66 DominatorTree *DT, LoopInfo *LI, Pass *P) {
67 BasicBlock *Latch = L->getLoopLatch();
68 assert(Latch && "Loop must have a latch");
70 // Create a PHI node for each outgoing value from the original loop
71 // (which means it is an outgoing value from the prolog code too).
72 // The new PHI node is inserted in the prolog end basic block.
73 // The new PHI name is added as an operand of a PHI node in either
74 // the loop header or the loop exit block.
75 for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
77 for (BasicBlock::iterator BBI = (*SBI)->begin();
78 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
80 // Add a new PHI node to the prolog end block and add the
81 // appropriate incoming values.
82 PHINode *NewPN = PHINode::Create(PN->getType(), 2, PN->getName()+".unr",
83 PrologEnd->getTerminator());
84 // Adding a value to the new PHI node from the original loop preheader.
85 // This is the value that skips all the prolog code.
86 if (L->contains(PN)) {
87 NewPN->addIncoming(PN->getIncomingValueForBlock(NewPH), OrigPH);
89 NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
92 Value *V = PN->getIncomingValueForBlock(Latch);
93 if (Instruction *I = dyn_cast<Instruction>(V)) {
98 // Adding a value to the new PHI node from the last prolog block
100 NewPN->addIncoming(V, LastPrologBB);
102 // Update the existing PHI node operand with the value from the
103 // new PHI node. How this is done depends on if the existing
104 // PHI node is in the original loop block, or the exit block.
105 if (L->contains(PN)) {
106 PN->setIncomingValue(PN->getBasicBlockIndex(NewPH), NewPN);
108 PN->addIncoming(NewPN, PrologEnd);
113 // Create a branch around the orignal loop, which is taken if there are no
114 // iterations remaining to be executed after running the prologue.
115 Instruction *InsertPt = PrologEnd->getTerminator();
117 assert(Count != 0 && "nonsensical Count!");
119 // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
120 // (since Count is a power of 2). This means %xtraiter is (BECount + 1) and
121 // and all of the iterations of this loop were executed by the prologue. Note
122 // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
123 Instruction *BrLoopExit =
124 new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, BECount,
125 ConstantInt::get(BECount->getType(), Count - 1));
126 BasicBlock *Exit = L->getUniqueExitBlock();
127 assert(Exit && "Loop must have a single exit block only");
128 // Split the exit to maintain loop canonicalization guarantees
129 SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
130 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI,
131 P->mustPreserveAnalysisID(LCSSAID));
132 // Add the branch to the exit block (around the unrolled loop)
133 BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
134 InsertPt->eraseFromParent();
137 /// Create a clone of the blocks in a loop and connect them together.
138 /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
139 /// loop will be created including all cloned blocks, and the iterator of it
140 /// switches to count NewIter down to 0.
142 static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
143 BasicBlock *InsertTop, BasicBlock *InsertBot,
144 std::vector<BasicBlock *> &NewBlocks,
145 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
147 BasicBlock *Preheader = L->getLoopPreheader();
148 BasicBlock *Header = L->getHeader();
149 BasicBlock *Latch = L->getLoopLatch();
150 Function *F = Header->getParent();
151 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
152 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
154 Loop *ParentLoop = L->getParentLoop();
156 NewLoop = new Loop();
158 ParentLoop->addChildLoop(NewLoop);
160 LI->addTopLevelLoop(NewLoop);
163 // For each block in the original loop, create a new copy,
164 // and update the value map with the newly created values.
165 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
166 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
167 NewBlocks.push_back(NewBB);
170 NewLoop->addBasicBlockToLoop(NewBB, *LI);
172 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
176 // For the first block, add a CFG connection to this newly
178 InsertTop->getTerminator()->setSuccessor(0, NewBB);
182 // For the last block, if UnrollProlog is true, create a direct jump to
183 // InsertBot. If not, create a loop back to cloned head.
184 VMap.erase((*BB)->getTerminator());
185 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
186 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
188 LatchBR->eraseFromParent();
189 BranchInst::Create(InsertBot, NewBB);
191 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
192 FirstLoopBB->getFirstNonPHI());
193 IRBuilder<> Builder(LatchBR);
195 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
196 NewIdx->getName() + ".sub");
198 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
199 BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB);
200 NewIdx->addIncoming(NewIter, InsertTop);
201 NewIdx->addIncoming(IdxSub, NewBB);
202 LatchBR->eraseFromParent();
207 // Change the incoming values to the ones defined in the preheader or
209 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
210 PHINode *NewPHI = cast<PHINode>(VMap[I]);
212 VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
213 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
215 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
216 NewPHI->setIncomingBlock(idx, InsertTop);
217 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
218 idx = NewPHI->getBasicBlockIndex(Latch);
219 Value *InVal = NewPHI->getIncomingValue(idx);
220 NewPHI->setIncomingBlock(idx, NewLatch);
222 NewPHI->setIncomingValue(idx, VMap[InVal]);
226 // Add unroll disable metadata to disable future unrolling for this loop.
227 SmallVector<Metadata *, 4> MDs;
228 // Reserve first location for self reference to the LoopID metadata node.
229 MDs.push_back(nullptr);
230 MDNode *LoopID = NewLoop->getLoopID();
232 // First remove any existing loop unrolling metadata.
233 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
234 bool IsUnrollMetadata = false;
235 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
237 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
238 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
240 if (!IsUnrollMetadata)
241 MDs.push_back(LoopID->getOperand(i));
245 LLVMContext &Context = NewLoop->getHeader()->getContext();
246 SmallVector<Metadata *, 1> DisableOperands;
247 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
248 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
249 MDs.push_back(DisableNode);
251 MDNode *NewLoopID = MDNode::get(Context, MDs);
252 // Set operand 0 to refer to the loop id itself.
253 NewLoopID->replaceOperandWith(0, NewLoopID);
254 NewLoop->setLoopID(NewLoopID);
258 /// Insert code in the prolog code when unrolling a loop with a
259 /// run-time trip-count.
261 /// This method assumes that the loop unroll factor is total number
262 /// of loop bodes in the loop after unrolling. (Some folks refer
263 /// to the unroll factor as the number of *extra* copies added).
264 /// We assume also that the loop unroll factor is a power-of-two. So, after
265 /// unrolling the loop, the number of loop bodies executed is 2,
266 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
267 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
268 /// the switch instruction is generated.
270 /// extraiters = tripcount % loopfactor
271 /// if (extraiters == 0) jump Loop:
274 /// extraiters -= 1 // Omitted if unroll factor is 2.
275 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
276 /// if (tripcount < loopfactor) jump End
281 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
282 LPPassManager *LPM) {
283 // for now, only unroll loops that contain a single exit
284 if (!L->getExitingBlock())
287 // Make sure the loop is in canonical form, and there is a single
289 if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
292 // Use Scalar Evolution to compute the trip count. This allows more
293 // loops to be unrolled than relying on induction var simplification
296 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
300 // Only unroll loops with a computable trip count and the trip count needs
301 // to be an int value (allowing a pointer type is a TODO item)
302 const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
303 if (isa<SCEVCouldNotCompute>(BECountSC) ||
304 !BECountSC->getType()->isIntegerTy())
307 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
309 // Add 1 since the backedge count doesn't include the first loop iteration
310 const SCEV *TripCountSC =
311 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
312 if (isa<SCEVCouldNotCompute>(TripCountSC))
315 // We only handle cases when the unroll factor is a power of 2.
316 // Count is the loop unroll factor, the number of extra copies added + 1.
317 if (!isPowerOf2_32(Count))
320 // This constraint lets us deal with an overflowing trip count easily; see the
321 // comment on ModVal below.
322 if (Log2_32(Count) > BEWidth)
325 // If this loop is nested, then the loop unroller changes the code in
326 // parent loop, so the Scalar Evolution pass needs to be run again
327 if (Loop *ParentLoop = L->getParentLoop())
328 SE->forgetLoop(ParentLoop);
330 // Grab analyses that we preserve.
331 auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
332 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
334 BasicBlock *PH = L->getLoopPreheader();
335 BasicBlock *Header = L->getHeader();
336 BasicBlock *Latch = L->getLoopLatch();
337 // It helps to splits the original preheader twice, one for the end of the
338 // prolog code and one for a new loop preheader
339 BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI);
340 BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
341 BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
342 const DataLayout &DL = Header->getModule()->getDataLayout();
344 // Compute the number of extra iterations required, which is:
345 // extra iterations = run-time trip count % (loop unroll factor + 1)
346 SCEVExpander Expander(*SE, DL, "loop-unroll");
347 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
349 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
352 IRBuilder<> B(PreHeaderBR);
353 Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
355 // If ModVal is zero, we know that either
356 // 1. there are no iteration to be run in the prologue loop
358 // 2. the addition computing TripCount overflowed
360 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so the
361 // number of iterations that remain to be run in the original loop is a
362 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
363 // explicitly check this above).
365 Value *BranchVal = B.CreateIsNotNull(ModVal, "lcmp.mod");
367 // Branch to either the extra iterations or the cloned/unrolled loop
368 // We will fix up the true branch label when adding loop body copies
369 BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
370 assert(PreHeaderBR->isUnconditional() &&
371 PreHeaderBR->getSuccessor(0) == PEnd &&
372 "CFG edges in Preheader are not correct");
373 PreHeaderBR->eraseFromParent();
374 Function *F = Header->getParent();
375 // Get an ordered list of blocks in the loop to help with the ordering of the
376 // cloned blocks in the prolog code
377 LoopBlocksDFS LoopBlocks(L);
378 LoopBlocks.perform(LI);
381 // For each extra loop iteration, create a copy of the loop's basic blocks
382 // and generate a condition that branches to the copy depending on the
383 // number of 'left over' iterations.
385 std::vector<BasicBlock *> NewBlocks;
386 ValueToValueMapTy VMap;
388 bool UnrollPrologue = Count == 2;
390 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
391 // the loop, otherwise we create a cloned loop to execute the extra
392 // iterations. This function adds the appropriate CFG connections.
393 CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
396 // Insert the cloned blocks into function just before the original loop
397 F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
400 // Rewrite the cloned instruction operands to use the values
401 // created when the clone is created.
402 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
403 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
404 E = NewBlocks[i]->end();
406 RemapInstruction(I, VMap,
407 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
411 // Connect the prolog code to the original loop and update the
413 BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
414 ConnectProlog(L, BECount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
415 /*AliasAnalysis*/ nullptr, DT, LI, LPM->getAsPass());
416 NumRuntimeUnrolled++;