LoopUnroll.cpp revision 2045ce154a69b8f251d3a5259324528f0def337b
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/LoopPass.h" 25#include "llvm/Analysis/ScalarEvolution.h" 26#include "llvm/Support/Debug.h" 27#include "llvm/Support/raw_ostream.h" 28#include "llvm/Transforms/Utils/BasicBlockUtils.h" 29#include "llvm/Transforms/Utils/Cloning.h" 30#include "llvm/Transforms/Utils/Local.h" 31using namespace llvm; 32 33// TODO: Should these be here or in LoopUnroll? 34STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled"); 35STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)"); 36 37/// RemapInstruction - Convert the instruction operands from referencing the 38/// current values into those specified by VMap. 39static inline void RemapInstruction(Instruction *I, 40 ValueToValueMapTy &VMap) { 41 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 42 Value *Op = I->getOperand(op); 43 ValueToValueMapTy::iterator It = VMap.find(Op); 44 if (It != VMap.end()) 45 I->setOperand(op, It->second); 46 } 47 48 if (PHINode *PN = dyn_cast<PHINode>(I)) { 49 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 50 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i)); 51 if (It != VMap.end()) 52 PN->setIncomingBlock(i, cast<BasicBlock>(It->second)); 53 } 54 } 55} 56 57/// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it 58/// only has one predecessor, and that predecessor only has one successor. 59/// The LoopInfo Analysis that is passed will be kept consistent. 60/// Returns the new combined block. 61static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI) { 62 // Merge basic blocks into their predecessor if there is only one distinct 63 // pred, and if there is only one distinct successor of the predecessor, and 64 // if there are no PHI nodes. 65 BasicBlock *OnlyPred = BB->getSinglePredecessor(); 66 if (!OnlyPred) return 0; 67 68 if (OnlyPred->getTerminator()->getNumSuccessors() != 1) 69 return 0; 70 71 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred); 72 73 // Resolve any PHI nodes at the start of the block. They are all 74 // guaranteed to have exactly one entry if they exist, unless there are 75 // multiple duplicate (but guaranteed to be equal) entries for the 76 // incoming edges. This occurs when there are multiple edges from 77 // OnlyPred to OnlySucc. 78 FoldSingleEntryPHINodes(BB); 79 80 // Delete the unconditional branch from the predecessor... 81 OnlyPred->getInstList().pop_back(); 82 83 // Make all PHI nodes that referred to BB now refer to Pred as their 84 // source... 85 BB->replaceAllUsesWith(OnlyPred); 86 87 // Move all definitions in the successor to the predecessor... 88 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList()); 89 90 std::string OldName = BB->getName(); 91 92 // Erase basic block from the function... 93 LI->removeBlock(BB); 94 BB->eraseFromParent(); 95 96 // Inherit predecessor's name if it exists... 97 if (!OldName.empty() && !OnlyPred->hasName()) 98 OnlyPred->setName(OldName); 99 100 return OnlyPred; 101} 102 103/// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true 104/// if unrolling was successful, or false if the loop was unmodified. Unrolling 105/// can only fail when the loop's latch block is not terminated by a conditional 106/// branch instruction. However, if the trip count (and multiple) are not known, 107/// loop unrolling will mostly produce more code that is no faster. 108/// 109/// The LoopInfo Analysis that is passed will be kept consistent. 110/// 111/// If a LoopPassManager is passed in, and the loop is fully removed, it will be 112/// removed from the LoopPassManager as well. LPM can also be NULL. 113bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, 114 unsigned TripMultiple, LoopInfo *LI, LPPassManager *LPM) { 115 BasicBlock *Preheader = L->getLoopPreheader(); 116 if (!Preheader) { 117 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n"); 118 return false; 119 } 120 121 BasicBlock *LatchBlock = L->getLoopLatch(); 122 if (!LatchBlock) { 123 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n"); 124 return false; 125 } 126 127 BasicBlock *Header = L->getHeader(); 128 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 129 130 if (!BI || BI->isUnconditional()) { 131 // The loop-rotate pass can be helpful to avoid this in many cases. 132 DEBUG(dbgs() << 133 " Can't unroll; loop not terminated by a conditional branch.\n"); 134 return false; 135 } 136 137 if (Header->hasAddressTaken()) { 138 // The loop-rotate pass can be helpful to avoid this in many cases. 139 DEBUG(dbgs() << 140 " Won't unroll loop: address of header block is taken.\n"); 141 return false; 142 } 143 144 // Notify ScalarEvolution that the loop will be substantially changed, 145 // if not outright eliminated. 146 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) 147 SE->forgetLoop(L); 148 149 if (TripCount != 0) 150 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n"); 151 if (TripMultiple != 1) 152 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n"); 153 154 // Effectively "DCE" unrolled iterations that are beyond the tripcount 155 // and will never be executed. 156 if (TripCount != 0 && Count > TripCount) 157 Count = TripCount; 158 159 assert(Count > 0); 160 assert(TripMultiple > 0); 161 assert(TripCount == 0 || TripCount % TripMultiple == 0); 162 163 // Are we eliminating the loop control altogether? 164 bool CompletelyUnroll = Count == TripCount; 165 166 // If we know the trip count, we know the multiple... 167 unsigned BreakoutTrip = 0; 168 if (TripCount != 0) { 169 BreakoutTrip = TripCount % Count; 170 TripMultiple = 0; 171 } else { 172 // Figure out what multiple to use. 173 BreakoutTrip = TripMultiple = 174 (unsigned)GreatestCommonDivisor64(Count, TripMultiple); 175 } 176 177 if (CompletelyUnroll) { 178 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName() 179 << " with trip count " << TripCount << "!\n"); 180 } else { 181 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() 182 << " by " << Count); 183 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) { 184 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip); 185 } else if (TripMultiple != 1) { 186 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch"); 187 } 188 DEBUG(dbgs() << "!\n"); 189 } 190 191 std::vector<BasicBlock*> LoopBlocks = L->getBlocks(); 192 193 bool ContinueOnTrue = L->contains(BI->getSuccessor(0)); 194 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue); 195 196 // For the first iteration of the loop, we should use the precloned values for 197 // PHI nodes. Insert associations now. 198 ValueToValueMapTy LastValueMap; 199 std::vector<PHINode*> OrigPHINode; 200 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 201 PHINode *PN = cast<PHINode>(I); 202 OrigPHINode.push_back(PN); 203 if (Instruction *I = 204 dyn_cast<Instruction>(PN->getIncomingValueForBlock(LatchBlock))) 205 if (L->contains(I)) 206 LastValueMap[I] = I; 207 } 208 209 std::vector<BasicBlock*> Headers; 210 std::vector<BasicBlock*> Latches; 211 Headers.push_back(Header); 212 Latches.push_back(LatchBlock); 213 214 for (unsigned It = 1; It != Count; ++It) { 215 std::vector<BasicBlock*> NewBlocks; 216 217 for (std::vector<BasicBlock*>::iterator BB = LoopBlocks.begin(), 218 E = LoopBlocks.end(); BB != E; ++BB) { 219 ValueToValueMapTy VMap; 220 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It)); 221 Header->getParent()->getBasicBlockList().push_back(New); 222 223 // Loop over all of the PHI nodes in the block, changing them to use the 224 // incoming values from the previous block. 225 if (*BB == Header) 226 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 227 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]); 228 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 229 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 230 if (It > 1 && L->contains(InValI)) 231 InVal = LastValueMap[InValI]; 232 VMap[OrigPHINode[i]] = InVal; 233 New->getInstList().erase(NewPHI); 234 } 235 236 // Update our running map of newest clones 237 LastValueMap[*BB] = New; 238 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); 239 VI != VE; ++VI) 240 LastValueMap[VI->first] = VI->second; 241 242 L->addBasicBlockToLoop(New, LI->getBase()); 243 244 // Add phi entries for newly created values to all exit blocks except 245 // the successor of the latch block. The successor of the exit block will 246 // be updated specially after unrolling all the way. 247 if (*BB != LatchBlock) 248 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB); SI != SE; 249 ++SI) 250 if (!L->contains(*SI)) 251 for (BasicBlock::iterator BBI = (*SI)->begin(); 252 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) { 253 Value *Incoming = phi->getIncomingValueForBlock(*BB); 254 phi->addIncoming(Incoming, New); 255 } 256 257 // Keep track of new headers and latches as we create them, so that 258 // we can insert the proper branches later. 259 if (*BB == Header) 260 Headers.push_back(New); 261 if (*BB == LatchBlock) { 262 Latches.push_back(New); 263 264 // Also, clear out the new latch's back edge so that it doesn't look 265 // like a new loop, so that it's amenable to being merged with adjacent 266 // blocks later on. 267 TerminatorInst *Term = New->getTerminator(); 268 assert(L->contains(Term->getSuccessor(!ContinueOnTrue))); 269 assert(Term->getSuccessor(ContinueOnTrue) == LoopExit); 270 Term->setSuccessor(!ContinueOnTrue, NULL); 271 } 272 273 NewBlocks.push_back(New); 274 } 275 276 // Remap all instructions in the most recent iteration 277 for (unsigned i = 0; i < NewBlocks.size(); ++i) 278 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 279 E = NewBlocks[i]->end(); I != E; ++I) 280 ::RemapInstruction(I, LastValueMap); 281 } 282 283 // The latch block exits the loop. If there are any PHI nodes in the 284 // successor blocks, update them to use the appropriate values computed as the 285 // last iteration of the loop. 286 if (Count != 1) { 287 BasicBlock *LastIterationBB = cast<BasicBlock>(LastValueMap[LatchBlock]); 288 for (succ_iterator SI = succ_begin(LatchBlock), SE = succ_end(LatchBlock); 289 SI != SE; ++SI) { 290 for (BasicBlock::iterator BBI = (*SI)->begin(); 291 PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) { 292 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 293 // If this value was defined in the loop, take the value defined by the 294 // last iteration of the loop. 295 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 296 if (L->contains(InValI)) 297 InVal = LastValueMap[InVal]; 298 } 299 PN->addIncoming(InVal, LastIterationBB); 300 } 301 } 302 } 303 304 // Now, if we're doing complete unrolling, loop over the PHI nodes in the 305 // original block, setting them to their incoming values. 306 if (CompletelyUnroll) { 307 BasicBlock *Preheader = L->getLoopPreheader(); 308 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 309 PHINode *PN = OrigPHINode[i]; 310 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 311 Header->getInstList().erase(PN); 312 } 313 } 314 315 // Now that all the basic blocks for the unrolled iterations are in place, 316 // set up the branches to connect them. 317 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 318 // The original branch was replicated in each unrolled iteration. 319 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 320 321 // The branch destination. 322 unsigned j = (i + 1) % e; 323 BasicBlock *Dest = Headers[j]; 324 bool NeedConditional = true; 325 326 // For a complete unroll, make the last iteration end with a branch 327 // to the exit block. 328 if (CompletelyUnroll && j == 0) { 329 Dest = LoopExit; 330 NeedConditional = false; 331 } 332 333 // If we know the trip count or a multiple of it, we can safely use an 334 // unconditional branch for some iterations. 335 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) { 336 NeedConditional = false; 337 } 338 339 if (NeedConditional) { 340 // Update the conditional branch's successor for the following 341 // iteration. 342 Term->setSuccessor(!ContinueOnTrue, Dest); 343 } else { 344 // Replace the conditional branch with an unconditional one. 345 BranchInst::Create(Dest, Term); 346 Term->eraseFromParent(); 347 } 348 } 349 350 // Merge adjacent basic blocks, if possible. 351 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 352 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 353 if (Term->isUnconditional()) { 354 BasicBlock *Dest = Term->getSuccessor(0); 355 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI)) 356 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 357 } 358 } 359 360 // At this point, the code is well formed. We now do a quick sweep over the 361 // inserted code, doing constant propagation and dead code elimination as we 362 // go. 363 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks(); 364 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(), 365 BBE = NewLoopBlocks.end(); BB != BBE; ++BB) 366 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) { 367 Instruction *Inst = I++; 368 369 if (isInstructionTriviallyDead(Inst)) 370 (*BB)->getInstList().erase(Inst); 371 else if (Value *V = SimplifyInstruction(Inst)) 372 if (LI->replacementPreservesLCSSAForm(Inst, V)) { 373 Inst->replaceAllUsesWith(V); 374 (*BB)->getInstList().erase(Inst); 375 } 376 } 377 378 NumCompletelyUnrolled += CompletelyUnroll; 379 ++NumUnrolled; 380 // Remove the loop from the LoopPassManager if it's completely removed. 381 if (CompletelyUnroll && LPM != NULL) 382 LPM->deleteLoopFromQueue(L); 383 384 return true; 385} 386