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