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/ADT/Statistic.h" 22 #include "llvm/Analysis/InstructionSimplify.h" 23 #include "llvm/Analysis/LoopIterator.h" 24 #include "llvm/Analysis/LoopPass.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/Dominators.h" 28 #include "llvm/Support/Debug.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 31 #include "llvm/Transforms/Utils/Cloning.h" 32 #include "llvm/Transforms/Utils/Local.h" 33 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 34 using namespace llvm; 35 36 // TODO: Should these be here or in LoopUnroll? 37 STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled"); 38 STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)"); 39 40 /// RemapInstruction - Convert the instruction operands from referencing the 41 /// current values into those specified by VMap. 42 static inline void RemapInstruction(Instruction *I, 43 ValueToValueMapTy &VMap) { 44 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) { 45 Value *Op = I->getOperand(op); 46 ValueToValueMapTy::iterator It = VMap.find(Op); 47 if (It != VMap.end()) 48 I->setOperand(op, It->second); 49 } 50 51 if (PHINode *PN = dyn_cast<PHINode>(I)) { 52 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 53 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i)); 54 if (It != VMap.end()) 55 PN->setIncomingBlock(i, cast<BasicBlock>(It->second)); 56 } 57 } 58 } 59 60 /// FoldBlockIntoPredecessor - Folds a basic block into its predecessor if it 61 /// only has one predecessor, and that predecessor only has one successor. 62 /// The LoopInfo Analysis that is passed will be kept consistent. 63 /// Returns the new combined block. 64 static BasicBlock *FoldBlockIntoPredecessor(BasicBlock *BB, LoopInfo* LI, 65 LPPassManager *LPM) { 66 // Merge basic blocks into their predecessor if there is only one distinct 67 // pred, and if there is only one distinct successor of the predecessor, and 68 // if there are no PHI nodes. 69 BasicBlock *OnlyPred = BB->getSinglePredecessor(); 70 if (!OnlyPred) return 0; 71 72 if (OnlyPred->getTerminator()->getNumSuccessors() != 1) 73 return 0; 74 75 DEBUG(dbgs() << "Merging: " << *BB << "into: " << *OnlyPred); 76 77 // Resolve any PHI nodes at the start of the block. They are all 78 // guaranteed to have exactly one entry if they exist, unless there are 79 // multiple duplicate (but guaranteed to be equal) entries for the 80 // incoming edges. This occurs when there are multiple edges from 81 // OnlyPred to OnlySucc. 82 FoldSingleEntryPHINodes(BB); 83 84 // Delete the unconditional branch from the predecessor... 85 OnlyPred->getInstList().pop_back(); 86 87 // Make all PHI nodes that referred to BB now refer to Pred as their 88 // source... 89 BB->replaceAllUsesWith(OnlyPred); 90 91 // Move all definitions in the successor to the predecessor... 92 OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList()); 93 94 // OldName will be valid until erased. 95 StringRef OldName = BB->getName(); 96 97 // Erase basic block from the function... 98 99 // ScalarEvolution holds references to loop exit blocks. 100 if (LPM) { 101 if (ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>()) { 102 if (Loop *L = LI->getLoopFor(BB)) 103 SE->forgetLoop(L); 104 } 105 } 106 LI->removeBlock(BB); 107 108 // Inherit predecessor's name if it exists... 109 if (!OldName.empty() && !OnlyPred->hasName()) 110 OnlyPred->setName(OldName); 111 112 BB->eraseFromParent(); 113 114 return OnlyPred; 115 } 116 117 /// Unroll the given loop by Count. The loop must be in LCSSA form. Returns true 118 /// if unrolling was successful, or false if the loop was unmodified. Unrolling 119 /// can only fail when the loop's latch block is not terminated by a conditional 120 /// branch instruction. However, if the trip count (and multiple) are not known, 121 /// loop unrolling will mostly produce more code that is no faster. 122 /// 123 /// TripCount is generally defined as the number of times the loop header 124 /// executes. UnrollLoop relaxes the definition to permit early exits: here 125 /// TripCount is the iteration on which control exits LatchBlock if no early 126 /// exits were taken. Note that UnrollLoop assumes that the loop counter test 127 /// terminates LatchBlock in order to remove unnecesssary instances of the 128 /// test. In other words, control may exit the loop prior to TripCount 129 /// iterations via an early branch, but control may not exit the loop from the 130 /// LatchBlock's terminator prior to TripCount iterations. 131 /// 132 /// Similarly, TripMultiple divides the number of times that the LatchBlock may 133 /// execute without exiting the loop. 134 /// 135 /// The LoopInfo Analysis that is passed will be kept consistent. 136 /// 137 /// If a LoopPassManager is passed in, and the loop is fully removed, it will be 138 /// removed from the LoopPassManager as well. LPM can also be NULL. 139 /// 140 /// This utility preserves LoopInfo. If DominatorTree or ScalarEvolution are 141 /// available it must also preserve those analyses. 142 bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount, 143 bool AllowRuntime, unsigned TripMultiple, 144 LoopInfo *LI, LPPassManager *LPM) { 145 BasicBlock *Preheader = L->getLoopPreheader(); 146 if (!Preheader) { 147 DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n"); 148 return false; 149 } 150 151 BasicBlock *LatchBlock = L->getLoopLatch(); 152 if (!LatchBlock) { 153 DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n"); 154 return false; 155 } 156 157 // Loops with indirectbr cannot be cloned. 158 if (!L->isSafeToClone()) { 159 DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n"); 160 return false; 161 } 162 163 BasicBlock *Header = L->getHeader(); 164 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); 165 166 if (!BI || BI->isUnconditional()) { 167 // The loop-rotate pass can be helpful to avoid this in many cases. 168 DEBUG(dbgs() << 169 " Can't unroll; loop not terminated by a conditional branch.\n"); 170 return false; 171 } 172 173 if (Header->hasAddressTaken()) { 174 // The loop-rotate pass can be helpful to avoid this in many cases. 175 DEBUG(dbgs() << 176 " Won't unroll loop: address of header block is taken.\n"); 177 return false; 178 } 179 180 if (TripCount != 0) 181 DEBUG(dbgs() << " Trip Count = " << TripCount << "\n"); 182 if (TripMultiple != 1) 183 DEBUG(dbgs() << " Trip Multiple = " << TripMultiple << "\n"); 184 185 // Effectively "DCE" unrolled iterations that are beyond the tripcount 186 // and will never be executed. 187 if (TripCount != 0 && Count > TripCount) 188 Count = TripCount; 189 190 // Don't enter the unroll code if there is nothing to do. This way we don't 191 // need to support "partial unrolling by 1". 192 if (TripCount == 0 && Count < 2) 193 return false; 194 195 assert(Count > 0); 196 assert(TripMultiple > 0); 197 assert(TripCount == 0 || TripCount % TripMultiple == 0); 198 199 // Are we eliminating the loop control altogether? 200 bool CompletelyUnroll = Count == TripCount; 201 202 // We assume a run-time trip count if the compiler cannot 203 // figure out the loop trip count and the unroll-runtime 204 // flag is specified. 205 bool RuntimeTripCount = (TripCount == 0 && Count > 0 && AllowRuntime); 206 207 if (RuntimeTripCount && !UnrollRuntimeLoopProlog(L, Count, LI, LPM)) 208 return false; 209 210 // Notify ScalarEvolution that the loop will be substantially changed, 211 // if not outright eliminated. 212 if (LPM) { 213 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>(); 214 if (SE) 215 SE->forgetLoop(L); 216 } 217 218 // If we know the trip count, we know the multiple... 219 unsigned BreakoutTrip = 0; 220 if (TripCount != 0) { 221 BreakoutTrip = TripCount % Count; 222 TripMultiple = 0; 223 } else { 224 // Figure out what multiple to use. 225 BreakoutTrip = TripMultiple = 226 (unsigned)GreatestCommonDivisor64(Count, TripMultiple); 227 } 228 229 if (CompletelyUnroll) { 230 DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName() 231 << " with trip count " << TripCount << "!\n"); 232 } else { 233 DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() 234 << " by " << Count); 235 if (TripMultiple == 0 || BreakoutTrip != TripMultiple) { 236 DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip); 237 } else if (TripMultiple != 1) { 238 DEBUG(dbgs() << " with " << TripMultiple << " trips per branch"); 239 } else if (RuntimeTripCount) { 240 DEBUG(dbgs() << " with run-time trip count"); 241 } 242 DEBUG(dbgs() << "!\n"); 243 } 244 245 bool ContinueOnTrue = L->contains(BI->getSuccessor(0)); 246 BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue); 247 248 // For the first iteration of the loop, we should use the precloned values for 249 // PHI nodes. Insert associations now. 250 ValueToValueMapTy LastValueMap; 251 std::vector<PHINode*> OrigPHINode; 252 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 253 OrigPHINode.push_back(cast<PHINode>(I)); 254 } 255 256 std::vector<BasicBlock*> Headers; 257 std::vector<BasicBlock*> Latches; 258 Headers.push_back(Header); 259 Latches.push_back(LatchBlock); 260 261 // The current on-the-fly SSA update requires blocks to be processed in 262 // reverse postorder so that LastValueMap contains the correct value at each 263 // exit. 264 LoopBlocksDFS DFS(L); 265 DFS.perform(LI); 266 267 // Stash the DFS iterators before adding blocks to the loop. 268 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO(); 269 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO(); 270 271 for (unsigned It = 1; It != Count; ++It) { 272 std::vector<BasicBlock*> NewBlocks; 273 274 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 275 ValueToValueMapTy VMap; 276 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It)); 277 Header->getParent()->getBasicBlockList().push_back(New); 278 279 // Loop over all of the PHI nodes in the block, changing them to use the 280 // incoming values from the previous block. 281 if (*BB == Header) 282 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 283 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHINode[i]]); 284 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock); 285 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) 286 if (It > 1 && L->contains(InValI)) 287 InVal = LastValueMap[InValI]; 288 VMap[OrigPHINode[i]] = InVal; 289 New->getInstList().erase(NewPHI); 290 } 291 292 // Update our running map of newest clones 293 LastValueMap[*BB] = New; 294 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); 295 VI != VE; ++VI) 296 LastValueMap[VI->first] = VI->second; 297 298 L->addBasicBlockToLoop(New, LI->getBase()); 299 300 // Add phi entries for newly created values to all exit blocks. 301 for (succ_iterator SI = succ_begin(*BB), SE = succ_end(*BB); 302 SI != SE; ++SI) { 303 if (L->contains(*SI)) 304 continue; 305 for (BasicBlock::iterator BBI = (*SI)->begin(); 306 PHINode *phi = dyn_cast<PHINode>(BBI); ++BBI) { 307 Value *Incoming = phi->getIncomingValueForBlock(*BB); 308 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming); 309 if (It != LastValueMap.end()) 310 Incoming = It->second; 311 phi->addIncoming(Incoming, New); 312 } 313 } 314 // Keep track of new headers and latches as we create them, so that 315 // we can insert the proper branches later. 316 if (*BB == Header) 317 Headers.push_back(New); 318 if (*BB == LatchBlock) 319 Latches.push_back(New); 320 321 NewBlocks.push_back(New); 322 } 323 324 // Remap all instructions in the most recent iteration 325 for (unsigned i = 0; i < NewBlocks.size(); ++i) 326 for (BasicBlock::iterator I = NewBlocks[i]->begin(), 327 E = NewBlocks[i]->end(); I != E; ++I) 328 ::RemapInstruction(I, LastValueMap); 329 } 330 331 // Loop over the PHI nodes in the original block, setting incoming values. 332 for (unsigned i = 0, e = OrigPHINode.size(); i != e; ++i) { 333 PHINode *PN = OrigPHINode[i]; 334 if (CompletelyUnroll) { 335 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader)); 336 Header->getInstList().erase(PN); 337 } 338 else if (Count > 1) { 339 Value *InVal = PN->removeIncomingValue(LatchBlock, false); 340 // If this value was defined in the loop, take the value defined by the 341 // last iteration of the loop. 342 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) { 343 if (L->contains(InValI)) 344 InVal = LastValueMap[InVal]; 345 } 346 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch"); 347 PN->addIncoming(InVal, Latches.back()); 348 } 349 } 350 351 // Now that all the basic blocks for the unrolled iterations are in place, 352 // set up the branches to connect them. 353 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 354 // The original branch was replicated in each unrolled iteration. 355 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 356 357 // The branch destination. 358 unsigned j = (i + 1) % e; 359 BasicBlock *Dest = Headers[j]; 360 bool NeedConditional = true; 361 362 if (RuntimeTripCount && j != 0) { 363 NeedConditional = false; 364 } 365 366 // For a complete unroll, make the last iteration end with a branch 367 // to the exit block. 368 if (CompletelyUnroll && j == 0) { 369 Dest = LoopExit; 370 NeedConditional = false; 371 } 372 373 // If we know the trip count or a multiple of it, we can safely use an 374 // unconditional branch for some iterations. 375 if (j != BreakoutTrip && (TripMultiple == 0 || j % TripMultiple != 0)) { 376 NeedConditional = false; 377 } 378 379 if (NeedConditional) { 380 // Update the conditional branch's successor for the following 381 // iteration. 382 Term->setSuccessor(!ContinueOnTrue, Dest); 383 } else { 384 // Remove phi operands at this loop exit 385 if (Dest != LoopExit) { 386 BasicBlock *BB = Latches[i]; 387 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); 388 SI != SE; ++SI) { 389 if (*SI == Headers[i]) 390 continue; 391 for (BasicBlock::iterator BBI = (*SI)->begin(); 392 PHINode *Phi = dyn_cast<PHINode>(BBI); ++BBI) { 393 Phi->removeIncomingValue(BB, false); 394 } 395 } 396 } 397 // Replace the conditional branch with an unconditional one. 398 BranchInst::Create(Dest, Term); 399 Term->eraseFromParent(); 400 } 401 } 402 403 // Merge adjacent basic blocks, if possible. 404 for (unsigned i = 0, e = Latches.size(); i != e; ++i) { 405 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator()); 406 if (Term->isUnconditional()) { 407 BasicBlock *Dest = Term->getSuccessor(0); 408 if (BasicBlock *Fold = FoldBlockIntoPredecessor(Dest, LI, LPM)) 409 std::replace(Latches.begin(), Latches.end(), Dest, Fold); 410 } 411 } 412 413 if (LPM) { 414 // FIXME: Reconstruct dom info, because it is not preserved properly. 415 // Incrementally updating domtree after loop unrolling would be easy. 416 if (DominatorTreeWrapperPass *DTWP = 417 LPM->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) 418 DTWP->getDomTree().recalculate(*L->getHeader()->getParent()); 419 420 // Simplify any new induction variables in the partially unrolled loop. 421 ScalarEvolution *SE = LPM->getAnalysisIfAvailable<ScalarEvolution>(); 422 if (SE && !CompletelyUnroll) { 423 SmallVector<WeakVH, 16> DeadInsts; 424 simplifyLoopIVs(L, SE, LPM, DeadInsts); 425 426 // Aggressively clean up dead instructions that simplifyLoopIVs already 427 // identified. Any remaining should be cleaned up below. 428 while (!DeadInsts.empty()) 429 if (Instruction *Inst = 430 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val())) 431 RecursivelyDeleteTriviallyDeadInstructions(Inst); 432 } 433 } 434 // At this point, the code is well formed. We now do a quick sweep over the 435 // inserted code, doing constant propagation and dead code elimination as we 436 // go. 437 const std::vector<BasicBlock*> &NewLoopBlocks = L->getBlocks(); 438 for (std::vector<BasicBlock*>::const_iterator BB = NewLoopBlocks.begin(), 439 BBE = NewLoopBlocks.end(); BB != BBE; ++BB) 440 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ) { 441 Instruction *Inst = I++; 442 443 if (isInstructionTriviallyDead(Inst)) 444 (*BB)->getInstList().erase(Inst); 445 else if (Value *V = SimplifyInstruction(Inst)) 446 if (LI->replacementPreservesLCSSAForm(Inst, V)) { 447 Inst->replaceAllUsesWith(V); 448 (*BB)->getInstList().erase(Inst); 449 } 450 } 451 452 NumCompletelyUnrolled += CompletelyUnroll; 453 ++NumUnrolled; 454 // Remove the loop from the LoopPassManager if it's completely removed. 455 if (CompletelyUnroll && LPM != NULL) 456 LPM->deleteLoopFromQueue(L); 457 458 return true; 459 } 460