1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===// 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 pass performs several transformations to transform natural loops into a 11 // simpler form, which makes subsequent analyses and transformations simpler and 12 // more effective. 13 // 14 // Loop pre-header insertion guarantees that there is a single, non-critical 15 // entry edge from outside of the loop to the loop header. This simplifies a 16 // number of analyses and transformations, such as LICM. 17 // 18 // Loop exit-block insertion guarantees that all exit blocks from the loop 19 // (blocks which are outside of the loop that have predecessors inside of the 20 // loop) only have predecessors from inside of the loop (and are thus dominated 21 // by the loop header). This simplifies transformations such as store-sinking 22 // that are built into LICM. 23 // 24 // This pass also guarantees that loops will have exactly one backedge. 25 // 26 // Indirectbr instructions introduce several complications. If the loop 27 // contains or is entered by an indirectbr instruction, it may not be possible 28 // to transform the loop and make these guarantees. Client code should check 29 // that these conditions are true before relying on them. 30 // 31 // Note that the simplifycfg pass will clean up blocks which are split out but 32 // end up being unnecessary, so usage of this pass should not pessimize 33 // generated code. 34 // 35 // This pass obviously modifies the CFG, but updates loop information and 36 // dominator information. 37 // 38 //===----------------------------------------------------------------------===// 39 40 #include "llvm/Transforms/Scalar.h" 41 #include "llvm/ADT/DepthFirstIterator.h" 42 #include "llvm/ADT/SetOperations.h" 43 #include "llvm/ADT/SetVector.h" 44 #include "llvm/ADT/SmallVector.h" 45 #include "llvm/ADT/Statistic.h" 46 #include "llvm/Analysis/AliasAnalysis.h" 47 #include "llvm/Analysis/DependenceAnalysis.h" 48 #include "llvm/Analysis/InstructionSimplify.h" 49 #include "llvm/Analysis/LoopInfo.h" 50 #include "llvm/Analysis/ScalarEvolution.h" 51 #include "llvm/IR/CFG.h" 52 #include "llvm/IR/Constants.h" 53 #include "llvm/IR/DataLayout.h" 54 #include "llvm/IR/Dominators.h" 55 #include "llvm/IR/Function.h" 56 #include "llvm/IR/Instructions.h" 57 #include "llvm/IR/IntrinsicInst.h" 58 #include "llvm/IR/LLVMContext.h" 59 #include "llvm/IR/Type.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 62 #include "llvm/Transforms/Utils/Local.h" 63 #include "llvm/Transforms/Utils/LoopUtils.h" 64 using namespace llvm; 65 66 #define DEBUG_TYPE "loop-simplify" 67 68 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted"); 69 STATISTIC(NumNested , "Number of nested loops split out"); 70 71 // If the block isn't already, move the new block to right after some 'outside 72 // block' block. This prevents the preheader from being placed inside the loop 73 // body, e.g. when the loop hasn't been rotated. 74 static void placeSplitBlockCarefully(BasicBlock *NewBB, 75 SmallVectorImpl<BasicBlock *> &SplitPreds, 76 Loop *L) { 77 // Check to see if NewBB is already well placed. 78 Function::iterator BBI = NewBB; --BBI; 79 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) { 80 if (&*BBI == SplitPreds[i]) 81 return; 82 } 83 84 // If it isn't already after an outside block, move it after one. This is 85 // always good as it makes the uncond branch from the outside block into a 86 // fall-through. 87 88 // Figure out *which* outside block to put this after. Prefer an outside 89 // block that neighbors a BB actually in the loop. 90 BasicBlock *FoundBB = nullptr; 91 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) { 92 Function::iterator BBI = SplitPreds[i]; 93 if (++BBI != NewBB->getParent()->end() && 94 L->contains(BBI)) { 95 FoundBB = SplitPreds[i]; 96 break; 97 } 98 } 99 100 // If our heuristic for a *good* bb to place this after doesn't find 101 // anything, just pick something. It's likely better than leaving it within 102 // the loop. 103 if (!FoundBB) 104 FoundBB = SplitPreds[0]; 105 NewBB->moveAfter(FoundBB); 106 } 107 108 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a 109 /// preheader, this method is called to insert one. This method has two phases: 110 /// preheader insertion and analysis updating. 111 /// 112 BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, Pass *PP) { 113 BasicBlock *Header = L->getHeader(); 114 115 // Compute the set of predecessors of the loop that are not in the loop. 116 SmallVector<BasicBlock*, 8> OutsideBlocks; 117 for (BasicBlock *P : predecessors(Header)) { 118 if (!L->contains(P)) { // Coming in from outside the loop? 119 // If the loop is branched to from an indirect branch, we won't 120 // be able to fully transform the loop, because it prohibits 121 // edge splitting. 122 if (isa<IndirectBrInst>(P->getTerminator())) return nullptr; 123 124 // Keep track of it. 125 OutsideBlocks.push_back(P); 126 } 127 } 128 129 // Split out the loop pre-header. 130 BasicBlock *PreheaderBB; 131 if (!Header->isLandingPad()) { 132 PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader", 133 PP); 134 } else { 135 SmallVector<BasicBlock*, 2> NewBBs; 136 SplitLandingPadPredecessors(Header, OutsideBlocks, ".preheader", 137 ".split-lp", PP, NewBBs); 138 PreheaderBB = NewBBs[0]; 139 } 140 141 PreheaderBB->getTerminator()->setDebugLoc( 142 Header->getFirstNonPHI()->getDebugLoc()); 143 DEBUG(dbgs() << "LoopSimplify: Creating pre-header " 144 << PreheaderBB->getName() << "\n"); 145 146 // Make sure that NewBB is put someplace intelligent, which doesn't mess up 147 // code layout too horribly. 148 placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L); 149 150 return PreheaderBB; 151 } 152 153 /// \brief Ensure that the loop preheader dominates all exit blocks. 154 /// 155 /// This method is used to split exit blocks that have predecessors outside of 156 /// the loop. 157 static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit, Pass *PP) { 158 SmallVector<BasicBlock*, 8> LoopBlocks; 159 for (BasicBlock *P : predecessors(Exit)) { 160 if (L->contains(P)) { 161 // Don't do this if the loop is exited via an indirect branch. 162 if (isa<IndirectBrInst>(P->getTerminator())) return nullptr; 163 164 LoopBlocks.push_back(P); 165 } 166 } 167 168 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?"); 169 BasicBlock *NewExitBB = nullptr; 170 171 if (Exit->isLandingPad()) { 172 SmallVector<BasicBlock*, 2> NewBBs; 173 SplitLandingPadPredecessors(Exit, ArrayRef<BasicBlock*>(&LoopBlocks[0], 174 LoopBlocks.size()), 175 ".loopexit", ".nonloopexit", 176 PP, NewBBs); 177 NewExitBB = NewBBs[0]; 178 } else { 179 NewExitBB = SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", PP); 180 } 181 182 DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " 183 << NewExitBB->getName() << "\n"); 184 return NewExitBB; 185 } 186 187 /// Add the specified block, and all of its predecessors, to the specified set, 188 /// if it's not already in there. Stop predecessor traversal when we reach 189 /// StopBlock. 190 static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock, 191 std::set<BasicBlock*> &Blocks) { 192 SmallVector<BasicBlock *, 8> Worklist; 193 Worklist.push_back(InputBB); 194 do { 195 BasicBlock *BB = Worklist.pop_back_val(); 196 if (Blocks.insert(BB).second && BB != StopBlock) 197 // If BB is not already processed and it is not a stop block then 198 // insert its predecessor in the work list 199 for (BasicBlock *WBB : predecessors(BB)) 200 Worklist.push_back(WBB); 201 } while (!Worklist.empty()); 202 } 203 204 /// \brief The first part of loop-nestification is to find a PHI node that tells 205 /// us how to partition the loops. 206 static PHINode *findPHIToPartitionLoops(Loop *L, AliasAnalysis *AA, 207 DominatorTree *DT) { 208 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) { 209 PHINode *PN = cast<PHINode>(I); 210 ++I; 211 if (Value *V = SimplifyInstruction(PN, nullptr, nullptr, DT)) { 212 // This is a degenerate PHI already, don't modify it! 213 PN->replaceAllUsesWith(V); 214 if (AA) AA->deleteValue(PN); 215 PN->eraseFromParent(); 216 continue; 217 } 218 219 // Scan this PHI node looking for a use of the PHI node by itself. 220 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 221 if (PN->getIncomingValue(i) == PN && 222 L->contains(PN->getIncomingBlock(i))) 223 // We found something tasty to remove. 224 return PN; 225 } 226 return nullptr; 227 } 228 229 /// \brief If this loop has multiple backedges, try to pull one of them out into 230 /// a nested loop. 231 /// 232 /// This is important for code that looks like 233 /// this: 234 /// 235 /// Loop: 236 /// ... 237 /// br cond, Loop, Next 238 /// ... 239 /// br cond2, Loop, Out 240 /// 241 /// To identify this common case, we look at the PHI nodes in the header of the 242 /// loop. PHI nodes with unchanging values on one backedge correspond to values 243 /// that change in the "outer" loop, but not in the "inner" loop. 244 /// 245 /// If we are able to separate out a loop, return the new outer loop that was 246 /// created. 247 /// 248 static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader, 249 AliasAnalysis *AA, DominatorTree *DT, 250 LoopInfo *LI, ScalarEvolution *SE, Pass *PP) { 251 // Don't try to separate loops without a preheader. 252 if (!Preheader) 253 return nullptr; 254 255 // The header is not a landing pad; preheader insertion should ensure this. 256 assert(!L->getHeader()->isLandingPad() && 257 "Can't insert backedge to landing pad"); 258 259 PHINode *PN = findPHIToPartitionLoops(L, AA, DT); 260 if (!PN) return nullptr; // No known way to partition. 261 262 // Pull out all predecessors that have varying values in the loop. This 263 // handles the case when a PHI node has multiple instances of itself as 264 // arguments. 265 SmallVector<BasicBlock*, 8> OuterLoopPreds; 266 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 267 if (PN->getIncomingValue(i) != PN || 268 !L->contains(PN->getIncomingBlock(i))) { 269 // We can't split indirectbr edges. 270 if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator())) 271 return nullptr; 272 OuterLoopPreds.push_back(PN->getIncomingBlock(i)); 273 } 274 } 275 DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n"); 276 277 // If ScalarEvolution is around and knows anything about values in 278 // this loop, tell it to forget them, because we're about to 279 // substantially change it. 280 if (SE) 281 SE->forgetLoop(L); 282 283 BasicBlock *Header = L->getHeader(); 284 BasicBlock *NewBB = 285 SplitBlockPredecessors(Header, OuterLoopPreds, ".outer", PP); 286 287 // Make sure that NewBB is put someplace intelligent, which doesn't mess up 288 // code layout too horribly. 289 placeSplitBlockCarefully(NewBB, OuterLoopPreds, L); 290 291 // Create the new outer loop. 292 Loop *NewOuter = new Loop(); 293 294 // Change the parent loop to use the outer loop as its child now. 295 if (Loop *Parent = L->getParentLoop()) 296 Parent->replaceChildLoopWith(L, NewOuter); 297 else 298 LI->changeTopLevelLoop(L, NewOuter); 299 300 // L is now a subloop of our outer loop. 301 NewOuter->addChildLoop(L); 302 303 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 304 I != E; ++I) 305 NewOuter->addBlockEntry(*I); 306 307 // Now reset the header in L, which had been moved by 308 // SplitBlockPredecessors for the outer loop. 309 L->moveToHeader(Header); 310 311 // Determine which blocks should stay in L and which should be moved out to 312 // the Outer loop now. 313 std::set<BasicBlock*> BlocksInL; 314 for (BasicBlock *P : predecessors(Header)) { 315 if (DT->dominates(Header, P)) 316 addBlockAndPredsToSet(P, Header, BlocksInL); 317 } 318 319 // Scan all of the loop children of L, moving them to OuterLoop if they are 320 // not part of the inner loop. 321 const std::vector<Loop*> &SubLoops = L->getSubLoops(); 322 for (size_t I = 0; I != SubLoops.size(); ) 323 if (BlocksInL.count(SubLoops[I]->getHeader())) 324 ++I; // Loop remains in L 325 else 326 NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I)); 327 328 // Now that we know which blocks are in L and which need to be moved to 329 // OuterLoop, move any blocks that need it. 330 for (unsigned i = 0; i != L->getBlocks().size(); ++i) { 331 BasicBlock *BB = L->getBlocks()[i]; 332 if (!BlocksInL.count(BB)) { 333 // Move this block to the parent, updating the exit blocks sets 334 L->removeBlockFromLoop(BB); 335 if ((*LI)[BB] == L) 336 LI->changeLoopFor(BB, NewOuter); 337 --i; 338 } 339 } 340 341 return NewOuter; 342 } 343 344 /// \brief This method is called when the specified loop has more than one 345 /// backedge in it. 346 /// 347 /// If this occurs, revector all of these backedges to target a new basic block 348 /// and have that block branch to the loop header. This ensures that loops 349 /// have exactly one backedge. 350 static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader, 351 AliasAnalysis *AA, 352 DominatorTree *DT, LoopInfo *LI) { 353 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!"); 354 355 // Get information about the loop 356 BasicBlock *Header = L->getHeader(); 357 Function *F = Header->getParent(); 358 359 // Unique backedge insertion currently depends on having a preheader. 360 if (!Preheader) 361 return nullptr; 362 363 // The header is not a landing pad; preheader insertion should ensure this. 364 assert(!Header->isLandingPad() && "Can't insert backedge to landing pad"); 365 366 // Figure out which basic blocks contain back-edges to the loop header. 367 std::vector<BasicBlock*> BackedgeBlocks; 368 for (BasicBlock *P : predecessors(Header)) { 369 // Indirectbr edges cannot be split, so we must fail if we find one. 370 if (isa<IndirectBrInst>(P->getTerminator())) 371 return nullptr; 372 373 if (P != Preheader) BackedgeBlocks.push_back(P); 374 } 375 376 // Create and insert the new backedge block... 377 BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(), 378 Header->getName()+".backedge", F); 379 BranchInst *BETerminator = BranchInst::Create(Header, BEBlock); 380 381 DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block " 382 << BEBlock->getName() << "\n"); 383 384 // Move the new backedge block to right after the last backedge block. 385 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos; 386 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock); 387 388 // Now that the block has been inserted into the function, create PHI nodes in 389 // the backedge block which correspond to any PHI nodes in the header block. 390 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 391 PHINode *PN = cast<PHINode>(I); 392 PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(), 393 PN->getName()+".be", BETerminator); 394 if (AA) AA->copyValue(PN, NewPN); 395 396 // Loop over the PHI node, moving all entries except the one for the 397 // preheader over to the new PHI node. 398 unsigned PreheaderIdx = ~0U; 399 bool HasUniqueIncomingValue = true; 400 Value *UniqueValue = nullptr; 401 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 402 BasicBlock *IBB = PN->getIncomingBlock(i); 403 Value *IV = PN->getIncomingValue(i); 404 if (IBB == Preheader) { 405 PreheaderIdx = i; 406 } else { 407 NewPN->addIncoming(IV, IBB); 408 if (HasUniqueIncomingValue) { 409 if (!UniqueValue) 410 UniqueValue = IV; 411 else if (UniqueValue != IV) 412 HasUniqueIncomingValue = false; 413 } 414 } 415 } 416 417 // Delete all of the incoming values from the old PN except the preheader's 418 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??"); 419 if (PreheaderIdx != 0) { 420 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx)); 421 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx)); 422 } 423 // Nuke all entries except the zero'th. 424 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i) 425 PN->removeIncomingValue(e-i, false); 426 427 // Finally, add the newly constructed PHI node as the entry for the BEBlock. 428 PN->addIncoming(NewPN, BEBlock); 429 430 // As an optimization, if all incoming values in the new PhiNode (which is a 431 // subset of the incoming values of the old PHI node) have the same value, 432 // eliminate the PHI Node. 433 if (HasUniqueIncomingValue) { 434 NewPN->replaceAllUsesWith(UniqueValue); 435 if (AA) AA->deleteValue(NewPN); 436 BEBlock->getInstList().erase(NewPN); 437 } 438 } 439 440 // Now that all of the PHI nodes have been inserted and adjusted, modify the 441 // backedge blocks to just to the BEBlock instead of the header. 442 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) { 443 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator(); 444 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op) 445 if (TI->getSuccessor(Op) == Header) 446 TI->setSuccessor(Op, BEBlock); 447 } 448 449 //===--- Update all analyses which we must preserve now -----------------===// 450 451 // Update Loop Information - we know that this block is now in the current 452 // loop and all parent loops. 453 L->addBasicBlockToLoop(BEBlock, LI->getBase()); 454 455 // Update dominator information 456 DT->splitBlock(BEBlock); 457 458 return BEBlock; 459 } 460 461 /// \brief Simplify one loop and queue further loops for simplification. 462 /// 463 /// FIXME: Currently this accepts both lots of analyses that it uses and a raw 464 /// Pass pointer. The Pass pointer is used by numerous utilities to update 465 /// specific analyses. Rather than a pass it would be much cleaner and more 466 /// explicit if they accepted the analysis directly and then updated it. 467 static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist, 468 AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI, 469 ScalarEvolution *SE, Pass *PP, 470 const DataLayout *DL) { 471 bool Changed = false; 472 ReprocessLoop: 473 474 // Check to see that no blocks (other than the header) in this loop have 475 // predecessors that are not in the loop. This is not valid for natural 476 // loops, but can occur if the blocks are unreachable. Since they are 477 // unreachable we can just shamelessly delete those CFG edges! 478 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end(); 479 BB != E; ++BB) { 480 if (*BB == L->getHeader()) continue; 481 482 SmallPtrSet<BasicBlock*, 4> BadPreds; 483 for (BasicBlock *P : predecessors(*BB)) { 484 if (!L->contains(P)) 485 BadPreds.insert(P); 486 } 487 488 // Delete each unique out-of-loop (and thus dead) predecessor. 489 for (SmallPtrSet<BasicBlock*, 4>::iterator I = BadPreds.begin(), 490 E = BadPreds.end(); I != E; ++I) { 491 492 DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor " 493 << (*I)->getName() << "\n"); 494 495 // Inform each successor of each dead pred. 496 for (BasicBlock *Succ : successors(*I)) 497 Succ->removePredecessor(*I); 498 // Zap the dead pred's terminator and replace it with unreachable. 499 TerminatorInst *TI = (*I)->getTerminator(); 500 TI->replaceAllUsesWith(UndefValue::get(TI->getType())); 501 (*I)->getTerminator()->eraseFromParent(); 502 new UnreachableInst((*I)->getContext(), *I); 503 Changed = true; 504 } 505 } 506 507 // If there are exiting blocks with branches on undef, resolve the undef in 508 // the direction which will exit the loop. This will help simplify loop 509 // trip count computations. 510 SmallVector<BasicBlock*, 8> ExitingBlocks; 511 L->getExitingBlocks(ExitingBlocks); 512 for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(), 513 E = ExitingBlocks.end(); I != E; ++I) 514 if (BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator())) 515 if (BI->isConditional()) { 516 if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) { 517 518 DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in " 519 << (*I)->getName() << "\n"); 520 521 BI->setCondition(ConstantInt::get(Cond->getType(), 522 !L->contains(BI->getSuccessor(0)))); 523 524 // This may make the loop analyzable, force SCEV recomputation. 525 if (SE) 526 SE->forgetLoop(L); 527 528 Changed = true; 529 } 530 } 531 532 // Does the loop already have a preheader? If so, don't insert one. 533 BasicBlock *Preheader = L->getLoopPreheader(); 534 if (!Preheader) { 535 Preheader = InsertPreheaderForLoop(L, PP); 536 if (Preheader) { 537 ++NumInserted; 538 Changed = true; 539 } 540 } 541 542 // Next, check to make sure that all exit nodes of the loop only have 543 // predecessors that are inside of the loop. This check guarantees that the 544 // loop preheader/header will dominate the exit blocks. If the exit block has 545 // predecessors from outside of the loop, split the edge now. 546 SmallVector<BasicBlock*, 8> ExitBlocks; 547 L->getExitBlocks(ExitBlocks); 548 549 SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(), 550 ExitBlocks.end()); 551 for (SmallSetVector<BasicBlock *, 8>::iterator I = ExitBlockSet.begin(), 552 E = ExitBlockSet.end(); I != E; ++I) { 553 BasicBlock *ExitBlock = *I; 554 for (BasicBlock *Pred : predecessors(ExitBlock)) 555 // Must be exactly this loop: no subloops, parent loops, or non-loop preds 556 // allowed. 557 if (!L->contains(Pred)) { 558 if (rewriteLoopExitBlock(L, ExitBlock, PP)) { 559 ++NumInserted; 560 Changed = true; 561 } 562 break; 563 } 564 } 565 566 // If the header has more than two predecessors at this point (from the 567 // preheader and from multiple backedges), we must adjust the loop. 568 BasicBlock *LoopLatch = L->getLoopLatch(); 569 if (!LoopLatch) { 570 // If this is really a nested loop, rip it out into a child loop. Don't do 571 // this for loops with a giant number of backedges, just factor them into a 572 // common backedge instead. 573 if (L->getNumBackEdges() < 8) { 574 if (Loop *OuterL = separateNestedLoop(L, Preheader, AA, DT, LI, SE, PP)) { 575 ++NumNested; 576 // Enqueue the outer loop as it should be processed next in our 577 // depth-first nest walk. 578 Worklist.push_back(OuterL); 579 580 // This is a big restructuring change, reprocess the whole loop. 581 Changed = true; 582 // GCC doesn't tail recursion eliminate this. 583 // FIXME: It isn't clear we can't rely on LLVM to TRE this. 584 goto ReprocessLoop; 585 } 586 } 587 588 // If we either couldn't, or didn't want to, identify nesting of the loops, 589 // insert a new block that all backedges target, then make it jump to the 590 // loop header. 591 LoopLatch = insertUniqueBackedgeBlock(L, Preheader, AA, DT, LI); 592 if (LoopLatch) { 593 ++NumInserted; 594 Changed = true; 595 } 596 } 597 598 // Scan over the PHI nodes in the loop header. Since they now have only two 599 // incoming values (the loop is canonicalized), we may have simplified the PHI 600 // down to 'X = phi [X, Y]', which should be replaced with 'Y'. 601 PHINode *PN; 602 for (BasicBlock::iterator I = L->getHeader()->begin(); 603 (PN = dyn_cast<PHINode>(I++)); ) 604 if (Value *V = SimplifyInstruction(PN, nullptr, nullptr, DT)) { 605 if (AA) AA->deleteValue(PN); 606 if (SE) SE->forgetValue(PN); 607 PN->replaceAllUsesWith(V); 608 PN->eraseFromParent(); 609 } 610 611 // If this loop has multiple exits and the exits all go to the same 612 // block, attempt to merge the exits. This helps several passes, such 613 // as LoopRotation, which do not support loops with multiple exits. 614 // SimplifyCFG also does this (and this code uses the same utility 615 // function), however this code is loop-aware, where SimplifyCFG is 616 // not. That gives it the advantage of being able to hoist 617 // loop-invariant instructions out of the way to open up more 618 // opportunities, and the disadvantage of having the responsibility 619 // to preserve dominator information. 620 bool UniqueExit = true; 621 if (!ExitBlocks.empty()) 622 for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i) 623 if (ExitBlocks[i] != ExitBlocks[0]) { 624 UniqueExit = false; 625 break; 626 } 627 if (UniqueExit) { 628 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 629 BasicBlock *ExitingBlock = ExitingBlocks[i]; 630 if (!ExitingBlock->getSinglePredecessor()) continue; 631 BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); 632 if (!BI || !BI->isConditional()) continue; 633 CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition()); 634 if (!CI || CI->getParent() != ExitingBlock) continue; 635 636 // Attempt to hoist out all instructions except for the 637 // comparison and the branch. 638 bool AllInvariant = true; 639 bool AnyInvariant = false; 640 for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) { 641 Instruction *Inst = I++; 642 // Skip debug info intrinsics. 643 if (isa<DbgInfoIntrinsic>(Inst)) 644 continue; 645 if (Inst == CI) 646 continue; 647 if (!L->makeLoopInvariant(Inst, AnyInvariant, 648 Preheader ? Preheader->getTerminator() 649 : nullptr)) { 650 AllInvariant = false; 651 break; 652 } 653 } 654 if (AnyInvariant) { 655 Changed = true; 656 // The loop disposition of all SCEV expressions that depend on any 657 // hoisted values have also changed. 658 if (SE) 659 SE->forgetLoopDispositions(L); 660 } 661 if (!AllInvariant) continue; 662 663 // The block has now been cleared of all instructions except for 664 // a comparison and a conditional branch. SimplifyCFG may be able 665 // to fold it now. 666 if (!FoldBranchToCommonDest(BI, DL)) continue; 667 668 // Success. The block is now dead, so remove it from the loop, 669 // update the dominator tree and delete it. 670 DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block " 671 << ExitingBlock->getName() << "\n"); 672 673 // Notify ScalarEvolution before deleting this block. Currently assume the 674 // parent loop doesn't change (spliting edges doesn't count). If blocks, 675 // CFG edges, or other values in the parent loop change, then we need call 676 // to forgetLoop() for the parent instead. 677 if (SE) 678 SE->forgetLoop(L); 679 680 assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock)); 681 Changed = true; 682 LI->removeBlock(ExitingBlock); 683 684 DomTreeNode *Node = DT->getNode(ExitingBlock); 685 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children = 686 Node->getChildren(); 687 while (!Children.empty()) { 688 DomTreeNode *Child = Children.front(); 689 DT->changeImmediateDominator(Child, Node->getIDom()); 690 } 691 DT->eraseNode(ExitingBlock); 692 693 BI->getSuccessor(0)->removePredecessor(ExitingBlock); 694 BI->getSuccessor(1)->removePredecessor(ExitingBlock); 695 ExitingBlock->eraseFromParent(); 696 } 697 } 698 699 return Changed; 700 } 701 702 bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, Pass *PP, 703 AliasAnalysis *AA, ScalarEvolution *SE, 704 const DataLayout *DL) { 705 bool Changed = false; 706 707 // Worklist maintains our depth-first queue of loops in this nest to process. 708 SmallVector<Loop *, 4> Worklist; 709 Worklist.push_back(L); 710 711 // Walk the worklist from front to back, pushing newly found sub loops onto 712 // the back. This will let us process loops from back to front in depth-first 713 // order. We can use this simple process because loops form a tree. 714 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 715 Loop *L2 = Worklist[Idx]; 716 for (Loop::iterator I = L2->begin(), E = L2->end(); I != E; ++I) 717 Worklist.push_back(*I); 718 } 719 720 while (!Worklist.empty()) 721 Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, AA, DT, LI, 722 SE, PP, DL); 723 724 return Changed; 725 } 726 727 namespace { 728 struct LoopSimplify : public FunctionPass { 729 static char ID; // Pass identification, replacement for typeid 730 LoopSimplify() : FunctionPass(ID) { 731 initializeLoopSimplifyPass(*PassRegistry::getPassRegistry()); 732 } 733 734 // AA - If we have an alias analysis object to update, this is it, otherwise 735 // this is null. 736 AliasAnalysis *AA; 737 DominatorTree *DT; 738 LoopInfo *LI; 739 ScalarEvolution *SE; 740 const DataLayout *DL; 741 742 bool runOnFunction(Function &F) override; 743 744 void getAnalysisUsage(AnalysisUsage &AU) const override { 745 // We need loop information to identify the loops... 746 AU.addRequired<DominatorTreeWrapperPass>(); 747 AU.addPreserved<DominatorTreeWrapperPass>(); 748 749 AU.addRequired<LoopInfo>(); 750 AU.addPreserved<LoopInfo>(); 751 752 AU.addPreserved<AliasAnalysis>(); 753 AU.addPreserved<ScalarEvolution>(); 754 AU.addPreserved<DependenceAnalysis>(); 755 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added. 756 } 757 758 /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees. 759 void verifyAnalysis() const override; 760 }; 761 } 762 763 char LoopSimplify::ID = 0; 764 INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify", 765 "Canonicalize natural loops", true, false) 766 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 767 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 768 INITIALIZE_PASS_END(LoopSimplify, "loop-simplify", 769 "Canonicalize natural loops", true, false) 770 771 // Publicly exposed interface to pass... 772 char &llvm::LoopSimplifyID = LoopSimplify::ID; 773 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); } 774 775 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do 776 /// it in any convenient order) inserting preheaders... 777 /// 778 bool LoopSimplify::runOnFunction(Function &F) { 779 bool Changed = false; 780 AA = getAnalysisIfAvailable<AliasAnalysis>(); 781 LI = &getAnalysis<LoopInfo>(); 782 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 783 SE = getAnalysisIfAvailable<ScalarEvolution>(); 784 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); 785 DL = DLP ? &DLP->getDataLayout() : nullptr; 786 787 // Simplify each loop nest in the function. 788 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 789 Changed |= simplifyLoop(*I, DT, LI, this, AA, SE, DL); 790 791 return Changed; 792 } 793 794 // FIXME: Restore this code when we re-enable verification in verifyAnalysis 795 // below. 796 #if 0 797 static void verifyLoop(Loop *L) { 798 // Verify subloops. 799 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I) 800 verifyLoop(*I); 801 802 // It used to be possible to just assert L->isLoopSimplifyForm(), however 803 // with the introduction of indirectbr, there are now cases where it's 804 // not possible to transform a loop as necessary. We can at least check 805 // that there is an indirectbr near any time there's trouble. 806 807 // Indirectbr can interfere with preheader and unique backedge insertion. 808 if (!L->getLoopPreheader() || !L->getLoopLatch()) { 809 bool HasIndBrPred = false; 810 for (pred_iterator PI = pred_begin(L->getHeader()), 811 PE = pred_end(L->getHeader()); PI != PE; ++PI) 812 if (isa<IndirectBrInst>((*PI)->getTerminator())) { 813 HasIndBrPred = true; 814 break; 815 } 816 assert(HasIndBrPred && 817 "LoopSimplify has no excuse for missing loop header info!"); 818 (void)HasIndBrPred; 819 } 820 821 // Indirectbr can interfere with exit block canonicalization. 822 if (!L->hasDedicatedExits()) { 823 bool HasIndBrExiting = false; 824 SmallVector<BasicBlock*, 8> ExitingBlocks; 825 L->getExitingBlocks(ExitingBlocks); 826 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) { 827 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) { 828 HasIndBrExiting = true; 829 break; 830 } 831 } 832 833 assert(HasIndBrExiting && 834 "LoopSimplify has no excuse for missing exit block info!"); 835 (void)HasIndBrExiting; 836 } 837 } 838 #endif 839 840 void LoopSimplify::verifyAnalysis() const { 841 // FIXME: This routine is being called mid-way through the loop pass manager 842 // as loop passes destroy this analysis. That's actually fine, but we have no 843 // way of expressing that here. Once all of the passes that destroy this are 844 // hoisted out of the loop pass manager we can add back verification here. 845 #if 0 846 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) 847 verifyLoop(*I); 848 #endif 849 } 850