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/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
43 #define DEBUG_TYPE "loop-unroll"
45 STATISTIC(NumRuntimeUnrolled,
46 "Number of loops unrolled with run-time trip counts");
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.
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.
61 static void ConnectProlog(Loop *L, Value *BECount, unsigned Count,
62 BasicBlock *LastPrologBB, BasicBlock *PrologEnd,
63 BasicBlock *OrigPH, BasicBlock *NewPH,
64 ValueToValueMapTy &VMap, AliasAnalysis *AA,
65 DominatorTree *DT, LoopInfo *LI, Pass *P) {
66 BasicBlock *Latch = L->getLoopLatch();
67 assert(Latch && "Loop must have a latch");
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.
74 for (succ_iterator SBI = succ_begin(Latch), SBE = succ_end(Latch);
76 for (BasicBlock::iterator BBI = (*SBI)->begin();
77 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) {
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);
88 NewPN->addIncoming(Constant::getNullValue(PN->getType()), OrigPH);
91 Value *V = PN->getIncomingValueForBlock(Latch);
92 if (Instruction *I = dyn_cast<Instruction>(V)) {
97 // Adding a value to the new PHI node from the last prolog block
99 NewPN->addIncoming(V, LastPrologBB);
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);
107 PN->addIncoming(NewPN, PrologEnd);
112 // Create a branch around the orignal loop, which is taken if there are no
113 // iterations remaining to be executed after running the prologue.
114 Instruction *InsertPt = PrologEnd->getTerminator();
116 assert(Count != 0 && "nonsensical Count!");
118 // If BECount <u (Count - 1) then (BECount + 1) & (Count - 1) == (BECount + 1)
119 // (since Count is a power of 2). This means %xtraiter is (BECount + 1) and
120 // and all of the iterations of this loop were executed by the prologue. Note
121 // that if BECount <u (Count - 1) then (BECount + 1) cannot unsigned-overflow.
122 Instruction *BrLoopExit =
123 new ICmpInst(InsertPt, ICmpInst::ICMP_ULT, BECount,
124 ConstantInt::get(BECount->getType(), Count - 1));
125 BasicBlock *Exit = L->getUniqueExitBlock();
126 assert(Exit && "Loop must have a single exit block only");
127 // Split the exit to maintain loop canonicalization guarantees
128 SmallVector<BasicBlock*, 4> Preds(pred_begin(Exit), pred_end(Exit));
129 SplitBlockPredecessors(Exit, Preds, ".unr-lcssa", AA, DT, LI,
130 P->mustPreserveAnalysisID(LCSSAID));
131 // Add the branch to the exit block (around the unrolled loop)
132 BranchInst::Create(Exit, NewPH, BrLoopExit, InsertPt);
133 InsertPt->eraseFromParent();
136 /// Create a clone of the blocks in a loop and connect them together.
137 /// If UnrollProlog is true, loop structure will not be cloned, otherwise a new
138 /// loop will be created including all cloned blocks, and the iterator of it
139 /// switches to count NewIter down to 0.
141 static void CloneLoopBlocks(Loop *L, Value *NewIter, const bool UnrollProlog,
142 BasicBlock *InsertTop, BasicBlock *InsertBot,
143 std::vector<BasicBlock *> &NewBlocks,
144 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
145 LoopInfo *LI, LPPassManager *LPM) {
146 BasicBlock *Preheader = L->getLoopPreheader();
147 BasicBlock *Header = L->getHeader();
148 BasicBlock *Latch = L->getLoopLatch();
149 Function *F = Header->getParent();
150 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
151 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
153 Loop *ParentLoop = L->getParentLoop();
155 NewLoop = new Loop();
156 LPM->insertLoop(NewLoop, ParentLoop);
159 // For each block in the original loop, create a new copy,
160 // and update the value map with the newly created values.
161 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
162 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".prol", F);
163 NewBlocks.push_back(NewBB);
166 NewLoop->addBasicBlockToLoop(NewBB, *LI);
168 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
172 // For the first block, add a CFG connection to this newly
174 InsertTop->getTerminator()->setSuccessor(0, NewBB);
178 // For the last block, if UnrollProlog is true, create a direct jump to
179 // InsertBot. If not, create a loop back to cloned head.
180 VMap.erase((*BB)->getTerminator());
181 BasicBlock *FirstLoopBB = cast<BasicBlock>(VMap[Header]);
182 BranchInst *LatchBR = cast<BranchInst>(NewBB->getTerminator());
184 LatchBR->eraseFromParent();
185 BranchInst::Create(InsertBot, NewBB);
187 PHINode *NewIdx = PHINode::Create(NewIter->getType(), 2, "prol.iter",
188 FirstLoopBB->getFirstNonPHI());
189 IRBuilder<> Builder(LatchBR);
191 Builder.CreateSub(NewIdx, ConstantInt::get(NewIdx->getType(), 1),
192 NewIdx->getName() + ".sub");
194 Builder.CreateIsNotNull(IdxSub, NewIdx->getName() + ".cmp");
195 BranchInst::Create(FirstLoopBB, InsertBot, IdxCmp, NewBB);
196 NewIdx->addIncoming(NewIter, InsertTop);
197 NewIdx->addIncoming(IdxSub, NewBB);
198 LatchBR->eraseFromParent();
203 // Change the incoming values to the ones defined in the preheader or
205 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
206 PHINode *NewPHI = cast<PHINode>(VMap[I]);
208 VMap[I] = NewPHI->getIncomingValueForBlock(Preheader);
209 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
211 unsigned idx = NewPHI->getBasicBlockIndex(Preheader);
212 NewPHI->setIncomingBlock(idx, InsertTop);
213 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
214 idx = NewPHI->getBasicBlockIndex(Latch);
215 Value *InVal = NewPHI->getIncomingValue(idx);
216 NewPHI->setIncomingBlock(idx, NewLatch);
218 NewPHI->setIncomingValue(idx, VMap[InVal]);
222 // Add unroll disable metadata to disable future unrolling for this loop.
223 SmallVector<Metadata *, 4> MDs;
224 // Reserve first location for self reference to the LoopID metadata node.
225 MDs.push_back(nullptr);
226 MDNode *LoopID = NewLoop->getLoopID();
228 // First remove any existing loop unrolling metadata.
229 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
230 bool IsUnrollMetadata = false;
231 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
233 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
234 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
236 if (!IsUnrollMetadata)
237 MDs.push_back(LoopID->getOperand(i));
241 LLVMContext &Context = NewLoop->getHeader()->getContext();
242 SmallVector<Metadata *, 1> DisableOperands;
243 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
244 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
245 MDs.push_back(DisableNode);
247 MDNode *NewLoopID = MDNode::get(Context, MDs);
248 // Set operand 0 to refer to the loop id itself.
249 NewLoopID->replaceOperandWith(0, NewLoopID);
250 NewLoop->setLoopID(NewLoopID);
254 /// Insert code in the prolog code when unrolling a loop with a
255 /// run-time trip-count.
257 /// This method assumes that the loop unroll factor is total number
258 /// of loop bodes in the loop after unrolling. (Some folks refer
259 /// to the unroll factor as the number of *extra* copies added).
260 /// We assume also that the loop unroll factor is a power-of-two. So, after
261 /// unrolling the loop, the number of loop bodies executed is 2,
262 /// 4, 8, etc. Note - LLVM converts the if-then-sequence to a switch
263 /// instruction in SimplifyCFG.cpp. Then, the backend decides how code for
264 /// the switch instruction is generated.
266 /// extraiters = tripcount % loopfactor
267 /// if (extraiters == 0) jump Loop:
270 /// extraiters -= 1 // Omitted if unroll factor is 2.
271 /// if (extraiters != 0) jump Prol: // Omitted if unroll factor is 2.
272 /// if (tripcount < loopfactor) jump End
277 bool llvm::UnrollRuntimeLoopProlog(Loop *L, unsigned Count, LoopInfo *LI,
278 LPPassManager *LPM) {
279 // for now, only unroll loops that contain a single exit
280 if (!L->getExitingBlock())
283 // Make sure the loop is in canonical form, and there is a single
285 if (!L->isLoopSimplifyForm() || !L->getUniqueExitBlock())
288 // Use Scalar Evolution to compute the trip count. This allows more
289 // loops to be unrolled than relying on induction var simplification
292 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
296 // Only unroll loops with a computable trip count and the trip count needs
297 // to be an int value (allowing a pointer type is a TODO item)
298 const SCEV *BECountSC = SE->getBackedgeTakenCount(L);
299 if (isa<SCEVCouldNotCompute>(BECountSC) ||
300 !BECountSC->getType()->isIntegerTy())
303 unsigned BEWidth = cast<IntegerType>(BECountSC->getType())->getBitWidth();
305 // Add 1 since the backedge count doesn't include the first loop iteration
306 const SCEV *TripCountSC =
307 SE->getAddExpr(BECountSC, SE->getConstant(BECountSC->getType(), 1));
308 if (isa<SCEVCouldNotCompute>(TripCountSC))
311 // We only handle cases when the unroll factor is a power of 2.
312 // Count is the loop unroll factor, the number of extra copies added + 1.
313 if (!isPowerOf2_32(Count))
316 // This constraint lets us deal with an overflowing trip count easily; see the
317 // comment on ModVal below. This check is equivalent to `Log2(Count) <
319 if (static_cast<uint64_t>(Count) > (1ULL << BEWidth))
322 // If this loop is nested, then the loop unroller changes the code in
323 // parent loop, so the Scalar Evolution pass needs to be run again
324 if (Loop *ParentLoop = L->getParentLoop())
325 SE->forgetLoop(ParentLoop);
327 // Grab analyses that we preserve.
328 auto *DTWP = LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
329 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
331 BasicBlock *PH = L->getLoopPreheader();
332 BasicBlock *Header = L->getHeader();
333 BasicBlock *Latch = L->getLoopLatch();
334 // It helps to splits the original preheader twice, one for the end of the
335 // prolog code and one for a new loop preheader
336 BasicBlock *PEnd = SplitEdge(PH, Header, DT, LI);
337 BasicBlock *NewPH = SplitBlock(PEnd, PEnd->getTerminator(), DT, LI);
338 BranchInst *PreHeaderBR = cast<BranchInst>(PH->getTerminator());
340 // Compute the number of extra iterations required, which is:
341 // extra iterations = run-time trip count % (loop unroll factor + 1)
342 SCEVExpander Expander(*SE, "loop-unroll");
343 Value *TripCount = Expander.expandCodeFor(TripCountSC, TripCountSC->getType(),
345 Value *BECount = Expander.expandCodeFor(BECountSC, BECountSC->getType(),
348 IRBuilder<> B(PreHeaderBR);
349 Value *ModVal = B.CreateAnd(TripCount, Count - 1, "xtraiter");
351 // If ModVal is zero, we know that either
352 // 1. there are no iteration to be run in the prologue loop
354 // 2. the addition computing TripCount overflowed
356 // If (2) is true, we know that TripCount really is (1 << BEWidth) and so the
357 // number of iterations that remain to be run in the original loop is a
358 // multiple Count == (1 << Log2(Count)) because Log2(Count) <= BEWidth (we
359 // explicitly check this above).
361 Value *BranchVal = B.CreateIsNotNull(ModVal, "lcmp.mod");
363 // Branch to either the extra iterations or the cloned/unrolled loop
364 // We will fix up the true branch label when adding loop body copies
365 BranchInst::Create(PEnd, PEnd, BranchVal, PreHeaderBR);
366 assert(PreHeaderBR->isUnconditional() &&
367 PreHeaderBR->getSuccessor(0) == PEnd &&
368 "CFG edges in Preheader are not correct");
369 PreHeaderBR->eraseFromParent();
370 Function *F = Header->getParent();
371 // Get an ordered list of blocks in the loop to help with the ordering of the
372 // cloned blocks in the prolog code
373 LoopBlocksDFS LoopBlocks(L);
374 LoopBlocks.perform(LI);
377 // For each extra loop iteration, create a copy of the loop's basic blocks
378 // and generate a condition that branches to the copy depending on the
379 // number of 'left over' iterations.
381 std::vector<BasicBlock *> NewBlocks;
382 ValueToValueMapTy VMap;
384 bool UnrollPrologue = Count == 2;
386 // Clone all the basic blocks in the loop. If Count is 2, we don't clone
387 // the loop, otherwise we create a cloned loop to execute the extra
388 // iterations. This function adds the appropriate CFG connections.
389 CloneLoopBlocks(L, ModVal, UnrollPrologue, PH, PEnd, NewBlocks, LoopBlocks,
392 // Insert the cloned blocks into function just before the original loop
393 F->getBasicBlockList().splice(PEnd, F->getBasicBlockList(), NewBlocks[0],
396 // Rewrite the cloned instruction operands to use the values
397 // created when the clone is created.
398 for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
399 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
400 E = NewBlocks[i]->end();
402 RemapInstruction(I, VMap,
403 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
407 // Connect the prolog code to the original loop and update the
409 BasicBlock *LastLoopBB = cast<BasicBlock>(VMap[Latch]);
410 ConnectProlog(L, BECount, Count, LastLoopBB, PEnd, PH, NewPH, VMap,
411 /*AliasAnalysis*/ nullptr, DT, LI, LPM->getAsPass());
412 NumRuntimeUnrolled++;