blob: 0227f8a5d13cf5007d779a9ba587bd209db9e8d7 [file] [log] [blame]
Michael Kupersteinb151a642016-11-30 21:13:57 +00001//===-- UnrollLoopPeel.cpp - Loop peeling 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 peeling loops
11// with dynamically inferred (from PGO) trip counts. See LoopUnroll.cpp for
12// unrolling loops with compile-time constant trip counts.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/LoopIterator.h"
18#include "llvm/Analysis/LoopPass.h"
19#include "llvm/Analysis/ScalarEvolution.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/IR/BasicBlock.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/MDBuilder.h"
24#include "llvm/IR/Metadata.h"
25#include "llvm/IR/Module.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/Transforms/Scalar.h"
29#include "llvm/Transforms/Utils/BasicBlockUtils.h"
30#include "llvm/Transforms/Utils/Cloning.h"
Eli Friedman0a217452017-01-18 23:26:37 +000031#include "llvm/Transforms/Utils/LoopSimplify.h"
Michael Kupersteinb151a642016-11-30 21:13:57 +000032#include "llvm/Transforms/Utils/LoopUtils.h"
33#include "llvm/Transforms/Utils/UnrollLoop.h"
34#include <algorithm>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "loop-unroll"
39STATISTIC(NumPeeled, "Number of loops peeled");
40
41static cl::opt<unsigned> UnrollPeelMaxCount(
42 "unroll-peel-max-count", cl::init(7), cl::Hidden,
43 cl::desc("Max average trip count which will cause loop peeling."));
44
45static cl::opt<unsigned> UnrollForcePeelCount(
46 "unroll-force-peel-count", cl::init(0), cl::Hidden,
47 cl::desc("Force a peel count regardless of profiling information."));
48
49// Check whether we are capable of peeling this loop.
50static bool canPeel(Loop *L) {
51 // Make sure the loop is in simplified form
52 if (!L->isLoopSimplifyForm())
53 return false;
54
55 // Only peel loops that contain a single exit
56 if (!L->getExitingBlock() || !L->getUniqueExitBlock())
57 return false;
58
59 return true;
60}
61
62// Return the number of iterations we want to peel off.
63void llvm::computePeelCount(Loop *L, unsigned LoopSize,
Sanjoy Daseed71b92017-03-03 18:19:10 +000064 TargetTransformInfo::UnrollingPreferences &UP,
65 unsigned &TripCount) {
Michael Kupersteinb151a642016-11-30 21:13:57 +000066 UP.PeelCount = 0;
67 if (!canPeel(L))
68 return;
69
70 // Only try to peel innermost loops.
71 if (!L->empty())
72 return;
73
Sanjoy Daseed71b92017-03-03 18:19:10 +000074 // Bail if we know the statically calculated trip count.
75 // In this case we rather prefer partial unrolling.
76 if (TripCount)
77 return;
78
Michael Kupersteinb151a642016-11-30 21:13:57 +000079 // If the user provided a peel count, use that.
80 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
81 if (UserPeelCount) {
82 DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
83 << " iterations.\n");
84 UP.PeelCount = UnrollForcePeelCount;
85 return;
86 }
87
88 // If we don't know the trip count, but have reason to believe the average
89 // trip count is low, peeling should be beneficial, since we will usually
90 // hit the peeled section.
91 // We only do this in the presence of profile information, since otherwise
92 // our estimates of the trip count are not reliable enough.
93 if (UP.AllowPeeling && L->getHeader()->getParent()->getEntryCount()) {
94 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L);
95 if (!PeelCount)
96 return;
97
98 DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount
99 << "\n");
100
101 if (*PeelCount) {
102 if ((*PeelCount <= UnrollPeelMaxCount) &&
103 (LoopSize * (*PeelCount + 1) <= UP.Threshold)) {
104 DEBUG(dbgs() << "Peeling first " << *PeelCount << " iterations.\n");
105 UP.PeelCount = *PeelCount;
106 return;
107 }
108 DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n");
109 DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
110 DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1) << "\n");
111 DEBUG(dbgs() << "Max peel cost: " << UP.Threshold << "\n");
112 }
113 }
114
115 return;
116}
117
118/// \brief Update the branch weights of the latch of a peeled-off loop
119/// iteration.
120/// This sets the branch weights for the latch of the recently peeled off loop
121/// iteration correctly.
122/// Our goal is to make sure that:
123/// a) The total weight of all the copies of the loop body is preserved.
124/// b) The total weight of the loop exit is preserved.
125/// c) The body weight is reasonably distributed between the peeled iterations.
126///
127/// \param Header The copy of the header block that belongs to next iteration.
128/// \param LatchBR The copy of the latch branch that belongs to this iteration.
129/// \param IterNumber The serial number of the iteration that was just
130/// peeled off.
131/// \param AvgIters The average number of iterations we expect the loop to have.
132/// \param[in,out] PeeledHeaderWeight The total number of dynamic loop
133/// iterations that are unaccounted for. As an input, it represents the number
134/// of times we expect to enter the header of the iteration currently being
135/// peeled off. The output is the number of times we expect to enter the
136/// header of the next iteration.
137static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
138 unsigned IterNumber, unsigned AvgIters,
139 uint64_t &PeeledHeaderWeight) {
140
141 // FIXME: Pick a more realistic distribution.
142 // Currently the proportion of weight we assign to the fall-through
143 // side of the branch drops linearly with the iteration number, and we use
144 // a 0.9 fudge factor to make the drop-off less sharp...
145 if (PeeledHeaderWeight) {
146 uint64_t FallThruWeight =
147 PeeledHeaderWeight * ((float)(AvgIters - IterNumber) / AvgIters * 0.9);
148 uint64_t ExitWeight = PeeledHeaderWeight - FallThruWeight;
149 PeeledHeaderWeight -= ExitWeight;
150
151 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
152 MDBuilder MDB(LatchBR->getContext());
153 MDNode *WeightNode =
154 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThruWeight)
155 : MDB.createBranchWeights(FallThruWeight, ExitWeight);
156 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
157 }
158}
159
160/// \brief Clones the body of the loop L, putting it between \p InsertTop and \p
161/// InsertBot.
162/// \param IterNumber The serial number of the iteration currently being
163/// peeled off.
164/// \param Exit The exit block of the original loop.
165/// \param[out] NewBlocks A list of the the blocks in the newly created clone
166/// \param[out] VMap The value map between the loop and the new clone.
167/// \param LoopBlocks A helper for DFS-traversal of the loop.
168/// \param LVMap A value-map that maps instructions from the original loop to
169/// instructions in the last peeled-off iteration.
170static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop,
171 BasicBlock *InsertBot, BasicBlock *Exit,
172 SmallVectorImpl<BasicBlock *> &NewBlocks,
173 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000174 ValueToValueMapTy &LVMap, DominatorTree *DT,
175 LoopInfo *LI) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000176
177 BasicBlock *Header = L->getHeader();
178 BasicBlock *Latch = L->getLoopLatch();
179 BasicBlock *PreHeader = L->getLoopPreheader();
180
181 Function *F = Header->getParent();
182 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
183 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
184 Loop *ParentLoop = L->getParentLoop();
185
186 // For each block in the original loop, create a new copy,
187 // and update the value map with the newly created values.
188 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
189 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
190 NewBlocks.push_back(NewBB);
191
192 if (ParentLoop)
193 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
194
195 VMap[*BB] = NewBB;
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000196
197 // If dominator tree is available, insert nodes to represent cloned blocks.
198 if (DT) {
199 if (Header == *BB)
200 DT->addNewBlock(NewBB, InsertTop);
201 else {
202 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
203 // VMap must contain entry for IDom, as the iteration order is RPO.
204 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
205 }
206 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000207 }
208
209 // Hook-up the control flow for the newly inserted blocks.
210 // The new header is hooked up directly to the "top", which is either
211 // the original loop preheader (for the first iteration) or the previous
212 // iteration's exiting block (for every other iteration)
213 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
214
215 // Similarly, for the latch:
216 // The original exiting edge is still hooked up to the loop exit.
217 // The backedge now goes to the "bottom", which is either the loop's real
218 // header (for the last peeled iteration) or the copied header of the next
219 // iteration (for every other iteration)
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000220 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
221 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000222 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
223 LatchBR->setSuccessor(HeaderIdx, InsertBot);
224 LatchBR->setSuccessor(1 - HeaderIdx, Exit);
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000225 if (DT)
226 DT->changeImmediateDominator(InsertBot, NewLatch);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000227
228 // The new copy of the loop body starts with a bunch of PHI nodes
229 // that pick an incoming value from either the preheader, or the previous
230 // loop iteration. Since this copy is no longer part of the loop, we
231 // resolve this statically:
232 // For the first iteration, we use the value from the preheader directly.
233 // For any other iteration, we replace the phi with the value generated by
234 // the immediately preceding clone of the loop body (which represents
235 // the previous iteration).
236 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
237 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
238 if (IterNumber == 0) {
239 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
240 } else {
241 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
242 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
243 if (LatchInst && L->contains(LatchInst))
244 VMap[&*I] = LVMap[LatchInst];
245 else
246 VMap[&*I] = LatchVal;
247 }
248 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
249 }
250
251 // Fix up the outgoing values - we need to add a value for the iteration
252 // we've just created. Note that this must happen *after* the incoming
253 // values are adjusted, since the value going out of the latch may also be
254 // a value coming into the header.
255 for (BasicBlock::iterator I = Exit->begin(); isa<PHINode>(I); ++I) {
256 PHINode *PHI = cast<PHINode>(I);
257 Value *LatchVal = PHI->getIncomingValueForBlock(Latch);
258 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
259 if (LatchInst && L->contains(LatchInst))
260 LatchVal = VMap[LatchVal];
261 PHI->addIncoming(LatchVal, cast<BasicBlock>(VMap[Latch]));
262 }
263
264 // LastValueMap is updated with the values for the current loop
265 // which are used the next time this function is called.
266 for (const auto &KV : VMap)
267 LVMap[KV.first] = KV.second;
268}
269
270/// \brief Peel off the first \p PeelCount iterations of loop \p L.
271///
272/// Note that this does not peel them off as a single straight-line block.
273/// Rather, each iteration is peeled off separately, and needs to check the
274/// exit condition.
275/// For loops that dynamically execute \p PeelCount iterations or less
276/// this provides a benefit, since the peeled off iterations, which account
277/// for the bulk of dynamic execution, can be further simplified by scalar
278/// optimizations.
279bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
280 ScalarEvolution *SE, DominatorTree *DT,
Eli Friedman0a217452017-01-18 23:26:37 +0000281 AssumptionCache *AC, bool PreserveLCSSA) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000282 if (!canPeel(L))
283 return false;
284
285 LoopBlocksDFS LoopBlocks(L);
286 LoopBlocks.perform(LI);
287
288 BasicBlock *Header = L->getHeader();
289 BasicBlock *PreHeader = L->getLoopPreheader();
290 BasicBlock *Latch = L->getLoopLatch();
291 BasicBlock *Exit = L->getUniqueExitBlock();
292
293 Function *F = Header->getParent();
294
295 // Set up all the necessary basic blocks. It is convenient to split the
296 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
297 // body, and a new preheader for the "real" loop.
298
299 // Peeling the first iteration transforms.
300 //
301 // PreHeader:
302 // ...
303 // Header:
304 // LoopBody
305 // If (cond) goto Header
306 // Exit:
307 //
308 // into
309 //
310 // InsertTop:
311 // LoopBody
312 // If (!cond) goto Exit
313 // InsertBot:
314 // NewPreHeader:
315 // ...
316 // Header:
317 // LoopBody
318 // If (cond) goto Header
319 // Exit:
320 //
321 // Each following iteration will split the current bottom anchor in two,
322 // and put the new copy of the loop body between these two blocks. That is,
323 // after peeling another iteration from the example above, we'll split
324 // InsertBot, and get:
325 //
326 // InsertTop:
327 // LoopBody
328 // If (!cond) goto Exit
329 // InsertBot:
330 // LoopBody
331 // If (!cond) goto Exit
332 // InsertBot.next:
333 // NewPreHeader:
334 // ...
335 // Header:
336 // LoopBody
337 // If (cond) goto Header
338 // Exit:
339
340 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI);
341 BasicBlock *InsertBot =
342 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI);
343 BasicBlock *NewPreHeader =
344 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
345
346 InsertTop->setName(Header->getName() + ".peel.begin");
347 InsertBot->setName(Header->getName() + ".peel.next");
348 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
349
350 ValueToValueMapTy LVMap;
351
352 // If we have branch weight information, we'll want to update it for the
353 // newly created branches.
354 BranchInst *LatchBR =
355 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
356 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
357
358 uint64_t TrueWeight, FalseWeight;
Xin Tong29402312017-01-02 20:27:23 +0000359 uint64_t ExitWeight = 0, CurHeaderWeight = 0;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000360 if (LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) {
361 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
Xin Tong29402312017-01-02 20:27:23 +0000362 // The # of times the loop body executes is the sum of the exit block
363 // weight and the # of times the backedges are taken.
364 CurHeaderWeight = TrueWeight + FalseWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000365 }
366
367 // For each peeled-off iteration, make a copy of the loop.
368 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
369 SmallVector<BasicBlock *, 8> NewBlocks;
370 ValueToValueMapTy VMap;
371
Xin Tong29402312017-01-02 20:27:23 +0000372 // Subtract the exit weight from the current header weight -- the exit
373 // weight is exactly the weight of the previous iteration's header.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000374 // FIXME: due to the way the distribution is constructed, we need a
375 // guard here to make sure we don't end up with non-positive weights.
Xin Tong29402312017-01-02 20:27:23 +0000376 if (ExitWeight < CurHeaderWeight)
377 CurHeaderWeight -= ExitWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000378 else
Xin Tong29402312017-01-02 20:27:23 +0000379 CurHeaderWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000380
381 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, Exit,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000382 NewBlocks, LoopBlocks, VMap, LVMap, DT, LI);
383 if (DT) {
384 // Latches of the cloned loops dominate over the loop exit, so idom of the
385 // latter is the first cloned loop body, as original PreHeader dominates
386 // the original loop body.
387 if (Iter == 0)
388 DT->changeImmediateDominator(Exit, cast<BasicBlock>(LVMap[Latch]));
389#ifndef NDEBUG
390 if (VerifyDomInfo)
391 DT->verifyDomTree();
392#endif
393 }
394
Michael Kupersteinb151a642016-11-30 21:13:57 +0000395 updateBranchWeights(InsertBot, cast<BranchInst>(VMap[LatchBR]), Iter,
396 PeelCount, ExitWeight);
397
398 InsertTop = InsertBot;
399 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
400 InsertBot->setName(Header->getName() + ".peel.next");
401
402 F->getBasicBlockList().splice(InsertTop->getIterator(),
403 F->getBasicBlockList(),
404 NewBlocks[0]->getIterator(), F->end());
405
406 // Remap to use values from the current iteration instead of the
407 // previous one.
408 remapInstructionsInBlocks(NewBlocks, VMap);
409 }
410
411 // Now adjust the phi nodes in the loop header to get their initial values
412 // from the last peeled-off iteration instead of the preheader.
413 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
414 PHINode *PHI = cast<PHINode>(I);
415 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
416 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
417 if (LatchInst && L->contains(LatchInst))
418 NewVal = LVMap[LatchInst];
419
420 PHI->setIncomingValue(PHI->getBasicBlockIndex(NewPreHeader), NewVal);
421 }
422
423 // Adjust the branch weights on the loop exit.
424 if (ExitWeight) {
Xin Tong29402312017-01-02 20:27:23 +0000425 // The backedge count is the difference of current header weight and
426 // current loop exit weight. If the current header weight is smaller than
427 // the current loop exit weight, we mark the loop backedge weight as 1.
428 uint64_t BackEdgeWeight = 0;
429 if (ExitWeight < CurHeaderWeight)
430 BackEdgeWeight = CurHeaderWeight - ExitWeight;
431 else
432 BackEdgeWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000433 MDBuilder MDB(LatchBR->getContext());
434 MDNode *WeightNode =
435 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
436 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
437 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
438 }
439
440 // If the loop is nested, we changed the parent loop, update SE.
Eli Friedman0a217452017-01-18 23:26:37 +0000441 if (Loop *ParentLoop = L->getParentLoop()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000442 SE->forgetLoop(ParentLoop);
443
Eli Friedman0a217452017-01-18 23:26:37 +0000444 // FIXME: Incrementally update loop-simplify
445 simplifyLoop(ParentLoop, DT, LI, SE, AC, PreserveLCSSA);
446 } else {
447 // FIXME: Incrementally update loop-simplify
448 simplifyLoop(L, DT, LI, SE, AC, PreserveLCSSA);
449 }
450
Michael Kupersteinb151a642016-11-30 21:13:57 +0000451 NumPeeled++;
452
453 return true;
454}