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/LoopInfo.h"
26 #include "llvm/Transforms/Utils/Cloning.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/IntrinsicInst.h"
40 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
43 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
44 cl::desc("The cut-off point for loop unrolling"));
46 class LoopUnroll : public FunctionPass {
47 LoopInfo *LI; // The current loop information
49 virtual bool runOnFunction(Function &F);
50 bool visitLoop(Loop *L);
52 /// This transformation requires natural loop information & requires that
53 /// loop preheaders be inserted into the CFG...
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequiredID(LoopSimplifyID);
57 AU.addRequiredID(LCSSAID);
58 AU.addRequired<LoopInfo>();
59 AU.addPreservedID(LCSSAID);
60 AU.addPreserved<LoopInfo>();
63 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
66 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
68 bool LoopUnroll::runOnFunction(Function &F) {
70 LI = &getAnalysis<LoopInfo>();
72 // Transform all the top-level loops. Copy the loop list so that the child
73 // can update the loop tree if it needs to delete the loop.
74 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
75 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
76 Changed |= visitLoop(SubLoops[i]);
81 /// ApproximateLoopSize - Approximate the size of the loop after it has been
83 static unsigned ApproximateLoopSize(const Loop *L) {
85 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
86 BasicBlock *BB = L->getBlocks()[i];
87 Instruction *Term = BB->getTerminator();
88 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
89 if (isa<PHINode>(I) && BB == L->getHeader()) {
90 // Ignore PHI nodes in the header.
91 } else if (I->hasOneUse() && I->use_back() == Term) {
92 // Ignore instructions only used by the loop terminator.
93 } else if (DbgInfoIntrinsic *DbgI = dyn_cast<DbgInfoIntrinsic>(I)) {
94 // Ignore debug instructions
99 // TODO: Ignore expressions derived from PHI and constants if inval of phi
100 // is a constant, or if operation is associative. This will get induction
108 // RemapInstruction - Convert the instruction operands from referencing the
109 // current values into those specified by ValueMap.
111 static inline void RemapInstruction(Instruction *I,
112 std::map<const Value *, Value*> &ValueMap) {
113 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
114 Value *Op = I->getOperand(op);
115 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
116 if (It != ValueMap.end()) Op = It->second;
117 I->setOperand(op, Op);
121 bool LoopUnroll::visitLoop(Loop *L) {
122 bool Changed = false;
124 // Recurse through all subloops before we process this loop. Copy the loop
125 // list so that the child can update the loop tree if it needs to delete the
127 std::vector<Loop*> SubLoops(L->begin(), L->end());
128 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
129 Changed |= visitLoop(SubLoops[i]);
131 BasicBlock* Header = L->getHeader();
132 BasicBlock* LatchBlock = L->getLoopLatch();
134 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
135 if (BI == 0) return Changed; // Must end in a conditional branch
137 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
138 if (!TripCountC) return Changed; // Must have constant trip count!
140 uint64_t TripCountFull = TripCountC->getRawValue();
141 if (TripCountFull != TripCountC->getRawValue() || TripCountFull == 0)
142 return Changed; // More than 2^32 iterations???
144 unsigned LoopSize = ApproximateLoopSize(L);
145 DEBUG(std::cerr << "Loop Unroll: F[" << Header->getParent()->getName()
146 << "] Loop %" << Header->getName() << " Loop Size = "
147 << LoopSize << " Trip Count = " << TripCountFull << " - ");
148 uint64_t Size = (uint64_t)LoopSize*TripCountFull;
149 if (Size > UnrollThreshold) {
150 DEBUG(std::cerr << "TOO LARGE: " << Size << ">" << UnrollThreshold << "\n");
153 DEBUG(std::cerr << "UNROLLING!\n");
155 std::vector<BasicBlock*> LoopBlocks = L->getBlocks();
157 unsigned TripCount = (unsigned)TripCountFull;
159 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
161 // For the first iteration of the loop, we should use the precloned values for
162 // PHI nodes. Insert associations now.
163 std::map<const Value*, Value*> LastValueMap;
164 std::vector<PHINode*> OrigPHINode;
165 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
166 PHINode *PN = cast<PHINode>(I);
167 OrigPHINode.push_back(PN);
169 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock)))
170 if (L->contains(I->getParent()))
174 // Remove the exit branch from the loop
175 LatchBlock->getInstList().erase(BI);
177 std::vector<BasicBlock*> Headers;
178 std::vector<BasicBlock*> Latches;
179 Headers.push_back(Header);
180 Latches.push_back(LatchBlock);
182 assert(TripCount != 0 && "Trip count of 0 is impossible!");
183 for (unsigned It = 1; It != TripCount; ++It) {
184 char SuffixBuffer[100];
185 sprintf(SuffixBuffer, ".%d", It);
187 std::vector<BasicBlock*> NewBlocks;
189 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(),
190 E = LoopBlocks.end(); BB != E; ++BB) {
191 std::map<const Value*, Value*> ValueMap;
192 BasicBlock *New = CloneBasicBlock(*BB, ValueMap, SuffixBuffer);
193 Header->getParent()->getBasicBlockList().push_back(New);
195 // Loop over all of the PHI nodes in the block, changing them to use the
196 // incoming values from the previous block.
198 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
199 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
200 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
201 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
202 if (It > 1 && L->contains(InValI->getParent()))
203 InVal = LastValueMap[InValI];
204 ValueMap[OrigPHINode[i]] = InVal;
205 New->getInstList().erase(NewPHI);
208 // Update our running map of newest clones
209 LastValueMap[*BB] = New;
210 for (std::map<const Value*, Value*>::iterator VI = ValueMap.begin(),
211 VE = ValueMap.end(); VI != VE; ++VI)
212 LastValueMap[VI->first] = VI->second;
214 L->addBasicBlockToLoop(New, *LI);
216 // Add phi entries for newly created values to all exit blocks except
217 // the successor of the latch block. The successor of the exit block will
218 // be updated specially after unrolling all the way.
219 if (*BB != LatchBlock)
220 for (Value::use_iterator UI = (*BB)->use_begin(), UE = (*BB)->use_end();
222 Instruction* UseInst = cast<Instruction>(*UI);
223 if (isa<PHINode>(UseInst) && !L->contains(UseInst->getParent())) {
224 PHINode* phi = cast<PHINode>(UseInst);
225 Value* Incoming = phi->getIncomingValueForBlock(*BB);
226 if (isa<Instruction>(Incoming))
227 Incoming = LastValueMap[Incoming];
229 phi->addIncoming(Incoming, New);
233 // Keep track of new headers and latches as we create them, so that
234 // we can insert the proper branches later.
236 Headers.push_back(New);
237 if (*BB == LatchBlock)
238 Latches.push_back(New);
240 NewBlocks.push_back(New);
243 // Remap all instructions in the most recent iteration
244 for (unsigned i = 0; i < NewBlocks.size(); ++i)
245 for (BasicBlock::iterator I = NewBlocks[i]->begin(),
246 E = NewBlocks[i]->end(); I != E; ++I)
247 RemapInstruction(I, LastValueMap);
250 // Insert the branches that link the different iterations together
251 for (unsigned i = 0; i < Latches.size()-1; ++i)
252 new BranchInst(Headers[i+1], Latches[i]);
254 // Finally, add an unconditional branch to the block to continue into the exit
256 new BranchInst(LoopExit, Latches[Latches.size()-1]);
258 // Update PHI nodes that reference the final latch block
260 std::set<PHINode*> Users;
261 for (Value::use_iterator UI = LatchBlock->use_begin(),
262 UE = LatchBlock->use_end(); UI != UE; ++UI)
263 if (PHINode* phi = dyn_cast<PHINode>(*UI))
266 for (std::set<PHINode*>::iterator SI = Users.begin(), SE = Users.end();
268 Value* InVal = (*SI)->getIncomingValueForBlock(LatchBlock);
269 if (isa<Instruction>(InVal))
270 InVal = LastValueMap[InVal];
271 (*SI)->removeIncomingValue(LatchBlock, false);
272 (*SI)->addIncoming(InVal, cast<BasicBlock>(LastValueMap[LatchBlock]));
276 // Now loop over the PHI nodes in the original block, setting them to their
278 BasicBlock *Preheader = L->getLoopPreheader();
279 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
280 PHINode *PN = OrigPHINode[i];
281 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
282 Header->getInstList().erase(PN);
285 // At this point, the code is well formed. We now do a quick sweep over the
286 // inserted code, doing constant propagation and dead code elimination as we
288 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks();
289 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
290 E = NewLoopBlocks.end(); BB != E; ++BB)
291 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) {
292 Instruction *Inst = I++;
294 if (isInstructionTriviallyDead(Inst))
295 (*BB)->getInstList().erase(Inst);
296 else if (Constant *C = ConstantFoldInstruction(Inst)) {
297 Inst->replaceAllUsesWith(C);
298 (*BB)->getInstList().erase(Inst);
302 // Update the loop information for this loop.
303 Loop *Parent = L->getParentLoop();
305 // Move all of the basic blocks in the loop into the parent loop.
306 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(),
307 E = NewLoopBlocks.end(); BB != E; ++BB)
308 LI->changeLoopFor(*BB, Parent);
310 // Remove the loop from the parent.
312 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
314 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));