blob: 73c14f5606b73035e2f046136ddd03ec191ac5ea [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
Michael Kuperstein2da2bfa2017-03-16 21:07:48 +000059 // Don't try to peel loops where the latch is not the exiting block.
60 // This can be an indication of two different things:
61 // 1) The loop is not rotated.
62 // 2) The loop contains irreducible control flow that involves the latch.
63 if (L->getLoopLatch() != L->getExitingBlock())
64 return false;
65
Michael Kupersteinb151a642016-11-30 21:13:57 +000066 return true;
67}
68
69// Return the number of iterations we want to peel off.
70void llvm::computePeelCount(Loop *L, unsigned LoopSize,
Sanjoy Daseed71b92017-03-03 18:19:10 +000071 TargetTransformInfo::UnrollingPreferences &UP,
72 unsigned &TripCount) {
Michael Kupersteinb151a642016-11-30 21:13:57 +000073 UP.PeelCount = 0;
74 if (!canPeel(L))
75 return;
76
77 // Only try to peel innermost loops.
78 if (!L->empty())
79 return;
80
Sanjoy Das664c9252017-03-03 18:19:15 +000081 // Try to find a Phi node that has the same loop invariant as an input from
82 // its only back edge. If there is such Phi, peeling 1 iteration from the
83 // loop is profitable, because starting from 2nd iteration we will have an
84 // invariant instead of this Phi.
Sanjoy Das30c35382017-03-07 06:03:15 +000085 if (LoopSize <= UP.Threshold) {
86 BasicBlock *BackEdge = L->getLoopLatch();
87 assert(BackEdge && "Loop is not in simplified form?");
Sanjoy Das664c9252017-03-03 18:19:15 +000088 BasicBlock *Header = L->getHeader();
89 // Iterate over Phis to find one with invariant input on back edge.
90 bool FoundCandidate = false;
91 PHINode *Phi;
Sanjoy Das0a4ec552017-03-03 18:53:09 +000092 for (auto BI = Header->begin(); isa<PHINode>(&*BI); ++BI) {
93 Phi = cast<PHINode>(&*BI);
Sanjoy Das664c9252017-03-03 18:19:15 +000094 Value *Input = Phi->getIncomingValueForBlock(BackEdge);
95 if (L->isLoopInvariant(Input)) {
96 FoundCandidate = true;
97 break;
98 }
99 }
100 if (FoundCandidate) {
101 DEBUG(dbgs() << "Peel one iteration to get rid of " << *Phi
102 << " because starting from 2nd iteration it is always"
103 << " an invariant\n");
104 UP.PeelCount = 1;
105 return;
106 }
107 }
108
Sanjoy Daseed71b92017-03-03 18:19:10 +0000109 // Bail if we know the statically calculated trip count.
110 // In this case we rather prefer partial unrolling.
111 if (TripCount)
112 return;
113
Michael Kupersteinb151a642016-11-30 21:13:57 +0000114 // If the user provided a peel count, use that.
115 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0;
116 if (UserPeelCount) {
117 DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount
118 << " iterations.\n");
119 UP.PeelCount = UnrollForcePeelCount;
120 return;
121 }
122
123 // If we don't know the trip count, but have reason to believe the average
124 // trip count is low, peeling should be beneficial, since we will usually
125 // hit the peeled section.
126 // We only do this in the presence of profile information, since otherwise
127 // our estimates of the trip count are not reliable enough.
128 if (UP.AllowPeeling && L->getHeader()->getParent()->getEntryCount()) {
129 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L);
130 if (!PeelCount)
131 return;
132
133 DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount
134 << "\n");
135
136 if (*PeelCount) {
137 if ((*PeelCount <= UnrollPeelMaxCount) &&
138 (LoopSize * (*PeelCount + 1) <= UP.Threshold)) {
139 DEBUG(dbgs() << "Peeling first " << *PeelCount << " iterations.\n");
140 UP.PeelCount = *PeelCount;
141 return;
142 }
143 DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n");
144 DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n");
145 DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1) << "\n");
146 DEBUG(dbgs() << "Max peel cost: " << UP.Threshold << "\n");
147 }
148 }
149
150 return;
151}
152
153/// \brief Update the branch weights of the latch of a peeled-off loop
154/// iteration.
155/// This sets the branch weights for the latch of the recently peeled off loop
156/// iteration correctly.
157/// Our goal is to make sure that:
158/// a) The total weight of all the copies of the loop body is preserved.
159/// b) The total weight of the loop exit is preserved.
160/// c) The body weight is reasonably distributed between the peeled iterations.
161///
162/// \param Header The copy of the header block that belongs to next iteration.
163/// \param LatchBR The copy of the latch branch that belongs to this iteration.
164/// \param IterNumber The serial number of the iteration that was just
165/// peeled off.
166/// \param AvgIters The average number of iterations we expect the loop to have.
167/// \param[in,out] PeeledHeaderWeight The total number of dynamic loop
168/// iterations that are unaccounted for. As an input, it represents the number
169/// of times we expect to enter the header of the iteration currently being
170/// peeled off. The output is the number of times we expect to enter the
171/// header of the next iteration.
172static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR,
173 unsigned IterNumber, unsigned AvgIters,
174 uint64_t &PeeledHeaderWeight) {
175
176 // FIXME: Pick a more realistic distribution.
177 // Currently the proportion of weight we assign to the fall-through
178 // side of the branch drops linearly with the iteration number, and we use
179 // a 0.9 fudge factor to make the drop-off less sharp...
180 if (PeeledHeaderWeight) {
181 uint64_t FallThruWeight =
182 PeeledHeaderWeight * ((float)(AvgIters - IterNumber) / AvgIters * 0.9);
183 uint64_t ExitWeight = PeeledHeaderWeight - FallThruWeight;
184 PeeledHeaderWeight -= ExitWeight;
185
186 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
187 MDBuilder MDB(LatchBR->getContext());
188 MDNode *WeightNode =
189 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThruWeight)
190 : MDB.createBranchWeights(FallThruWeight, ExitWeight);
191 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
192 }
193}
194
195/// \brief Clones the body of the loop L, putting it between \p InsertTop and \p
196/// InsertBot.
197/// \param IterNumber The serial number of the iteration currently being
198/// peeled off.
199/// \param Exit The exit block of the original loop.
200/// \param[out] NewBlocks A list of the the blocks in the newly created clone
201/// \param[out] VMap The value map between the loop and the new clone.
202/// \param LoopBlocks A helper for DFS-traversal of the loop.
203/// \param LVMap A value-map that maps instructions from the original loop to
204/// instructions in the last peeled-off iteration.
205static void cloneLoopBlocks(Loop *L, unsigned IterNumber, BasicBlock *InsertTop,
206 BasicBlock *InsertBot, BasicBlock *Exit,
207 SmallVectorImpl<BasicBlock *> &NewBlocks,
208 LoopBlocksDFS &LoopBlocks, ValueToValueMapTy &VMap,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000209 ValueToValueMapTy &LVMap, DominatorTree *DT,
210 LoopInfo *LI) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000211
212 BasicBlock *Header = L->getHeader();
213 BasicBlock *Latch = L->getLoopLatch();
214 BasicBlock *PreHeader = L->getLoopPreheader();
215
216 Function *F = Header->getParent();
217 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO();
218 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO();
219 Loop *ParentLoop = L->getParentLoop();
220
221 // For each block in the original loop, create a new copy,
222 // and update the value map with the newly created values.
223 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
224 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F);
225 NewBlocks.push_back(NewBB);
226
227 if (ParentLoop)
228 ParentLoop->addBasicBlockToLoop(NewBB, *LI);
229
230 VMap[*BB] = NewBB;
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000231
232 // If dominator tree is available, insert nodes to represent cloned blocks.
233 if (DT) {
234 if (Header == *BB)
235 DT->addNewBlock(NewBB, InsertTop);
236 else {
237 DomTreeNode *IDom = DT->getNode(*BB)->getIDom();
238 // VMap must contain entry for IDom, as the iteration order is RPO.
239 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()]));
240 }
241 }
Michael Kupersteinb151a642016-11-30 21:13:57 +0000242 }
243
244 // Hook-up the control flow for the newly inserted blocks.
245 // The new header is hooked up directly to the "top", which is either
246 // the original loop preheader (for the first iteration) or the previous
247 // iteration's exiting block (for every other iteration)
248 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header]));
249
250 // Similarly, for the latch:
251 // The original exiting edge is still hooked up to the loop exit.
252 // The backedge now goes to the "bottom", which is either the loop's real
253 // header (for the last peeled iteration) or the copied header of the next
254 // iteration (for every other iteration)
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000255 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]);
256 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000257 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
258 LatchBR->setSuccessor(HeaderIdx, InsertBot);
259 LatchBR->setSuccessor(1 - HeaderIdx, Exit);
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000260 if (DT)
261 DT->changeImmediateDominator(InsertBot, NewLatch);
Michael Kupersteinb151a642016-11-30 21:13:57 +0000262
263 // The new copy of the loop body starts with a bunch of PHI nodes
264 // that pick an incoming value from either the preheader, or the previous
265 // loop iteration. Since this copy is no longer part of the loop, we
266 // resolve this statically:
267 // For the first iteration, we use the value from the preheader directly.
268 // For any other iteration, we replace the phi with the value generated by
269 // the immediately preceding clone of the loop body (which represents
270 // the previous iteration).
271 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
272 PHINode *NewPHI = cast<PHINode>(VMap[&*I]);
273 if (IterNumber == 0) {
274 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader);
275 } else {
276 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch);
277 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
278 if (LatchInst && L->contains(LatchInst))
279 VMap[&*I] = LVMap[LatchInst];
280 else
281 VMap[&*I] = LatchVal;
282 }
283 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI);
284 }
285
286 // Fix up the outgoing values - we need to add a value for the iteration
287 // we've just created. Note that this must happen *after* the incoming
288 // values are adjusted, since the value going out of the latch may also be
289 // a value coming into the header.
290 for (BasicBlock::iterator I = Exit->begin(); isa<PHINode>(I); ++I) {
291 PHINode *PHI = cast<PHINode>(I);
292 Value *LatchVal = PHI->getIncomingValueForBlock(Latch);
293 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal);
294 if (LatchInst && L->contains(LatchInst))
295 LatchVal = VMap[LatchVal];
296 PHI->addIncoming(LatchVal, cast<BasicBlock>(VMap[Latch]));
297 }
298
299 // LastValueMap is updated with the values for the current loop
300 // which are used the next time this function is called.
301 for (const auto &KV : VMap)
302 LVMap[KV.first] = KV.second;
303}
304
305/// \brief Peel off the first \p PeelCount iterations of loop \p L.
306///
307/// Note that this does not peel them off as a single straight-line block.
308/// Rather, each iteration is peeled off separately, and needs to check the
309/// exit condition.
310/// For loops that dynamically execute \p PeelCount iterations or less
311/// this provides a benefit, since the peeled off iterations, which account
312/// for the bulk of dynamic execution, can be further simplified by scalar
313/// optimizations.
314bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI,
315 ScalarEvolution *SE, DominatorTree *DT,
Eli Friedman0a217452017-01-18 23:26:37 +0000316 AssumptionCache *AC, bool PreserveLCSSA) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000317 if (!canPeel(L))
318 return false;
319
320 LoopBlocksDFS LoopBlocks(L);
321 LoopBlocks.perform(LI);
322
323 BasicBlock *Header = L->getHeader();
324 BasicBlock *PreHeader = L->getLoopPreheader();
325 BasicBlock *Latch = L->getLoopLatch();
326 BasicBlock *Exit = L->getUniqueExitBlock();
327
328 Function *F = Header->getParent();
329
330 // Set up all the necessary basic blocks. It is convenient to split the
331 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop
332 // body, and a new preheader for the "real" loop.
333
334 // Peeling the first iteration transforms.
335 //
336 // PreHeader:
337 // ...
338 // Header:
339 // LoopBody
340 // If (cond) goto Header
341 // Exit:
342 //
343 // into
344 //
345 // InsertTop:
346 // LoopBody
347 // If (!cond) goto Exit
348 // InsertBot:
349 // NewPreHeader:
350 // ...
351 // Header:
352 // LoopBody
353 // If (cond) goto Header
354 // Exit:
355 //
356 // Each following iteration will split the current bottom anchor in two,
357 // and put the new copy of the loop body between these two blocks. That is,
358 // after peeling another iteration from the example above, we'll split
359 // InsertBot, and get:
360 //
361 // InsertTop:
362 // LoopBody
363 // If (!cond) goto Exit
364 // InsertBot:
365 // LoopBody
366 // If (!cond) goto Exit
367 // InsertBot.next:
368 // NewPreHeader:
369 // ...
370 // Header:
371 // LoopBody
372 // If (cond) goto Header
373 // Exit:
374
375 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI);
376 BasicBlock *InsertBot =
377 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI);
378 BasicBlock *NewPreHeader =
379 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
380
381 InsertTop->setName(Header->getName() + ".peel.begin");
382 InsertBot->setName(Header->getName() + ".peel.next");
383 NewPreHeader->setName(PreHeader->getName() + ".peel.newph");
384
385 ValueToValueMapTy LVMap;
386
387 // If we have branch weight information, we'll want to update it for the
388 // newly created branches.
389 BranchInst *LatchBR =
390 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator());
391 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1);
392
393 uint64_t TrueWeight, FalseWeight;
Xin Tong29402312017-01-02 20:27:23 +0000394 uint64_t ExitWeight = 0, CurHeaderWeight = 0;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000395 if (LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) {
396 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight;
Xin Tong29402312017-01-02 20:27:23 +0000397 // The # of times the loop body executes is the sum of the exit block
398 // weight and the # of times the backedges are taken.
399 CurHeaderWeight = TrueWeight + FalseWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000400 }
401
402 // For each peeled-off iteration, make a copy of the loop.
403 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) {
404 SmallVector<BasicBlock *, 8> NewBlocks;
405 ValueToValueMapTy VMap;
406
Xin Tong29402312017-01-02 20:27:23 +0000407 // Subtract the exit weight from the current header weight -- the exit
408 // weight is exactly the weight of the previous iteration's header.
Michael Kupersteinb151a642016-11-30 21:13:57 +0000409 // FIXME: due to the way the distribution is constructed, we need a
410 // guard here to make sure we don't end up with non-positive weights.
Xin Tong29402312017-01-02 20:27:23 +0000411 if (ExitWeight < CurHeaderWeight)
412 CurHeaderWeight -= ExitWeight;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000413 else
Xin Tong29402312017-01-02 20:27:23 +0000414 CurHeaderWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000415
416 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, Exit,
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000417 NewBlocks, LoopBlocks, VMap, LVMap, DT, LI);
Serge Pavlovb71bb802017-03-26 16:46:53 +0000418
419 // Remap to use values from the current iteration instead of the
420 // previous one.
421 remapInstructionsInBlocks(NewBlocks, VMap);
422
Serge Pavlov098ee2f2017-01-24 06:58:39 +0000423 if (DT) {
424 // Latches of the cloned loops dominate over the loop exit, so idom of the
425 // latter is the first cloned loop body, as original PreHeader dominates
426 // the original loop body.
427 if (Iter == 0)
428 DT->changeImmediateDominator(Exit, cast<BasicBlock>(LVMap[Latch]));
429#ifndef NDEBUG
430 if (VerifyDomInfo)
431 DT->verifyDomTree();
432#endif
433 }
434
Michael Kupersteinb151a642016-11-30 21:13:57 +0000435 updateBranchWeights(InsertBot, cast<BranchInst>(VMap[LatchBR]), Iter,
436 PeelCount, ExitWeight);
437
438 InsertTop = InsertBot;
439 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI);
440 InsertBot->setName(Header->getName() + ".peel.next");
441
442 F->getBasicBlockList().splice(InsertTop->getIterator(),
443 F->getBasicBlockList(),
444 NewBlocks[0]->getIterator(), F->end());
Michael Kupersteinb151a642016-11-30 21:13:57 +0000445 }
446
447 // Now adjust the phi nodes in the loop header to get their initial values
448 // from the last peeled-off iteration instead of the preheader.
449 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
450 PHINode *PHI = cast<PHINode>(I);
451 Value *NewVal = PHI->getIncomingValueForBlock(Latch);
452 Instruction *LatchInst = dyn_cast<Instruction>(NewVal);
453 if (LatchInst && L->contains(LatchInst))
454 NewVal = LVMap[LatchInst];
455
456 PHI->setIncomingValue(PHI->getBasicBlockIndex(NewPreHeader), NewVal);
457 }
458
459 // Adjust the branch weights on the loop exit.
460 if (ExitWeight) {
Xin Tong29402312017-01-02 20:27:23 +0000461 // The backedge count is the difference of current header weight and
462 // current loop exit weight. If the current header weight is smaller than
463 // the current loop exit weight, we mark the loop backedge weight as 1.
464 uint64_t BackEdgeWeight = 0;
465 if (ExitWeight < CurHeaderWeight)
466 BackEdgeWeight = CurHeaderWeight - ExitWeight;
467 else
468 BackEdgeWeight = 1;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000469 MDBuilder MDB(LatchBR->getContext());
470 MDNode *WeightNode =
471 HeaderIdx ? MDB.createBranchWeights(ExitWeight, BackEdgeWeight)
472 : MDB.createBranchWeights(BackEdgeWeight, ExitWeight);
473 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode);
474 }
475
476 // If the loop is nested, we changed the parent loop, update SE.
Eli Friedman0a217452017-01-18 23:26:37 +0000477 if (Loop *ParentLoop = L->getParentLoop()) {
Michael Kupersteinb151a642016-11-30 21:13:57 +0000478 SE->forgetLoop(ParentLoop);
479
Eli Friedman0a217452017-01-18 23:26:37 +0000480 // FIXME: Incrementally update loop-simplify
481 simplifyLoop(ParentLoop, DT, LI, SE, AC, PreserveLCSSA);
482 } else {
483 // FIXME: Incrementally update loop-simplify
484 simplifyLoop(L, DT, LI, SE, AC, PreserveLCSSA);
485 }
486
Michael Kupersteinb151a642016-11-30 21:13:57 +0000487 NumPeeled++;
488
489 return true;
490}