1 //===-- UnrollLoop.cpp - 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. It does not define any
11 // actual pass or policy, but provides a single function to perform loop
12 // unrolling.
13 //
14 // The process of unrolling can produce extraneous basic blocks linked with
15 // unconditional branches. This will be corrected in the future.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "loop-unroll"
20 #include "llvm/Transforms/Utils/UnrollLoop.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopIterator.h"
25 #include "llvm/Analysis/LoopPass.h"
26 #include "llvm/Analysis/ScalarEvolution.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Cloning.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
33 using namespace llvm;
34
35 // TODO: Should these be here or in LoopUnroll?
36 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled");
37 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)");
38
39 /// RemapInstruction - Convert the instruction operands from referencing the
40 /// current values into those specified by VMap.
RemapInstruction(Instruction * I,ValueToValueMapTy & VMap)41 static inline void RemapInstruction(Instruction *I,
42 ValueToValueMapTy &VMap) {
43 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
44 Value *Op = I->getOperand(op);
45 ValueToValueMapTy::iterator It = VMap.find(Op);
46 if (It != VMap.end())
47 I->setOperand(op, It->second);
48 }
49
50 if (PHINode *PN = dyn_cast<PHINode>(I)) {
51 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
52 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
53 if (It != VMap.end())
54 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
55 }
56 }
57 }
58
59 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
60 /// only has one predecessor, and that predecessor only has one successor.
61 /// The LoopInfo Analysis that is passed will be kept consistent.
62 /// Returns the new combined block.
FoldBlockIntoPredecessor(BasicBlock * BB,LoopInfo * LI,LPPassManager * LPM)63 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI,
64 LPPassManager *LPM) {
65 // Merge basic blocks into their predecessor if there is only one distinct
66 // pred, and if there is only one distinct successor of the predecessor, and
67 // if there are no PHI nodes.
68 BasicBlock *OnlyPred = BB->getSinglePredecessor();
69 if (!OnlyPred) return 0;
70
71 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
72 return 0;
73
74 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred);
75
76 // Resolve any PHI nodes at the start of the block. They are all
77 // guaranteed to have exactly one entry if they exist, unless there are
78 // multiple duplicate (but guaranteed to be equal) entries for the
79 // incoming edges. This occurs when there are multiple edges from
80 // OnlyPred to OnlySucc.
81 FoldSingleEntryPHINodes(BB);
82
83 // Delete the unconditional branch from the predecessor...
84 OnlyPred->getInstList().pop_back();
85
86 // Make all PHI nodes that referred to BB now refer to Pred as their
87 // source...
88 BB->replaceAllUsesWith(OnlyPred);
89
90 // Move all definitions in the successor to the predecessor...
91 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
92
93 std::string OldName = BB->getName();
94
95 // Erase basic block from the function...
96
97 // ScalarEvolution holds references to loop exit blocks.
98 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) {
99 if (Loop *L = LI->getLoopFor(BB))
100 SE->forgetLoop(L);
101 }
102 LI->removeBlock(BB);
103 BB->eraseFromParent();
104
105 // Inherit predecessor's name if it exists...
106 if (!OldName.empty() && !OnlyPred->hasName())
107 OnlyPred->setName(OldName);
108
109 return OnlyPred;
110 }
111
112 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true
113 /// if unrolling was successful, or false if the loop was unmodified. Unrolling
114 /// can only fail when the loop's latch block is not terminated by a conditional
115 /// branch instruction. However, if the trip count (and multiple) are not known,
116 /// loop unrolling will mostly produce more code that is no faster.
117 ///
118 /// TripCount is generally defined as the number of times the loop header
119 /// executes. UnrollLoop relaxes the definition to permit early exits: here
120 /// TripCount is the iteration on which control exits LatchBlock if no early
121 /// exits were taken. Note that UnrollLoop assumes that the loop counter test
122 /// terminates LatchBlock in order to remove unnecesssary instances of the
123 /// test. In other words, control may exit the loop prior to TripCount
124 /// iterations via an early branch, but control may not exit the loop from the
125 /// LatchBlock's terminator prior to TripCount iterations.
126 ///
127 /// Similarly, TripMultiple divides the number of times that the LatchBlock may
128 /// execute without exiting the loop.
129 ///
130 /// The LoopInfo Analysis that is passed will be kept consistent.
131 ///
132 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be
133 /// removed from the LoopPassManager as well. LPM can also be NULL.
134 ///
135 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are
136 /// available it must also preserve those analyses.
UnrollLoop(Loop * L,unsigned Count,unsigned TripCount,bool AllowRuntime,unsigned TripMultiple,LoopInfo * LI,LPPassManager * LPM)137 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
138 bool AllowRuntime, unsigned TripMultiple,
139 LoopInfo *LI, LPPassManager *LPM) {
140 BasicBlock *Preheader = L->getLoopPreheader();
141 if (!Preheader) {
142 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n");
143 return false;
144 }
145
146 BasicBlock *LatchBlock = L->getLoopLatch();
147 if (!LatchBlock) {
148 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n");
149 return false;
150 }
151
152 // Loops with indirectbr cannot be cloned.
153 if (!L->isSafeToClone()) {
154 DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n");
155 return false;
156 }
157
158 BasicBlock *Header = L->getHeader();
159 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
160
161 if (!BI || BI->isUnconditional()) {
162 // The loop-rotate pass can be helpful to avoid this in many cases.
163 DEBUG(dbgs() <<
164 " Can't unroll; loop not terminated by a conditional branch.\n");
165 return false;
166 }
167
168 if (Header->hasAddressTaken()) {
169 // The loop-rotate pass can be helpful to avoid this in many cases.
170 DEBUG(dbgs() <<
171 " Won't unroll loop: address of header block is taken.\n");
172 return false;
173 }
174
175 if (TripCount != 0)
176 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n");
177 if (TripMultiple != 1)
178 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n");
179
180 // Effectively "DCE" unrolled iterations that are beyond the tripcount
181 // and will never be executed.
182 if (TripCount != 0 && Count > TripCount)
183 Count = TripCount;
184
185 // Don't enter the unroll code if there is nothing to do. This way we don't
186 // need to support "partial unrolling by 1".
187 if (TripCount == 0 && Count < 2)
188 return false;
189
190 assert(Count > 0);
191 assert(TripMultiple > 0);
192 assert(TripCount == 0 || TripCount % TripMultiple == 0);
193
194 // Are we eliminating the loop control altogether?
195 bool CompletelyUnroll = Count == TripCount;
196
197 // We assume a run-time trip count if the compiler cannot
198 // figure out the loop trip count and the unroll-runtime
199 // flag is specified.
200 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime);
201
202 if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM))
203 return false;
204
205 // Notify ScalarEvolution that the loop will be substantially changed,
206 // if not outright eliminated.
207 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>();
208 if (SE)
209 SE->forgetLoop(L);
210
211 // If we know the trip count, we know the multiple...
212 unsigned BreakoutTrip = 0;
213 if (TripCount != 0) {
214 BreakoutTrip = TripCount % Count;
215 TripMultiple = 0;
216 } else {
217 // Figure out what multiple to use.
218 BreakoutTrip = TripMultiple =
219 (unsigned)GreatestCommonDivisor64(Count, TripMultiple);
220 }
221
222 if (CompletelyUnroll) {
223 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()
224 << " with trip count " << TripCount << "!\n");
225 } else {
226 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName()
227 << " by " << Count);
228 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) {
229 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip);
230 } else if (TripMultiple != 1) {
231 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch");
232 } else if (RuntimeTripCount) {
233 DEBUG(dbgs() << " with run-time trip count");
234 }
235 DEBUG(dbgs() << "!\n");
236 }
237
238 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
239
240 bool ContinueOnTrue = L->contains(BI->getSuccessor(0));
241 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue);
242
243 // For the first iteration of the loop, we should use the precloned values for
244 // PHI nodes. Insert associations now.
245 ValueToValueMapTy LastValueMap;
246 std::vector<PHINode*> OrigPHINode;
247 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
248 OrigPHINode.push_back(cast<PHINode>(I));
249 }
250
251 std::vector<BasicBlock*> Headers;
252 std::vector<BasicBlock*> Latches;
253 Headers.push_back(Header);
254 Latches.push_back(LatchBlock);
255
256 // The current on-the-fly SSA update requires blocks to be processed in
257 // reverse postorder so that LastValueMap contains the correct value at each
258 // exit.
259 LoopBlocksDFS DFS(L);
260 DFS.perform(LI);
261
262 // Stash the DFS iterators before adding blocks to the loop.
263 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
264 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
265
266 for (unsigned It = 1; It != Count; ++It) {
267 std::vector<BasicBlock*> NewBlocks;
268
269 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
270 ValueToValueMapTy VMap;
271 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
272 Header->getParent()->getBasicBlockList().push_back(New);
273
274 // Loop over all of the PHI nodes in the block, changing them to use the
275 // incoming values from the previous block.
276 if (*BB == Header)
277 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
278 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]);
279 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
280 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
281 if (It > 1 && L->contains(InValI))
282 InVal = LastValueMap[InValI];
283 VMap[OrigPHINode[i]] = InVal;
284 New->getInstList().erase(NewPHI);
285 }
286
287 // Update our running map of newest clones
288 LastValueMap[*BB] = New;
289 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
290 VI != VE; ++VI)
291 LastValueMap[VI->first] = VI->second;
292
293 L->addBasicBlockToLoop(New, LI->getBase());
294
295 // Add phi entries for newly created values to all exit blocks.
296 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB);
297 SI != SE; ++SI) {
298 if (L->contains(*SI))
299 continue;
300 for (BasicBlock::iterator BBI = (*SI)->begin();
301 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) {
302 Value *Incoming = phi->getIncomingValueForBlock(*BB);
303 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
304 if (It != LastValueMap.end())
305 Incoming = It->second;
306 phi->addIncoming(Incoming, New);
307 }
308 }
309 // Keep track of new headers and latches as we create them, so that
310 // we can insert the proper branches later.
311 if (*BB == Header)
312 Headers.push_back(New);
313 if (*BB == LatchBlock)
314 Latches.push_back(New);
315
316 NewBlocks.push_back(New);
317 }
318
319 // Remap all instructions in the most recent iteration
320 for (unsigned i = 0; i < NewBlocks.size(); ++i)
321 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
322 E = NewBlocks[i]->end(); I != E; ++I)
323 ::RemapInstruction(I, LastValueMap);
324 }
325
326 // Loop over the PHI nodes in the original block, setting incoming values.
327 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
328 PHINode *PN = OrigPHINode[i];
329 if (CompletelyUnroll) {
330 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
331 Header->getInstList().erase(PN);
332 }
333 else if (Count > 1) {
334 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
335 // If this value was defined in the loop, take the value defined by the
336 // last iteration of the loop.
337 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
338 if (L->contains(InValI))
339 InVal = LastValueMap[InVal];
340 }
341 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch");
342 PN->addIncoming(InVal, Latches.back());
343 }
344 }
345
346 // Now that all the basic blocks for the unrolled iterations are in place,
347 // set up the branches to connect them.
348 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
349 // The original branch was replicated in each unrolled iteration.
350 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
351
352 // The branch destination.
353 unsigned j = (i + 1) % e;
354 BasicBlock *Dest = Headers[j];
355 bool NeedConditional = true;
356
357 if (RuntimeTripCount && j != 0) {
358 NeedConditional = false;
359 }
360
361 // For a complete unroll, make the last iteration end with a branch
362 // to the exit block.
363 if (CompletelyUnroll && j == 0) {
364 Dest = LoopExit;
365 NeedConditional = false;
366 }
367
368 // If we know the trip count or a multiple of it, we can safely use an
369 // unconditional branch for some iterations.
370 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) {
371 NeedConditional = false;
372 }
373
374 if (NeedConditional) {
375 // Update the conditional branch's successor for the following
376 // iteration.
377 Term->setSuccessor(!ContinueOnTrue, Dest);
378 } else {
379 // Remove phi operands at this loop exit
380 if (Dest != LoopExit) {
381 BasicBlock *BB = Latches[i];
382 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
383 SI != SE; ++SI) {
384 if (*SI == Headers[i])
385 continue;
386 for (BasicBlock::iterator BBI = (*SI)->begin();
387 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) {
388 Phi->removeIncomingValue(BB, false);
389 }
390 }
391 }
392 // Replace the conditional branch with an unconditional one.
393 BranchInst::Create(Dest, Term);
394 Term->eraseFromParent();
395 }
396 }
397
398 // Merge adjacent basic blocks, if possible.
399 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
400 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
401 if (Term->isUnconditional()) {
402 BasicBlock *Dest = Term->getSuccessor(0);
403 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM))
404 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
405 }
406 }
407
408 // FIXME: Reconstruct dom info, because it is not preserved properly.
409 // Incrementally updating domtree after loop unrolling would be easy.
410 if (DominatorTree *DT = LPM->getAnalysisIfAvailable<DominatorTree>())
411 DT->runOnFunction(*L->getHeader()->getParent());
412
413 // Simplify any new induction variables in the partially unrolled loop.
414 if (SE && !CompletelyUnroll) {
415 SmallVector<WeakVH, 16> DeadInsts;
416 simplifyLoopIVs(L, SE, LPM, DeadInsts);
417
418 // Aggressively clean up dead instructions that simplifyLoopIVs already
419 // identified. Any remaining should be cleaned up below.
420 while (!DeadInsts.empty())
421 if (Instruction *Inst =
422 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
423 RecursivelyDeleteTriviallyDeadInstructions(Inst);
424 }
425
426 // At this point, the code is well formed. We now do a quick sweep over the
427 // inserted code, doing constant propagation and dead code elimination as we
428 // go.
429 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
430 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
431 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
432 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
433 Instruction *Inst = I++;
434
435 if (isInstructionTriviallyDead(Inst))
436 (*BB)->getInstList().erase(Inst);
437 else if (Value *V = SimplifyInstruction(Inst))
438 if (LI->replacementPreservesLCSSAForm(Inst, V)) {
439 Inst->replaceAllUsesWith(V);
440 (*BB)->getInstList().erase(Inst);
441 }
442 }
443
444 NumCompletelyUnrolled += CompletelyUnroll;
445 ++NumUnrolled;
446 // Remove the loop from the LoopPassManager if it's completely removed.
447 if (CompletelyUnroll && LPM != NULL)
448 LPM->deleteLoopFromQueue(L);
449
450 return true;
451 }
452