1 //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass implements a simple loop unroller. It works best when loops have
11 // been canonicalized by the -indvars pass, allowing it to determine the trip
12 // counts of loops easily.
14 // This pass will multi-block loops only if they contain no non-unrolled
15 // subloops. The process of unrolling can produce extraneous basic blocks
16 // linked with unconditional branches. This will be corrected in the future.
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "loop-unroll"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/Analysis/LoopPass.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/IntrinsicInst.h"
42 STATISTIC(NumUnrolled, "Number of loops completely unrolled");
46 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
47 cl::desc("The cut-off point for loop unrolling"));
49 class VISIBILITY_HIDDEN LoopUnroll : public LoopPass {
50 LoopInfo *LI; // The current loop information
52 static char ID; // Pass ID, replacement for typeid
53 LoopUnroll() : LoopPass((intptr_t)&ID) {}
55 bool runOnLoop(Loop *L, LPPassManager &LPM);
56 BasicBlock* FoldBlockIntoPredecessor(BasicBlock* BB);
58 /// This transformation requires natural loop information & requires that
59 /// loop preheaders be inserted into the CFG...
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequiredID(LoopSimplifyID);
63 AU.addRequiredID(LCSSAID);
64 AU.addRequired<LoopInfo>();
65 AU.addPreservedID(LCSSAID);
66 AU.addPreserved<LoopInfo>();
69 char LoopUnroll::ID = 0;
70 RegisterPass<LoopUnroll> X("loop-unroll", "Unroll loops");
73 LoopPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
75 /// ApproximateLoopSize - Approximate the size of the loop after it has been
77 static unsigned ApproximateLoopSize(const Loop *L) {
79 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
80 BasicBlock *BB = L->getBlocks()[i];
81 Instruction *Term = BB->getTerminator();
82 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
83 if (isa<PHINode>(I) && BB == L->getHeader()) {
84 // Ignore PHI nodes in the header.
85 } else if (I->hasOneUse() && I->use_back() == Term) {
86 // Ignore instructions only used by the loop terminator.
87 } else if (isa<DbgInfoIntrinsic>(I)) {
88 // Ignore debug instructions
93 // TODO: Ignore expressions derived from PHI and constants if inval of phi
94 // is a constant, or if operation is associative. This will get induction
102 // RemapInstruction - Convert the instruction operands from referencing the
103 // current values into those specified by ValueMap.
105 static inline void RemapInstruction(Instruction *I,
106 DenseMap<const Value *, Value*> &ValueMap) {
107 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
108 Value *Op = I->getOperand(op);
109 DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
110 if (It != ValueMap.end()) Op = It->second;
111 I->setOperand(op, Op);
115 // FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it
116 // only has one predecessor, and that predecessor only has one successor.
117 // Returns the new combined block.
118 BasicBlock* LoopUnroll::FoldBlockIntoPredecessor(BasicBlock* BB) {
119 // Merge basic blocks into their predecessor if there is only one distinct
120 // pred, and if there is only one distinct successor of the predecessor, and
121 // if there are no PHI nodes.
123 BasicBlock *OnlyPred = BB->getSinglePredecessor();
124 if (!OnlyPred) return 0;
126 if (OnlyPred->getTerminator()->getNumSuccessors() != 1)
129 DOUT << "Merging: " << *BB << "into: " << *OnlyPred;
131 // Resolve any PHI nodes at the start of the block. They are all
132 // guaranteed to have exactly one entry if they exist, unless there are
133 // multiple duplicate (but guaranteed to be equal) entries for the
134 // incoming edges. This occurs when there are multiple edges from
135 // OnlyPred to OnlySucc.
137 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
138 PN->replaceAllUsesWith(PN->getIncomingValue(0));
139 BB->getInstList().pop_front(); // Delete the phi node...
142 // Delete the unconditional branch from the predecessor...
143 OnlyPred->getInstList().pop_back();
145 // Move all definitions in the successor to the predecessor...
146 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
148 // Make all PHI nodes that referred to BB now refer to Pred as their
150 BB->replaceAllUsesWith(OnlyPred);
152 std::string OldName = BB->getName();
154 // Erase basic block from the function...
156 BB->eraseFromParent();
158 // Inherit predecessors name if it exists...
159 if (!OldName.empty() && !OnlyPred->hasName())
160 OnlyPred->setName(OldName);
165 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {
166 bool Changed = false;
167 LI = &getAnalysis<LoopInfo>();
169 BasicBlock* Header = L->getHeader();
170 BasicBlock* LatchBlock = L->getLoopLatch();
172 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
173 if (BI == 0) return Changed; // Must end in a conditional branch
175 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
176 if (!TripCountC) return Changed; // Must have constant trip count!
178 // Guard against huge trip counts. This also guards against assertions in
179 // APInt from the use of getZExtValue, below.
180 if (TripCountC->getValue().getActiveBits() > 32)
181 return Changed; // More than 2^32 iterations???
183 uint64_t TripCountFull = TripCountC->getZExtValue();
184 if (TripCountFull == 0)
185 return Changed; // Zero iteraitons?
187 unsigned LoopSize = ApproximateLoopSize(L);
188 DOUT << "Loop Unroll: F[" << Header->getParent()->getName()
189 << "] Loop %" << Header->getName() << " Loop Size = "
190 << LoopSize << " Trip Count = " << TripCountFull << " - ";
191 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
192 if (Size > UnrollThreshold) {
193 DOUT << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n";
196 DOUT << "UNROLLING!\n";
198 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
200 unsigned TripCount = (unsigned)TripCountFull;
202 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
204 // For the first iteration of the loop, we should use the precloned values for
205 // PHI nodes. Insert associations now.
206 typedef DenseMap<const Value*, Value*> ValueMapTy;
207 ValueMapTy LastValueMap;
208 std::vector<PHINode*> OrigPHINode;
209 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
210 PHINode *PN = cast<PHINode>(I);
211 OrigPHINode.push_back(PN);
213 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
214 if (L->contains(I->getParent()))
218 // Remove the exit branch from the loop
219 LatchBlock->getInstList().erase(BI);
221 std::vector<BasicBlock*> Headers;
222 std::vector<BasicBlock*> Latches;
223 Headers.push_back(Header);
224 Latches.push_back(LatchBlock);
226 assert(TripCount != 0 && "Trip count of 0 is impossible!");
227 for (unsigned It = 1; It != TripCount; ++It) {
228 char SuffixBuffer[100];
229 sprintf(SuffixBuffer, ".%d", It);
231 std::vector<BasicBlock*> NewBlocks;
233 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
234 E = LoopBlocks.end(); BB != E; ++BB) {
236 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
237 Header->getParent()->getBasicBlockList().push_back(New);
239 // Loop over all of the PHI nodes in the block, changing them to use the
240 // incoming values from the previous block.
242 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
243 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
244 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
245 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
246 if (It > 1 && L->contains(InValI->getParent()))
247 InVal = LastValueMap[InValI];
248 ValueMap[OrigPHINode[i]] = InVal;
249 New->getInstList().erase(NewPHI);
252 // Update our running map of newest clones
253 LastValueMap[*BB] = New;
254 for (ValueMapTy::iterator VI = ValueMap.begin(), VE = ValueMap.end();
256 LastValueMap[VI->first] = VI->second;
258 L->addBasicBlockToLoop(New, *LI);
260 // Add phi entries for newly created values to all exit blocks except
261 // the successor of the latch block. The successor of the exit block will
262 // be updated specially after unrolling all the way.
263 if (*BB != LatchBlock)
264 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
266 Instruction* UseInst = cast<Instruction>(*UI);
267 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
268 PHINode* phi = cast<PHINode>(UseInst);
269 Value* Incoming = phi->getIncomingValueForBlock(*BB);
270 if (isa<Instruction>(Incoming))
271 Incoming = LastValueMap[Incoming];
273 phi->addIncoming(Incoming, New);
277 // Keep track of new headers and latches as we create them, so that
278 // we can insert the proper branches later.
280 Headers.push_back(New);
281 if (*BB == LatchBlock)
282 Latches.push_back(New);
284 NewBlocks.push_back(New);
287 // Remap all instructions in the most recent iteration
288 for (unsigned i = 0; i < NewBlocks.size(); ++i)
289 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
290 E = NewBlocks[i]->end(); I != E; ++I)
291 RemapInstruction(I, LastValueMap);
295 // The latch block exits the loop. If there are any PHI nodes in the
296 // successor blocks, update them to use the appropriate values computed as the
297 // last iteration of the loop.
299 SmallPtrSet<PHINode*, 8> Users;
300 for (Value::use_iterator UI = LatchBlock->use_begin(),
301 UE = LatchBlock->use_end(); UI != UE; ++UI)
302 if (PHINode* phi = dyn_cast<PHINode>(*UI))
305 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]);
306 for (SmallPtrSet<PHINode*,8>::iterator SI = Users.begin(), SE = Users.end();
309 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
310 // If this value was defined in the loop, take the value defined by the
311 // last iteration of the loop.
312 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
313 if (L->contains(InValI->getParent()))
314 InVal = LastValueMap[InVal];
316 PN->addIncoming(InVal, LastIterationBB);
320 // Now loop over the PHI nodes in the original block, setting them to their
322 BasicBlock *Preheader = L->getLoopPreheader();
323 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
324 PHINode *PN = OrigPHINode[i];
325 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
326 Header->getInstList().erase(PN);
329 // Insert the branches that link the different iterations together
330 for (unsigned i = 0; i < Latches.size()-1; ++i) {
331 new BranchInst(Headers[i+1], Latches[i]);
332 if(BasicBlock* Fold = FoldBlockIntoPredecessor(Headers[i+1])) {
333 std::replace(Latches.begin(), Latches.end(), Headers[i+1], Fold);
334 std::replace(Headers.begin(), Headers.end(), Headers[i+1], Fold);
338 // Finally, add an unconditional branch to the block to continue into the exit
340 new BranchInst(LoopExit, Latches[Latches.size()-1]);
341 FoldBlockIntoPredecessor(LoopExit);
343 // At this point, the code is well formed. We now do a quick sweep over the
344 // inserted code, doing constant propagation and dead code elimination as we
346 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
347 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
348 BBE = NewLoopBlocks.end(); BB != BBE; ++BB)
349 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
350 Instruction *Inst = I++;
352 if (isInstructionTriviallyDead(Inst))
353 (*BB)->getInstList().erase(Inst);
354 else if (Constant *C = ConstantFoldInstruction(Inst)) {
355 Inst->replaceAllUsesWith(C);
356 (*BB)->getInstList().erase(Inst);
360 // Update the loop information for this loop.
361 // Remove the loop from the parent.
362 LPM.deleteLoopFromQueue(L);