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 is currently extremely limited. It only currently only unrolls
15 // single basic block loops that execute a constant number of times.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "loop-unroll"
20 #include "llvm/Transforms/Scalar.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "Support/CommandLine.h"
28 #include "Support/Debug.h"
29 #include "Support/Statistic.h"
30 #include "Support/STLExtras.h"
36 Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled");
39 UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden,
40 cl::desc("The cut-off point for loop unrolling"));
42 class LoopUnroll : public FunctionPass {
43 LoopInfo *LI; // The current loop information
45 virtual bool runOnFunction(Function &F);
46 bool visitLoop(Loop *L);
48 /// This transformation requires natural loop information & requires that
49 /// loop preheaders be inserted into the CFG...
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.addRequiredID(LoopSimplifyID);
53 AU.addRequired<LoopInfo>();
54 AU.addPreserved<LoopInfo>();
57 RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops");
60 FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }
62 bool LoopUnroll::runOnFunction(Function &F) {
64 LI = &getAnalysis<LoopInfo>();
66 // Transform all the top-level loops. Copy the loop list so that the child
67 // can update the loop tree if it needs to delete the loop.
68 std::vector<Loop*> SubLoops(LI->begin(), LI->end());
69 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
70 Changed |= visitLoop(SubLoops[i]);
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.
91 // TODO: Ignore expressions derived from PHI and constants if inval of phi
92 // is a constant, or if operation is associative. This will get induction
100 // RemapInstruction - Convert the instruction operands from referencing the
101 // current values into those specified by ValueMap.
103 static inline void RemapInstruction(Instruction *I,
104 std::map<const Value *, Value*> &ValueMap) {
105 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
106 Value *Op = I->getOperand(op);
107 std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
108 if (It != ValueMap.end()) Op = It->second;
109 I->setOperand(op, Op);
113 bool LoopUnroll::visitLoop(Loop *L) {
114 bool Changed = false;
116 // Recurse through all subloops before we process this loop. Copy the loop
117 // list so that the child can update the loop tree if it needs to delete the
119 std::vector<Loop*> SubLoops(L->begin(), L->end());
120 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
121 Changed |= visitLoop(SubLoops[i]);
123 // We only handle single basic block loops right now.
124 if (L->getBlocks().size() != 1)
127 BasicBlock *BB = L->getHeader();
128 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
129 if (BI == 0) return Changed; // Must end in a conditional branch
131 ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount());
132 if (!TripCountC) return Changed; // Must have constant trip count!
134 unsigned TripCount = TripCountC->getRawValue();
135 if (TripCount != TripCountC->getRawValue() || TripCount == 0)
136 return Changed; // More than 2^32 iterations???
138 unsigned LoopSize = ApproximateLoopSize(L);
139 DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName()
140 << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize
141 << " Trip Count = " << TripCount << " - ");
142 if (LoopSize*TripCount > UnrollThreshold) {
143 DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">"
144 << UnrollThreshold << "\n");
147 DEBUG(std::cerr << "UNROLLING!\n");
149 BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0)));
151 // Create a new basic block to temporarily hold all of the cloned code.
152 BasicBlock *NewBlock = new BasicBlock();
154 // For the first iteration of the loop, we should use the precloned values for
155 // PHI nodes. Insert associations now.
156 std::map<const Value*, Value*> LastValueMap;
157 std::vector<PHINode*> OrigPHINode;
158 for (BasicBlock::iterator I = BB->begin();
159 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
160 OrigPHINode.push_back(PN);
161 if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB)))
162 if (I->getParent() == BB)
166 // Remove the exit branch from the loop
167 BB->getInstList().erase(BI);
169 assert(TripCount != 0 && "Trip count of 0 is impossible!");
170 for (unsigned It = 1; It != TripCount; ++It) {
171 char SuffixBuffer[100];
172 sprintf(SuffixBuffer, ".%d", It);
173 std::map<const Value*, Value*> ValueMap;
174 BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer);
176 // Loop over all of the PHI nodes in the block, changing them to use the
177 // incoming values from the previous block.
178 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
179 PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]);
180 Value *InVal = NewPHI->getIncomingValueForBlock(BB);
181 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
182 if (InValI->getParent() == BB)
183 InVal = LastValueMap[InValI];
184 ValueMap[OrigPHINode[i]] = InVal;
185 New->getInstList().erase(NewPHI);
188 for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I)
189 RemapInstruction(I, ValueMap);
191 // Now that all of the instructions are remapped, splice them into the end
193 NewBlock->getInstList().splice(NewBlock->end(), New->getInstList());
196 // LastValue map now contains values from this iteration.
197 std::swap(LastValueMap, ValueMap);
200 // If there was more than one iteration, replace any uses of values computed
201 // in the loop with values computed during the last iteration of the loop.
202 if (TripCount != 1) {
203 std::set<User*> Users;
204 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
205 Users.insert(I->use_begin(), I->use_end());
207 // We don't want to reprocess entries with PHI nodes in them. For this
208 // reason, we look at each operand of each user exactly once, performing the
209 // stubstitution exactly once.
210 for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E;
212 Instruction *I = cast<Instruction>(*UI);
213 if (I->getParent() != BB && I->getParent() != NewBlock)
214 RemapInstruction(I, LastValueMap);
218 // Now that we cloned the block as many times as we needed, stitch the new
219 // code into the original block and delete the temporary block.
220 BB->getInstList().splice(BB->end(), NewBlock->getInstList());
223 // Now loop over the PHI nodes in the original block, setting them to their
225 BasicBlock *Preheader = L->getLoopPreheader();
226 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) {
227 PHINode *PN = OrigPHINode[i];
228 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
229 BB->getInstList().erase(PN);
232 // Finally, add an unconditional branch to the block to continue into the exit
234 new BranchInst(LoopExit, BB);
236 // At this point, the code is well formed. We now do a quick sweep over the
237 // inserted code, doing constant propagation and dead code elimination as we
239 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
240 Instruction *Inst = I++;
242 if (isInstructionTriviallyDead(Inst))
243 BB->getInstList().erase(Inst);
244 else if (Constant *C = ConstantFoldInstruction(Inst)) {
245 Inst->replaceAllUsesWith(C);
246 BB->getInstList().erase(Inst);
250 // Update the loop information for this loop.
251 Loop *Parent = L->getParentLoop();
253 // Move all of the basic blocks in the loop into the parent loop.
254 LI->changeLoopFor(BB, Parent);
256 // Remove the loop from the parent.
258 delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L));
260 delete LI->removeLoop(std::find(LI->begin(), LI->end(), L));
263 // FIXME: Should update dominator analyses
266 // Now that everything is up-to-date that will be, we fold the loop block into
267 // the preheader and exit block, updating our analyses as we go.
268 LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(),
269 BB->getInstList().begin(),
270 prior(BB->getInstList().end()));
271 LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(),
272 Preheader->getInstList().begin(),
273 prior(Preheader->getInstList().end()));
275 // Make all other blocks in the program branch to LoopExit now instead of
277 Preheader->replaceAllUsesWith(LoopExit);
279 // Remove BB and LoopExit from our analyses.
280 LI->removeBlock(Preheader);
283 // If the preheader was the entry block of this function, move the exit block
284 // to be the new entry of the loop.
285 Function *F = LoopExit->getParent();
286 if (Preheader == &F->front())
287 F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit);
289 // Actually delete the blocks now.
290 F->getBasicBlockList().erase(Preheader);
291 F->getBasicBlockList().erase(BB);