Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 1 | //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 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. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 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. |
| 13 | // |
| 14 | // This pass is currently extremely limited. It only currently only unrolls |
| 15 | // single basic block loops that execute a constant number of times. |
| 16 | // |
| 17 | //===----------------------------------------------------------------------===// |
| 18 | |
| 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" |
Chris Lattner | 50ca0a1 | 2004-04-18 06:27:43 +0000 | [diff] [blame] | 30 | #include "Support/STLExtras.h" |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 31 | #include <cstdio> |
| 32 | using namespace llvm; |
| 33 | |
| 34 | namespace { |
| 35 | Statistic<> NumUnrolled("loop-unroll", "Number of loops completely unrolled"); |
| 36 | |
| 37 | cl::opt<unsigned> |
Chris Lattner | e3a5586 | 2004-04-18 18:06:14 +0000 | [diff] [blame] | 38 | UnrollThreshold("unroll-threshold", cl::init(100), cl::Hidden, |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 39 | cl::desc("The cut-off point for loop unrolling")); |
| 40 | |
| 41 | class LoopUnroll : public FunctionPass { |
| 42 | LoopInfo *LI; // The current loop information |
| 43 | public: |
| 44 | virtual bool runOnFunction(Function &F); |
| 45 | bool visitLoop(Loop *L); |
| 46 | |
| 47 | /// This transformation requires natural loop information & requires that |
| 48 | /// loop preheaders be inserted into the CFG... |
| 49 | /// |
| 50 | virtual void getAnalysisUsage(AnalysisUsage &AU) const { |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 51 | AU.addRequiredID(LoopSimplifyID); |
| 52 | AU.addRequired<LoopInfo>(); |
Chris Lattner | 9c2cc46 | 2004-04-18 05:38:37 +0000 | [diff] [blame] | 53 | AU.addPreserved<LoopInfo>(); |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 54 | } |
| 55 | }; |
| 56 | RegisterOpt<LoopUnroll> X("loop-unroll", "Unroll loops"); |
| 57 | } |
| 58 | |
| 59 | FunctionPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); } |
| 60 | |
| 61 | bool LoopUnroll::runOnFunction(Function &F) { |
| 62 | bool Changed = false; |
| 63 | LI = &getAnalysis<LoopInfo>(); |
| 64 | |
Chris Lattner | 9c2cc46 | 2004-04-18 05:38:37 +0000 | [diff] [blame] | 65 | // Transform all the top-level loops. Copy the loop list so that the child |
| 66 | // can update the loop tree if it needs to delete the loop. |
| 67 | std::vector<Loop*> SubLoops(LI->begin(), LI->end()); |
| 68 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 69 | Changed |= visitLoop(SubLoops[i]); |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 70 | |
| 71 | return Changed; |
| 72 | } |
| 73 | |
| 74 | /// ApproximateLoopSize - Approximate the size of the loop after it has been |
| 75 | /// unrolled. |
| 76 | static unsigned ApproximateLoopSize(const Loop *L) { |
| 77 | unsigned Size = 0; |
| 78 | for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) { |
| 79 | BasicBlock *BB = L->getBlocks()[i]; |
| 80 | Instruction *Term = BB->getTerminator(); |
| 81 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { |
| 82 | if (isa<PHINode>(I) && BB == L->getHeader()) { |
| 83 | // Ignore PHI nodes in the header. |
| 84 | } else if (I->hasOneUse() && I->use_back() == Term) { |
| 85 | // Ignore instructions only used by the loop terminator. |
| 86 | } else { |
| 87 | ++Size; |
| 88 | } |
| 89 | |
| 90 | // TODO: Ignore expressions derived from PHI and constants if inval of phi |
| 91 | // is a constant, or if operation is associative. This will get induction |
| 92 | // variables. |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | return Size; |
| 97 | } |
| 98 | |
| 99 | // RemapInstruction - Convert the instruction operands from referencing the |
| 100 | // current values into those specified by ValueMap. |
| 101 | // |
| 102 | static inline void RemapInstruction(Instruction *I, |
| 103 | std::map<const Value *, Value*> &ValueMap) { |
| 104 | for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { |
| 105 | Value *Op = I->getOperand(op); |
| 106 | std::map<const Value *, Value*>::iterator It = ValueMap.find(Op); |
| 107 | if (It != ValueMap.end()) Op = It->second; |
| 108 | I->setOperand(op, Op); |
| 109 | } |
| 110 | } |
| 111 | |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 112 | bool LoopUnroll::visitLoop(Loop *L) { |
| 113 | bool Changed = false; |
| 114 | |
| 115 | // Recurse through all subloops before we process this loop. Copy the loop |
| 116 | // list so that the child can update the loop tree if it needs to delete the |
| 117 | // loop. |
| 118 | std::vector<Loop*> SubLoops(L->begin(), L->end()); |
| 119 | for (unsigned i = 0, e = SubLoops.size(); i != e; ++i) |
| 120 | Changed |= visitLoop(SubLoops[i]); |
| 121 | |
| 122 | // We only handle single basic block loops right now. |
| 123 | if (L->getBlocks().size() != 1) |
| 124 | return Changed; |
| 125 | |
| 126 | BasicBlock *BB = L->getHeader(); |
| 127 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 128 | if (BI == 0) return Changed; // Must end in a conditional branch |
| 129 | |
| 130 | ConstantInt *TripCountC = dyn_cast_or_null<ConstantInt>(L->getTripCount()); |
| 131 | if (!TripCountC) return Changed; // Must have constant trip count! |
| 132 | |
| 133 | unsigned TripCount = TripCountC->getRawValue(); |
| 134 | if (TripCount != TripCountC->getRawValue()) |
| 135 | return Changed; // More than 2^32 iterations??? |
| 136 | |
| 137 | unsigned LoopSize = ApproximateLoopSize(L); |
| 138 | DEBUG(std::cerr << "Loop Unroll: F[" << BB->getParent()->getName() |
| 139 | << "] Loop %" << BB->getName() << " Loop Size = " << LoopSize |
| 140 | << " Trip Count = " << TripCount << " - "); |
| 141 | if (LoopSize*TripCount > UnrollThreshold) { |
| 142 | DEBUG(std::cerr << "TOO LARGE: " << LoopSize*TripCount << ">" |
| 143 | << UnrollThreshold << "\n"); |
| 144 | return Changed; |
| 145 | } |
| 146 | DEBUG(std::cerr << "UNROLLING!\n"); |
| 147 | |
Chris Lattner | f1ab4b4 | 2004-04-18 22:14:10 +0000 | [diff] [blame^] | 148 | BasicBlock *LoopExit = BI->getSuccessor(L->contains(BI->getSuccessor(0))); |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 149 | |
| 150 | // Create a new basic block to temporarily hold all of the cloned code. |
| 151 | BasicBlock *NewBlock = new BasicBlock(); |
| 152 | |
| 153 | // For the first iteration of the loop, we should use the precloned values for |
| 154 | // PHI nodes. Insert associations now. |
| 155 | std::map<const Value*, Value*> LastValueMap; |
| 156 | std::vector<PHINode*> OrigPHINode; |
| 157 | for (BasicBlock::iterator I = BB->begin(); |
| 158 | PHINode *PN = dyn_cast<PHINode>(I); ++I) { |
| 159 | OrigPHINode.push_back(PN); |
| 160 | if (Instruction *I =dyn_cast<Instruction>(PN->getIncomingValueForBlock(BB))) |
| 161 | if (I->getParent() == BB) |
| 162 | LastValueMap[I] = I; |
| 163 | } |
| 164 | |
| 165 | // Remove the exit branch from the loop |
| 166 | BB->getInstList().erase(BI); |
| 167 | |
| 168 | assert(TripCount != 0 && "Trip count of 0 is impossible!"); |
| 169 | for (unsigned It = 1; It != TripCount; ++It) { |
| 170 | char SuffixBuffer[100]; |
| 171 | sprintf(SuffixBuffer, ".%d", It); |
| 172 | std::map<const Value*, Value*> ValueMap; |
| 173 | BasicBlock *New = CloneBasicBlock(BB, ValueMap, SuffixBuffer); |
| 174 | |
| 175 | // Loop over all of the PHI nodes in the block, changing them to use the |
| 176 | // incoming values from the previous block. |
| 177 | for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { |
| 178 | PHINode *NewPHI = cast<PHINode>(ValueMap[OrigPHINode[i]]); |
| 179 | Value *InVal = NewPHI->getIncomingValueForBlock(BB); |
| 180 | if (Instruction *InValI = dyn_cast<Instruction>(InVal)) |
| 181 | if (InValI->getParent() == BB) |
| 182 | InVal = LastValueMap[InValI]; |
| 183 | ValueMap[OrigPHINode[i]] = InVal; |
| 184 | New->getInstList().erase(NewPHI); |
| 185 | } |
| 186 | |
| 187 | for (BasicBlock::iterator I = New->begin(), E = New->end(); I != E; ++I) |
| 188 | RemapInstruction(I, ValueMap); |
| 189 | |
| 190 | // Now that all of the instructions are remapped, splice them into the end |
| 191 | // of the NewBlock. |
| 192 | NewBlock->getInstList().splice(NewBlock->end(), New->getInstList()); |
| 193 | delete New; |
| 194 | |
| 195 | // LastValue map now contains values from this iteration. |
| 196 | std::swap(LastValueMap, ValueMap); |
| 197 | } |
| 198 | |
| 199 | // If there was more than one iteration, replace any uses of values computed |
Chris Lattner | 998f44f | 2004-04-18 17:32:39 +0000 | [diff] [blame] | 200 | // in the loop with values computed during the last iteration of the loop. |
| 201 | if (TripCount != 1) { |
| 202 | std::set<User*> Users; |
| 203 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) |
| 204 | Users.insert(I->use_begin(), I->use_end()); |
| 205 | |
| 206 | // We don't want to reprocess entries with PHI nodes in them. For this |
| 207 | // reason, we look at each operand of each user exactly once, performing the |
| 208 | // stubstitution exactly once. |
| 209 | for (std::set<User*>::iterator UI = Users.begin(), E = Users.end(); UI != E; |
| 210 | ++UI) { |
| 211 | Instruction *I = cast<Instruction>(*UI); |
| 212 | if (I->getParent() != BB && I->getParent() != NewBlock) |
| 213 | RemapInstruction(I, LastValueMap); |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 214 | } |
Chris Lattner | 998f44f | 2004-04-18 17:32:39 +0000 | [diff] [blame] | 215 | } |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 216 | |
| 217 | // Now that we cloned the block as many times as we needed, stitch the new |
| 218 | // code into the original block and delete the temporary block. |
| 219 | BB->getInstList().splice(BB->end(), NewBlock->getInstList()); |
| 220 | delete NewBlock; |
| 221 | |
| 222 | // Now loop over the PHI nodes in the original block, setting them to their |
| 223 | // incoming values. |
| 224 | BasicBlock *Preheader = L->getLoopPreheader(); |
| 225 | for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { |
| 226 | PHINode *PN = OrigPHINode[i]; |
| 227 | PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); |
| 228 | BB->getInstList().erase(PN); |
| 229 | } |
| 230 | |
| 231 | // Finally, add an unconditional branch to the block to continue into the exit |
| 232 | // block. |
| 233 | new BranchInst(LoopExit, BB); |
| 234 | |
| 235 | // At this point, the code is well formed. We now do a quick sweep over the |
| 236 | // inserted code, doing constant propagation and dead code elimination as we |
| 237 | // go. |
| 238 | for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) { |
| 239 | Instruction *Inst = I++; |
| 240 | |
| 241 | if (isInstructionTriviallyDead(Inst)) |
| 242 | BB->getInstList().erase(Inst); |
| 243 | else if (Constant *C = ConstantFoldInstruction(Inst)) { |
| 244 | Inst->replaceAllUsesWith(C); |
| 245 | BB->getInstList().erase(Inst); |
| 246 | } |
| 247 | } |
| 248 | |
Chris Lattner | 9c2cc46 | 2004-04-18 05:38:37 +0000 | [diff] [blame] | 249 | // Update the loop information for this loop. |
| 250 | Loop *Parent = L->getParentLoop(); |
| 251 | |
| 252 | // Move all of the basic blocks in the loop into the parent loop. |
| 253 | LI->changeLoopFor(BB, Parent); |
| 254 | |
| 255 | // Remove the loop from the parent. |
| 256 | if (Parent) |
| 257 | delete Parent->removeChildLoop(std::find(Parent->begin(), Parent->end(),L)); |
| 258 | else |
| 259 | delete LI->removeLoop(std::find(LI->begin(), LI->end(), L)); |
| 260 | |
| 261 | |
| 262 | // FIXME: Should update dominator analyses |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 263 | |
Chris Lattner | 50ca0a1 | 2004-04-18 06:27:43 +0000 | [diff] [blame] | 264 | |
| 265 | // Now that everything is up-to-date that will be, we fold the loop block into |
| 266 | // the preheader and exit block, updating our analyses as we go. |
| 267 | LoopExit->getInstList().splice(LoopExit->begin(), BB->getInstList(), |
| 268 | BB->getInstList().begin(), |
| 269 | prior(BB->getInstList().end())); |
| 270 | LoopExit->getInstList().splice(LoopExit->begin(), Preheader->getInstList(), |
| 271 | Preheader->getInstList().begin(), |
| 272 | prior(Preheader->getInstList().end())); |
| 273 | |
| 274 | // Make all other blocks in the program branch to LoopExit now instead of |
| 275 | // Preheader. |
| 276 | Preheader->replaceAllUsesWith(LoopExit); |
| 277 | |
| 278 | // Remove BB and LoopExit from our analyses. |
| 279 | LI->removeBlock(Preheader); |
| 280 | LI->removeBlock(BB); |
| 281 | |
Chris Lattner | cc43909 | 2004-04-18 17:38:42 +0000 | [diff] [blame] | 282 | // If the preheader was the entry block of this function, move the exit block |
| 283 | // to be the new entry of the loop. |
| 284 | Function *F = LoopExit->getParent(); |
| 285 | if (Preheader == &F->front()) |
| 286 | F->getBasicBlockList().splice(F->begin(), F->getBasicBlockList(), LoopExit); |
Chris Lattner | 50ca0a1 | 2004-04-18 06:27:43 +0000 | [diff] [blame] | 287 | |
| 288 | // Actually delete the blocks now. |
Chris Lattner | cc43909 | 2004-04-18 17:38:42 +0000 | [diff] [blame] | 289 | F->getBasicBlockList().erase(Preheader); |
| 290 | F->getBasicBlockList().erase(BB); |
Chris Lattner | 83bf288 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 291 | |
| 292 | ++NumUnrolled; |
| 293 | return true; |
| 294 | } |