10b57cec5SDimitry Andric //===- LoopDeletion.cpp - Dead Loop Deletion Pass ---------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file implements the Dead Loop Deletion Pass. This pass is responsible 100b57cec5SDimitry Andric // for eliminating loops with non-infinite computable trip counts that have no 110b57cec5SDimitry Andric // side effects or volatile instructions, and do not contribute to the 120b57cec5SDimitry Andric // computation of the function's return value. 130b57cec5SDimitry Andric // 140b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 150b57cec5SDimitry Andric 160b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LoopDeletion.h" 170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 180b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 19fe6060f1SDimitry Andric #include "llvm/Analysis/CFG.h" 20fe6060f1SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 21fe6060f1SDimitry Andric #include "llvm/Analysis/LoopIterator.h" 220b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h" 235ffd83dbSDimitry Andric #include "llvm/Analysis/MemorySSA.h" 245ffd83dbSDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h" 2581ad6265SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 260b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 27fe6060f1SDimitry Andric 280b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h" 290b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h" 300b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h" 31e8d8bef9SDimitry Andric 320b57cec5SDimitry Andric using namespace llvm; 330b57cec5SDimitry Andric 340b57cec5SDimitry Andric #define DEBUG_TYPE "loop-delete" 350b57cec5SDimitry Andric 360b57cec5SDimitry Andric STATISTIC(NumDeleted, "Number of loops deleted"); 37349cc55cSDimitry Andric STATISTIC(NumBackedgesBroken, 38349cc55cSDimitry Andric "Number of loops for which we managed to break the backedge"); 390b57cec5SDimitry Andric 40fe6060f1SDimitry Andric static cl::opt<bool> EnableSymbolicExecution( 41fe6060f1SDimitry Andric "loop-deletion-enable-symbolic-execution", cl::Hidden, cl::init(true), 42fe6060f1SDimitry Andric cl::desc("Break backedge through symbolic execution of 1st iteration " 43fe6060f1SDimitry Andric "attempting to prove that the backedge is never taken")); 44fe6060f1SDimitry Andric 450b57cec5SDimitry Andric enum class LoopDeletionResult { 460b57cec5SDimitry Andric Unmodified, 470b57cec5SDimitry Andric Modified, 480b57cec5SDimitry Andric Deleted, 490b57cec5SDimitry Andric }; 500b57cec5SDimitry Andric 51e8d8bef9SDimitry Andric static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B) { 52e8d8bef9SDimitry Andric if (A == LoopDeletionResult::Deleted || B == LoopDeletionResult::Deleted) 53e8d8bef9SDimitry Andric return LoopDeletionResult::Deleted; 54e8d8bef9SDimitry Andric if (A == LoopDeletionResult::Modified || B == LoopDeletionResult::Modified) 55e8d8bef9SDimitry Andric return LoopDeletionResult::Modified; 56e8d8bef9SDimitry Andric return LoopDeletionResult::Unmodified; 57e8d8bef9SDimitry Andric } 58e8d8bef9SDimitry Andric 590b57cec5SDimitry Andric /// Determines if a loop is dead. 600b57cec5SDimitry Andric /// 610b57cec5SDimitry Andric /// This assumes that we've already checked for unique exit and exiting blocks, 620b57cec5SDimitry Andric /// and that the code is in LCSSA form. 630b57cec5SDimitry Andric static bool isLoopDead(Loop *L, ScalarEvolution &SE, 640b57cec5SDimitry Andric SmallVectorImpl<BasicBlock *> &ExitingBlocks, 650b57cec5SDimitry Andric BasicBlock *ExitBlock, bool &Changed, 66fe6060f1SDimitry Andric BasicBlock *Preheader, LoopInfo &LI) { 670b57cec5SDimitry Andric // Make sure that all PHI entries coming from the loop are loop invariant. 680b57cec5SDimitry Andric // Because the code is in LCSSA form, any values used outside of the loop 690b57cec5SDimitry Andric // must pass through a PHI in the exit block, meaning that this check is 700b57cec5SDimitry Andric // sufficient to guarantee that no loop-variant values are used outside 710b57cec5SDimitry Andric // of the loop. 720b57cec5SDimitry Andric bool AllEntriesInvariant = true; 730b57cec5SDimitry Andric bool AllOutgoingValuesSame = true; 7406c3fb27SDimitry Andric if (ExitBlock) { 750b57cec5SDimitry Andric for (PHINode &P : ExitBlock->phis()) { 760b57cec5SDimitry Andric Value *incoming = P.getIncomingValueForBlock(ExitingBlocks[0]); 770b57cec5SDimitry Andric 78e8d8bef9SDimitry Andric // Make sure all exiting blocks produce the same incoming value for the 790b57cec5SDimitry Andric // block. If there are different incoming values for different exiting 80e8d8bef9SDimitry Andric // blocks, then it is impossible to statically determine which value 81e8d8bef9SDimitry Andric // should be used. 820b57cec5SDimitry Andric AllOutgoingValuesSame = 83bdd1243dSDimitry Andric all_of(ArrayRef(ExitingBlocks).slice(1), [&](BasicBlock *BB) { 840b57cec5SDimitry Andric return incoming == P.getIncomingValueForBlock(BB); 850b57cec5SDimitry Andric }); 860b57cec5SDimitry Andric 870b57cec5SDimitry Andric if (!AllOutgoingValuesSame) 880b57cec5SDimitry Andric break; 890b57cec5SDimitry Andric 90bdd1243dSDimitry Andric if (Instruction *I = dyn_cast<Instruction>(incoming)) { 91bdd1243dSDimitry Andric if (!L->makeLoopInvariant(I, Changed, Preheader->getTerminator(), 92bdd1243dSDimitry Andric /*MSSAU=*/nullptr, &SE)) { 930b57cec5SDimitry Andric AllEntriesInvariant = false; 940b57cec5SDimitry Andric break; 950b57cec5SDimitry Andric } 960b57cec5SDimitry Andric } 97e8d8bef9SDimitry Andric } 98bdd1243dSDimitry Andric } 990b57cec5SDimitry Andric 1000b57cec5SDimitry Andric if (!AllEntriesInvariant || !AllOutgoingValuesSame) 1010b57cec5SDimitry Andric return false; 1020b57cec5SDimitry Andric 1030b57cec5SDimitry Andric // Make sure that no instructions in the block have potential side-effects. 1040b57cec5SDimitry Andric // This includes instructions that could write to memory, and loads that are 1050b57cec5SDimitry Andric // marked volatile. 106bdd1243dSDimitry Andric for (const auto &I : L->blocks()) 107e8d8bef9SDimitry Andric if (any_of(*I, [](Instruction &I) { 108e8d8bef9SDimitry Andric return I.mayHaveSideEffects() && !I.isDroppable(); 109e8d8bef9SDimitry Andric })) 1100b57cec5SDimitry Andric return false; 111fe6060f1SDimitry Andric 112fe6060f1SDimitry Andric // The loop or any of its sub-loops looping infinitely is legal. The loop can 113fe6060f1SDimitry Andric // only be considered dead if either 114fe6060f1SDimitry Andric // a. the function is mustprogress. 115fe6060f1SDimitry Andric // b. all (sub-)loops are mustprogress or have a known trip-count. 116fe6060f1SDimitry Andric if (L->getHeader()->getParent()->mustProgress()) 117fe6060f1SDimitry Andric return true; 118fe6060f1SDimitry Andric 119fe6060f1SDimitry Andric LoopBlocksRPO RPOT(L); 120fe6060f1SDimitry Andric RPOT.perform(&LI); 121fe6060f1SDimitry Andric // If the loop contains an irreducible cycle, it may loop infinitely. 122fe6060f1SDimitry Andric if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 123fe6060f1SDimitry Andric return false; 124fe6060f1SDimitry Andric 125fe6060f1SDimitry Andric SmallVector<Loop *, 8> WorkList; 126fe6060f1SDimitry Andric WorkList.push_back(L); 127fe6060f1SDimitry Andric while (!WorkList.empty()) { 128fe6060f1SDimitry Andric Loop *Current = WorkList.pop_back_val(); 129fe6060f1SDimitry Andric if (hasMustProgress(Current)) 130fe6060f1SDimitry Andric continue; 131fe6060f1SDimitry Andric 132fe6060f1SDimitry Andric const SCEV *S = SE.getConstantMaxBackedgeTakenCount(Current); 133fe6060f1SDimitry Andric if (isa<SCEVCouldNotCompute>(S)) { 134fe6060f1SDimitry Andric LLVM_DEBUG( 135fe6060f1SDimitry Andric dbgs() << "Could not compute SCEV MaxBackedgeTakenCount and was " 136fe6060f1SDimitry Andric "not required to make progress.\n"); 137fe6060f1SDimitry Andric return false; 138fe6060f1SDimitry Andric } 139fe6060f1SDimitry Andric WorkList.append(Current->begin(), Current->end()); 140fe6060f1SDimitry Andric } 1410b57cec5SDimitry Andric return true; 1420b57cec5SDimitry Andric } 1430b57cec5SDimitry Andric 1440b57cec5SDimitry Andric /// This function returns true if there is no viable path from the 1450b57cec5SDimitry Andric /// entry block to the header of \p L. Right now, it only does 1460b57cec5SDimitry Andric /// a local search to save compile time. 1470b57cec5SDimitry Andric static bool isLoopNeverExecuted(Loop *L) { 1480b57cec5SDimitry Andric using namespace PatternMatch; 1490b57cec5SDimitry Andric 1500b57cec5SDimitry Andric auto *Preheader = L->getLoopPreheader(); 1510b57cec5SDimitry Andric // TODO: We can relax this constraint, since we just need a loop 1520b57cec5SDimitry Andric // predecessor. 1530b57cec5SDimitry Andric assert(Preheader && "Needs preheader!"); 1540b57cec5SDimitry Andric 155fe6060f1SDimitry Andric if (Preheader->isEntryBlock()) 1560b57cec5SDimitry Andric return false; 1570b57cec5SDimitry Andric // All predecessors of the preheader should have a constant conditional 1580b57cec5SDimitry Andric // branch, with the loop's preheader as not-taken. 1590b57cec5SDimitry Andric for (auto *Pred: predecessors(Preheader)) { 1600b57cec5SDimitry Andric BasicBlock *Taken, *NotTaken; 1610b57cec5SDimitry Andric ConstantInt *Cond; 1620b57cec5SDimitry Andric if (!match(Pred->getTerminator(), 1630b57cec5SDimitry Andric m_Br(m_ConstantInt(Cond), Taken, NotTaken))) 1640b57cec5SDimitry Andric return false; 1650b57cec5SDimitry Andric if (!Cond->getZExtValue()) 1660b57cec5SDimitry Andric std::swap(Taken, NotTaken); 1670b57cec5SDimitry Andric if (Taken == Preheader) 1680b57cec5SDimitry Andric return false; 1690b57cec5SDimitry Andric } 1700b57cec5SDimitry Andric assert(!pred_empty(Preheader) && 1710b57cec5SDimitry Andric "Preheader should have predecessors at this point!"); 1720b57cec5SDimitry Andric // All the predecessors have the loop preheader as not-taken target. 1730b57cec5SDimitry Andric return true; 1740b57cec5SDimitry Andric } 1750b57cec5SDimitry Andric 176fe6060f1SDimitry Andric static Value * 177fe6060f1SDimitry Andric getValueOnFirstIteration(Value *V, DenseMap<Value *, Value *> &FirstIterValue, 178fe6060f1SDimitry Andric const SimplifyQuery &SQ) { 179fe6060f1SDimitry Andric // Quick hack: do not flood cache with non-instruction values. 180fe6060f1SDimitry Andric if (!isa<Instruction>(V)) 181fe6060f1SDimitry Andric return V; 182fe6060f1SDimitry Andric // Do we already know cached result? 183fe6060f1SDimitry Andric auto Existing = FirstIterValue.find(V); 184fe6060f1SDimitry Andric if (Existing != FirstIterValue.end()) 185fe6060f1SDimitry Andric return Existing->second; 186fe6060f1SDimitry Andric Value *FirstIterV = nullptr; 187fe6060f1SDimitry Andric if (auto *BO = dyn_cast<BinaryOperator>(V)) { 188fe6060f1SDimitry Andric Value *LHS = 189fe6060f1SDimitry Andric getValueOnFirstIteration(BO->getOperand(0), FirstIterValue, SQ); 190fe6060f1SDimitry Andric Value *RHS = 191fe6060f1SDimitry Andric getValueOnFirstIteration(BO->getOperand(1), FirstIterValue, SQ); 19281ad6265SDimitry Andric FirstIterV = simplifyBinOp(BO->getOpcode(), LHS, RHS, SQ); 193349cc55cSDimitry Andric } else if (auto *Cmp = dyn_cast<ICmpInst>(V)) { 194349cc55cSDimitry Andric Value *LHS = 195349cc55cSDimitry Andric getValueOnFirstIteration(Cmp->getOperand(0), FirstIterValue, SQ); 196349cc55cSDimitry Andric Value *RHS = 197349cc55cSDimitry Andric getValueOnFirstIteration(Cmp->getOperand(1), FirstIterValue, SQ); 19881ad6265SDimitry Andric FirstIterV = simplifyICmpInst(Cmp->getPredicate(), LHS, RHS, SQ); 199349cc55cSDimitry Andric } else if (auto *Select = dyn_cast<SelectInst>(V)) { 200349cc55cSDimitry Andric Value *Cond = 201349cc55cSDimitry Andric getValueOnFirstIteration(Select->getCondition(), FirstIterValue, SQ); 202349cc55cSDimitry Andric if (auto *C = dyn_cast<ConstantInt>(Cond)) { 203349cc55cSDimitry Andric auto *Selected = C->isAllOnesValue() ? Select->getTrueValue() 204349cc55cSDimitry Andric : Select->getFalseValue(); 205349cc55cSDimitry Andric FirstIterV = getValueOnFirstIteration(Selected, FirstIterValue, SQ); 206349cc55cSDimitry Andric } 207fe6060f1SDimitry Andric } 208fe6060f1SDimitry Andric if (!FirstIterV) 209fe6060f1SDimitry Andric FirstIterV = V; 210fe6060f1SDimitry Andric FirstIterValue[V] = FirstIterV; 211fe6060f1SDimitry Andric return FirstIterV; 212fe6060f1SDimitry Andric } 213fe6060f1SDimitry Andric 214fe6060f1SDimitry Andric // Try to prove that one of conditions that dominates the latch must exit on 1st 215fe6060f1SDimitry Andric // iteration. 216fe6060f1SDimitry Andric static bool canProveExitOnFirstIteration(Loop *L, DominatorTree &DT, 217fe6060f1SDimitry Andric LoopInfo &LI) { 218fe6060f1SDimitry Andric // Disabled by option. 219fe6060f1SDimitry Andric if (!EnableSymbolicExecution) 220fe6060f1SDimitry Andric return false; 221fe6060f1SDimitry Andric 222fe6060f1SDimitry Andric BasicBlock *Predecessor = L->getLoopPredecessor(); 223fe6060f1SDimitry Andric BasicBlock *Latch = L->getLoopLatch(); 224fe6060f1SDimitry Andric 225fe6060f1SDimitry Andric if (!Predecessor || !Latch) 226fe6060f1SDimitry Andric return false; 227fe6060f1SDimitry Andric 228fe6060f1SDimitry Andric LoopBlocksRPO RPOT(L); 229fe6060f1SDimitry Andric RPOT.perform(&LI); 230fe6060f1SDimitry Andric 231fe6060f1SDimitry Andric // For the optimization to be correct, we need RPOT to have a property that 232fe6060f1SDimitry Andric // each block is processed after all its predecessors, which may only be 233fe6060f1SDimitry Andric // violated for headers of the current loop and all nested loops. Irreducible 234fe6060f1SDimitry Andric // CFG provides multiple ways to break this assumption, so we do not want to 235fe6060f1SDimitry Andric // deal with it. 236fe6060f1SDimitry Andric if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI)) 237fe6060f1SDimitry Andric return false; 238fe6060f1SDimitry Andric 239fe6060f1SDimitry Andric BasicBlock *Header = L->getHeader(); 240fe6060f1SDimitry Andric // Blocks that are reachable on the 1st iteration. 241fe6060f1SDimitry Andric SmallPtrSet<BasicBlock *, 4> LiveBlocks; 242fe6060f1SDimitry Andric // Edges that are reachable on the 1st iteration. 243fe6060f1SDimitry Andric DenseSet<BasicBlockEdge> LiveEdges; 244fe6060f1SDimitry Andric LiveBlocks.insert(Header); 245fe6060f1SDimitry Andric 246fe6060f1SDimitry Andric SmallPtrSet<BasicBlock *, 4> Visited; 247fe6060f1SDimitry Andric auto MarkLiveEdge = [&](BasicBlock *From, BasicBlock *To) { 248fe6060f1SDimitry Andric assert(LiveBlocks.count(From) && "Must be live!"); 249fe6060f1SDimitry Andric assert((LI.isLoopHeader(To) || !Visited.count(To)) && 250fe6060f1SDimitry Andric "Only canonical backedges are allowed. Irreducible CFG?"); 251fe6060f1SDimitry Andric assert((LiveBlocks.count(To) || !Visited.count(To)) && 252fe6060f1SDimitry Andric "We already discarded this block as dead!"); 253fe6060f1SDimitry Andric LiveBlocks.insert(To); 254fe6060f1SDimitry Andric LiveEdges.insert({ From, To }); 255fe6060f1SDimitry Andric }; 256fe6060f1SDimitry Andric 257fe6060f1SDimitry Andric auto MarkAllSuccessorsLive = [&](BasicBlock *BB) { 258fe6060f1SDimitry Andric for (auto *Succ : successors(BB)) 259fe6060f1SDimitry Andric MarkLiveEdge(BB, Succ); 260fe6060f1SDimitry Andric }; 261fe6060f1SDimitry Andric 262fe6060f1SDimitry Andric // Check if there is only one value coming from all live predecessor blocks. 263fe6060f1SDimitry Andric // Note that because we iterate in RPOT, we have already visited all its 264fe6060f1SDimitry Andric // (non-latch) predecessors. 265fe6060f1SDimitry Andric auto GetSoleInputOnFirstIteration = [&](PHINode & PN)->Value * { 266fe6060f1SDimitry Andric BasicBlock *BB = PN.getParent(); 267fe6060f1SDimitry Andric bool HasLivePreds = false; 268fe6060f1SDimitry Andric (void)HasLivePreds; 269fe6060f1SDimitry Andric if (BB == Header) 270fe6060f1SDimitry Andric return PN.getIncomingValueForBlock(Predecessor); 271fe6060f1SDimitry Andric Value *OnlyInput = nullptr; 272fe6060f1SDimitry Andric for (auto *Pred : predecessors(BB)) 273fe6060f1SDimitry Andric if (LiveEdges.count({ Pred, BB })) { 274fe6060f1SDimitry Andric HasLivePreds = true; 275fe6060f1SDimitry Andric Value *Incoming = PN.getIncomingValueForBlock(Pred); 276*0fca6ea1SDimitry Andric // Skip poison. If they are present, we can assume they are equal to 277*0fca6ea1SDimitry Andric // the non-poison input. 278*0fca6ea1SDimitry Andric if (isa<PoisonValue>(Incoming)) 279fe6060f1SDimitry Andric continue; 280fe6060f1SDimitry Andric // Two inputs. 281fe6060f1SDimitry Andric if (OnlyInput && OnlyInput != Incoming) 282fe6060f1SDimitry Andric return nullptr; 283fe6060f1SDimitry Andric OnlyInput = Incoming; 284fe6060f1SDimitry Andric } 285fe6060f1SDimitry Andric 286fe6060f1SDimitry Andric assert(HasLivePreds && "No live predecessors?"); 287*0fca6ea1SDimitry Andric // If all incoming live value were poison, return poison. 288*0fca6ea1SDimitry Andric return OnlyInput ? OnlyInput : PoisonValue::get(PN.getType()); 289fe6060f1SDimitry Andric }; 290fe6060f1SDimitry Andric DenseMap<Value *, Value *> FirstIterValue; 291fe6060f1SDimitry Andric 292fe6060f1SDimitry Andric // Use the following algorithm to prove we never take the latch on the 1st 293fe6060f1SDimitry Andric // iteration: 294fe6060f1SDimitry Andric // 1. Traverse in topological order, so that whenever we visit a block, all 295fe6060f1SDimitry Andric // its predecessors are already visited. 296fe6060f1SDimitry Andric // 2. If we can prove that the block may have only 1 predecessor on the 1st 297fe6060f1SDimitry Andric // iteration, map all its phis onto input from this predecessor. 298fe6060f1SDimitry Andric // 3a. If we can prove which successor of out block is taken on the 1st 299fe6060f1SDimitry Andric // iteration, mark this successor live. 300fe6060f1SDimitry Andric // 3b. If we cannot prove it, conservatively assume that all successors are 301fe6060f1SDimitry Andric // live. 302*0fca6ea1SDimitry Andric auto &DL = Header->getDataLayout(); 303fe6060f1SDimitry Andric const SimplifyQuery SQ(DL); 304fe6060f1SDimitry Andric for (auto *BB : RPOT) { 305fe6060f1SDimitry Andric Visited.insert(BB); 306fe6060f1SDimitry Andric 307fe6060f1SDimitry Andric // This block is not reachable on the 1st iterations. 308fe6060f1SDimitry Andric if (!LiveBlocks.count(BB)) 309fe6060f1SDimitry Andric continue; 310fe6060f1SDimitry Andric 311fe6060f1SDimitry Andric // Skip inner loops. 312fe6060f1SDimitry Andric if (LI.getLoopFor(BB) != L) { 313fe6060f1SDimitry Andric MarkAllSuccessorsLive(BB); 314fe6060f1SDimitry Andric continue; 315fe6060f1SDimitry Andric } 316fe6060f1SDimitry Andric 317fe6060f1SDimitry Andric // If Phi has only one input from all live input blocks, use it. 318fe6060f1SDimitry Andric for (auto &PN : BB->phis()) { 319fe6060f1SDimitry Andric if (!PN.getType()->isIntegerTy()) 320fe6060f1SDimitry Andric continue; 321fe6060f1SDimitry Andric auto *Incoming = GetSoleInputOnFirstIteration(PN); 322fe6060f1SDimitry Andric if (Incoming && DT.dominates(Incoming, BB->getTerminator())) { 323fe6060f1SDimitry Andric Value *FirstIterV = 324fe6060f1SDimitry Andric getValueOnFirstIteration(Incoming, FirstIterValue, SQ); 325fe6060f1SDimitry Andric FirstIterValue[&PN] = FirstIterV; 326fe6060f1SDimitry Andric } 327fe6060f1SDimitry Andric } 328fe6060f1SDimitry Andric 329fe6060f1SDimitry Andric using namespace PatternMatch; 330349cc55cSDimitry Andric Value *Cond; 331fe6060f1SDimitry Andric BasicBlock *IfTrue, *IfFalse; 332fe6060f1SDimitry Andric auto *Term = BB->getTerminator(); 333349cc55cSDimitry Andric if (match(Term, m_Br(m_Value(Cond), 334fe6060f1SDimitry Andric m_BasicBlock(IfTrue), m_BasicBlock(IfFalse)))) { 335349cc55cSDimitry Andric auto *ICmp = dyn_cast<ICmpInst>(Cond); 336349cc55cSDimitry Andric if (!ICmp || !ICmp->getType()->isIntegerTy()) { 337fe6060f1SDimitry Andric MarkAllSuccessorsLive(BB); 338fe6060f1SDimitry Andric continue; 339fe6060f1SDimitry Andric } 340fe6060f1SDimitry Andric 341fe6060f1SDimitry Andric // Can we prove constant true or false for this condition? 342349cc55cSDimitry Andric auto *KnownCondition = getValueOnFirstIteration(ICmp, FirstIterValue, SQ); 343349cc55cSDimitry Andric if (KnownCondition == ICmp) { 344fe6060f1SDimitry Andric // Failed to simplify. 345fe6060f1SDimitry Andric MarkAllSuccessorsLive(BB); 346fe6060f1SDimitry Andric continue; 347fe6060f1SDimitry Andric } 348fe6060f1SDimitry Andric if (isa<UndefValue>(KnownCondition)) { 349fe6060f1SDimitry Andric // TODO: According to langref, branching by undef is undefined behavior. 350fe6060f1SDimitry Andric // It means that, theoretically, we should be able to just continue 351fe6060f1SDimitry Andric // without marking any successors as live. However, we are not certain 352fe6060f1SDimitry Andric // how correct our compiler is at handling such cases. So we are being 353fe6060f1SDimitry Andric // very conservative here. 354fe6060f1SDimitry Andric // 355fe6060f1SDimitry Andric // If there is a non-loop successor, always assume this branch leaves the 356fe6060f1SDimitry Andric // loop. Otherwise, arbitrarily take IfTrue. 357fe6060f1SDimitry Andric // 358fe6060f1SDimitry Andric // Once we are certain that branching by undef is handled correctly by 359fe6060f1SDimitry Andric // other transforms, we should not mark any successors live here. 360fe6060f1SDimitry Andric if (L->contains(IfTrue) && L->contains(IfFalse)) 361fe6060f1SDimitry Andric MarkLiveEdge(BB, IfTrue); 362fe6060f1SDimitry Andric continue; 363fe6060f1SDimitry Andric } 364fe6060f1SDimitry Andric auto *ConstCondition = dyn_cast<ConstantInt>(KnownCondition); 365fe6060f1SDimitry Andric if (!ConstCondition) { 366fe6060f1SDimitry Andric // Non-constant condition, cannot analyze any further. 367fe6060f1SDimitry Andric MarkAllSuccessorsLive(BB); 368fe6060f1SDimitry Andric continue; 369fe6060f1SDimitry Andric } 370fe6060f1SDimitry Andric if (ConstCondition->isAllOnesValue()) 371fe6060f1SDimitry Andric MarkLiveEdge(BB, IfTrue); 372fe6060f1SDimitry Andric else 373fe6060f1SDimitry Andric MarkLiveEdge(BB, IfFalse); 374fe6060f1SDimitry Andric } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) { 375fe6060f1SDimitry Andric auto *SwitchValue = SI->getCondition(); 376fe6060f1SDimitry Andric auto *SwitchValueOnFirstIter = 377fe6060f1SDimitry Andric getValueOnFirstIteration(SwitchValue, FirstIterValue, SQ); 378fe6060f1SDimitry Andric auto *ConstSwitchValue = dyn_cast<ConstantInt>(SwitchValueOnFirstIter); 379fe6060f1SDimitry Andric if (!ConstSwitchValue) { 380fe6060f1SDimitry Andric MarkAllSuccessorsLive(BB); 381fe6060f1SDimitry Andric continue; 382fe6060f1SDimitry Andric } 383fe6060f1SDimitry Andric auto CaseIterator = SI->findCaseValue(ConstSwitchValue); 384fe6060f1SDimitry Andric MarkLiveEdge(BB, CaseIterator->getCaseSuccessor()); 385fe6060f1SDimitry Andric } else { 386fe6060f1SDimitry Andric MarkAllSuccessorsLive(BB); 387fe6060f1SDimitry Andric continue; 388fe6060f1SDimitry Andric } 389fe6060f1SDimitry Andric } 390fe6060f1SDimitry Andric 391fe6060f1SDimitry Andric // We can break the latch if it wasn't live. 392fe6060f1SDimitry Andric return !LiveEdges.count({ Latch, Header }); 393fe6060f1SDimitry Andric } 394fe6060f1SDimitry Andric 395e8d8bef9SDimitry Andric /// If we can prove the backedge is untaken, remove it. This destroys the 396e8d8bef9SDimitry Andric /// loop, but leaves the (now trivially loop invariant) control flow and 397e8d8bef9SDimitry Andric /// side effects (if any) in place. 398e8d8bef9SDimitry Andric static LoopDeletionResult 399e8d8bef9SDimitry Andric breakBackedgeIfNotTaken(Loop *L, DominatorTree &DT, ScalarEvolution &SE, 400e8d8bef9SDimitry Andric LoopInfo &LI, MemorySSA *MSSA, 401e8d8bef9SDimitry Andric OptimizationRemarkEmitter &ORE) { 402e8d8bef9SDimitry Andric assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 403e8d8bef9SDimitry Andric 404e8d8bef9SDimitry Andric if (!L->getLoopLatch()) 405e8d8bef9SDimitry Andric return LoopDeletionResult::Unmodified; 406e8d8bef9SDimitry Andric 40704eeddc0SDimitry Andric auto *BTCMax = SE.getConstantMaxBackedgeTakenCount(L); 40804eeddc0SDimitry Andric if (!BTCMax->isZero()) { 40904eeddc0SDimitry Andric auto *BTC = SE.getBackedgeTakenCount(L); 41004eeddc0SDimitry Andric if (!BTC->isZero()) { 41104eeddc0SDimitry Andric if (!isa<SCEVCouldNotCompute>(BTC) && SE.isKnownNonZero(BTC)) 412349cc55cSDimitry Andric return LoopDeletionResult::Unmodified; 41304eeddc0SDimitry Andric if (!canProveExitOnFirstIteration(L, DT, LI)) 41404eeddc0SDimitry Andric return LoopDeletionResult::Unmodified; 41504eeddc0SDimitry Andric } 41604eeddc0SDimitry Andric } 41704eeddc0SDimitry Andric ++NumBackedgesBroken; 41804eeddc0SDimitry Andric breakLoopBackedge(L, DT, SE, LI, MSSA); 41904eeddc0SDimitry Andric return LoopDeletionResult::Deleted; 420349cc55cSDimitry Andric } 421349cc55cSDimitry Andric 4220b57cec5SDimitry Andric /// Remove a loop if it is dead. 4230b57cec5SDimitry Andric /// 424e8d8bef9SDimitry Andric /// A loop is considered dead either if it does not impact the observable 425e8d8bef9SDimitry Andric /// behavior of the program other than finite running time, or if it is 426e8d8bef9SDimitry Andric /// required to make progress by an attribute such as 'mustprogress' or 427e8d8bef9SDimitry Andric /// 'llvm.loop.mustprogress' and does not make any. This may remove 428e8d8bef9SDimitry Andric /// infinite loops that have been required to make progress. 4290b57cec5SDimitry Andric /// 4300b57cec5SDimitry Andric /// This entire process relies pretty heavily on LoopSimplify form and LCSSA in 4310b57cec5SDimitry Andric /// order to make various safety checks work. 4320b57cec5SDimitry Andric /// 4330b57cec5SDimitry Andric /// \returns true if any changes were made. This may mutate the loop even if it 4340b57cec5SDimitry Andric /// is unable to delete it due to hoisting trivially loop invariant 4350b57cec5SDimitry Andric /// instructions out of the loop. 4360b57cec5SDimitry Andric static LoopDeletionResult deleteLoopIfDead(Loop *L, DominatorTree &DT, 4375ffd83dbSDimitry Andric ScalarEvolution &SE, LoopInfo &LI, 4385ffd83dbSDimitry Andric MemorySSA *MSSA, 4395ffd83dbSDimitry Andric OptimizationRemarkEmitter &ORE) { 4400b57cec5SDimitry Andric assert(L->isLCSSAForm(DT) && "Expected LCSSA!"); 4410b57cec5SDimitry Andric 4420b57cec5SDimitry Andric // We can only remove the loop if there is a preheader that we can branch from 4430b57cec5SDimitry Andric // after removing it. Also, if LoopSimplify form is not available, stay out 4440b57cec5SDimitry Andric // of trouble. 4450b57cec5SDimitry Andric BasicBlock *Preheader = L->getLoopPreheader(); 4460b57cec5SDimitry Andric if (!Preheader || !L->hasDedicatedExits()) { 4470b57cec5SDimitry Andric LLVM_DEBUG( 4480b57cec5SDimitry Andric dbgs() 4490b57cec5SDimitry Andric << "Deletion requires Loop with preheader and dedicated exits.\n"); 4500b57cec5SDimitry Andric return LoopDeletionResult::Unmodified; 4510b57cec5SDimitry Andric } 4520b57cec5SDimitry Andric 4530b57cec5SDimitry Andric BasicBlock *ExitBlock = L->getUniqueExitBlock(); 4540b57cec5SDimitry Andric 4557a6dacacSDimitry Andric // We can't directly branch to an EH pad. Don't bother handling this edge 4567a6dacacSDimitry Andric // case. 4577a6dacacSDimitry Andric if (ExitBlock && ExitBlock->isEHPad()) { 4587a6dacacSDimitry Andric LLVM_DEBUG(dbgs() << "Cannot delete loop exiting to EH pad.\n"); 4597a6dacacSDimitry Andric return LoopDeletionResult::Unmodified; 4607a6dacacSDimitry Andric } 4617a6dacacSDimitry Andric 4620b57cec5SDimitry Andric if (ExitBlock && isLoopNeverExecuted(L)) { 463bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Loop is proven to never execute, delete it!\n"); 464e8d8bef9SDimitry Andric // We need to forget the loop before setting the incoming values of the exit 46581ad6265SDimitry Andric // phis to poison, so we properly invalidate the SCEV expressions for those 466e8d8bef9SDimitry Andric // phis. 467e8d8bef9SDimitry Andric SE.forgetLoop(L); 46881ad6265SDimitry Andric // Set incoming value to poison for phi nodes in the exit block. 4690b57cec5SDimitry Andric for (PHINode &P : ExitBlock->phis()) { 4700b57cec5SDimitry Andric std::fill(P.incoming_values().begin(), P.incoming_values().end(), 47181ad6265SDimitry Andric PoisonValue::get(P.getType())); 4720b57cec5SDimitry Andric } 4735ffd83dbSDimitry Andric ORE.emit([&]() { 4745ffd83dbSDimitry Andric return OptimizationRemark(DEBUG_TYPE, "NeverExecutes", L->getStartLoc(), 4755ffd83dbSDimitry Andric L->getHeader()) 4765ffd83dbSDimitry Andric << "Loop deleted because it never executes"; 4775ffd83dbSDimitry Andric }); 4785ffd83dbSDimitry Andric deleteDeadLoop(L, &DT, &SE, &LI, MSSA); 4790b57cec5SDimitry Andric ++NumDeleted; 4800b57cec5SDimitry Andric return LoopDeletionResult::Deleted; 4810b57cec5SDimitry Andric } 4820b57cec5SDimitry Andric 4830b57cec5SDimitry Andric // The remaining checks below are for a loop being dead because all statements 4840b57cec5SDimitry Andric // in the loop are invariant. 4850b57cec5SDimitry Andric SmallVector<BasicBlock *, 4> ExitingBlocks; 4860b57cec5SDimitry Andric L->getExitingBlocks(ExitingBlocks); 4870b57cec5SDimitry Andric 488e8d8bef9SDimitry Andric // We require that the loop has at most one exit block. Otherwise, we'd be in 489e8d8bef9SDimitry Andric // the situation of needing to be able to solve statically which exit block 490e8d8bef9SDimitry Andric // will be branched to, or trying to preserve the branching logic in a loop 491e8d8bef9SDimitry Andric // invariant manner. 492e8d8bef9SDimitry Andric if (!ExitBlock && !L->hasNoExitBlocks()) { 493e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Deletion requires at most one exit block.\n"); 4940b57cec5SDimitry Andric return LoopDeletionResult::Unmodified; 4950b57cec5SDimitry Andric } 49606c3fb27SDimitry Andric 4970b57cec5SDimitry Andric // Finally, we have to check that the loop really is dead. 4980b57cec5SDimitry Andric bool Changed = false; 499fe6060f1SDimitry Andric if (!isLoopDead(L, SE, ExitingBlocks, ExitBlock, Changed, Preheader, LI)) { 5000b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Loop is not invariant, cannot delete.\n"); 5010b57cec5SDimitry Andric return Changed ? LoopDeletionResult::Modified 5020b57cec5SDimitry Andric : LoopDeletionResult::Unmodified; 5030b57cec5SDimitry Andric } 5040b57cec5SDimitry Andric 505bdd1243dSDimitry Andric LLVM_DEBUG(dbgs() << "Loop is invariant, delete it!\n"); 5065ffd83dbSDimitry Andric ORE.emit([&]() { 5075ffd83dbSDimitry Andric return OptimizationRemark(DEBUG_TYPE, "Invariant", L->getStartLoc(), 5085ffd83dbSDimitry Andric L->getHeader()) 5095ffd83dbSDimitry Andric << "Loop deleted because it is invariant"; 5105ffd83dbSDimitry Andric }); 5115ffd83dbSDimitry Andric deleteDeadLoop(L, &DT, &SE, &LI, MSSA); 5120b57cec5SDimitry Andric ++NumDeleted; 5130b57cec5SDimitry Andric 5140b57cec5SDimitry Andric return LoopDeletionResult::Deleted; 5150b57cec5SDimitry Andric } 5160b57cec5SDimitry Andric 5170b57cec5SDimitry Andric PreservedAnalyses LoopDeletionPass::run(Loop &L, LoopAnalysisManager &AM, 5180b57cec5SDimitry Andric LoopStandardAnalysisResults &AR, 5190b57cec5SDimitry Andric LPMUpdater &Updater) { 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Analyzing Loop for deletion: "); 5220b57cec5SDimitry Andric LLVM_DEBUG(L.dump()); 5235ffd83dbSDimitry Andric std::string LoopName = std::string(L.getName()); 5245ffd83dbSDimitry Andric // For the new PM, we can't use OptimizationRemarkEmitter as an analysis 5255ffd83dbSDimitry Andric // pass. Function analyses need to be preserved across loop transformations 5265ffd83dbSDimitry Andric // but ORE cannot be preserved (see comment before the pass definition). 5275ffd83dbSDimitry Andric OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 5285ffd83dbSDimitry Andric auto Result = deleteLoopIfDead(&L, AR.DT, AR.SE, AR.LI, AR.MSSA, ORE); 529e8d8bef9SDimitry Andric 530e8d8bef9SDimitry Andric // If we can prove the backedge isn't taken, just break it and be done. This 531e8d8bef9SDimitry Andric // leaves the loop structure in place which means it can handle dispatching 532e8d8bef9SDimitry Andric // to the right exit based on whatever loop invariant structure remains. 533e8d8bef9SDimitry Andric if (Result != LoopDeletionResult::Deleted) 534e8d8bef9SDimitry Andric Result = merge(Result, breakBackedgeIfNotTaken(&L, AR.DT, AR.SE, AR.LI, 535e8d8bef9SDimitry Andric AR.MSSA, ORE)); 536e8d8bef9SDimitry Andric 5370b57cec5SDimitry Andric if (Result == LoopDeletionResult::Unmodified) 5380b57cec5SDimitry Andric return PreservedAnalyses::all(); 5390b57cec5SDimitry Andric 5400b57cec5SDimitry Andric if (Result == LoopDeletionResult::Deleted) 5410b57cec5SDimitry Andric Updater.markLoopAsDeleted(L, LoopName); 5420b57cec5SDimitry Andric 5435ffd83dbSDimitry Andric auto PA = getLoopPassPreservedAnalyses(); 5445ffd83dbSDimitry Andric if (AR.MSSA) 5455ffd83dbSDimitry Andric PA.preserve<MemorySSAAnalysis>(); 5465ffd83dbSDimitry Andric return PA; 5470b57cec5SDimitry Andric } 548