1a369a457SEugene Zelenko //===- SimpleLoopUnswitch.cpp - Hoist loop-invariant control flow ---------===// 21353f9a4SChandler Carruth // 31353f9a4SChandler Carruth // The LLVM Compiler Infrastructure 41353f9a4SChandler Carruth // 51353f9a4SChandler Carruth // This file is distributed under the University of Illinois Open Source 61353f9a4SChandler Carruth // License. See LICENSE.TXT for details. 71353f9a4SChandler Carruth // 81353f9a4SChandler Carruth //===----------------------------------------------------------------------===// 91353f9a4SChandler Carruth 106bda14b3SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 11a369a457SEugene Zelenko #include "llvm/ADT/DenseMap.h" 126bda14b3SChandler Carruth #include "llvm/ADT/STLExtras.h" 13a369a457SEugene Zelenko #include "llvm/ADT/Sequence.h" 14a369a457SEugene Zelenko #include "llvm/ADT/SetVector.h" 151353f9a4SChandler Carruth #include "llvm/ADT/SmallPtrSet.h" 16a369a457SEugene Zelenko #include "llvm/ADT/SmallVector.h" 171353f9a4SChandler Carruth #include "llvm/ADT/Statistic.h" 18a369a457SEugene Zelenko #include "llvm/ADT/Twine.h" 191353f9a4SChandler Carruth #include "llvm/Analysis/AssumptionCache.h" 20693eedb1SChandler Carruth #include "llvm/Analysis/CodeMetrics.h" 21a369a457SEugene Zelenko #include "llvm/Analysis/LoopAnalysisManager.h" 221353f9a4SChandler Carruth #include "llvm/Analysis/LoopInfo.h" 231353f9a4SChandler Carruth #include "llvm/Analysis/LoopPass.h" 24a369a457SEugene Zelenko #include "llvm/IR/BasicBlock.h" 25a369a457SEugene Zelenko #include "llvm/IR/Constant.h" 261353f9a4SChandler Carruth #include "llvm/IR/Constants.h" 271353f9a4SChandler Carruth #include "llvm/IR/Dominators.h" 281353f9a4SChandler Carruth #include "llvm/IR/Function.h" 29a369a457SEugene Zelenko #include "llvm/IR/InstrTypes.h" 30a369a457SEugene Zelenko #include "llvm/IR/Instruction.h" 311353f9a4SChandler Carruth #include "llvm/IR/Instructions.h" 32693eedb1SChandler Carruth #include "llvm/IR/IntrinsicInst.h" 33a369a457SEugene Zelenko #include "llvm/IR/Use.h" 34a369a457SEugene Zelenko #include "llvm/IR/Value.h" 35a369a457SEugene Zelenko #include "llvm/Pass.h" 36a369a457SEugene Zelenko #include "llvm/Support/Casting.h" 371353f9a4SChandler Carruth #include "llvm/Support/Debug.h" 38a369a457SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 39a369a457SEugene Zelenko #include "llvm/Support/GenericDomTree.h" 401353f9a4SChandler Carruth #include "llvm/Support/raw_ostream.h" 41693eedb1SChandler Carruth #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 421353f9a4SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43693eedb1SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h" 441353f9a4SChandler Carruth #include "llvm/Transforms/Utils/LoopUtils.h" 45693eedb1SChandler Carruth #include "llvm/Transforms/Utils/ValueMapper.h" 46a369a457SEugene Zelenko #include <algorithm> 47a369a457SEugene Zelenko #include <cassert> 48a369a457SEugene Zelenko #include <iterator> 49693eedb1SChandler Carruth #include <numeric> 50a369a457SEugene Zelenko #include <utility> 511353f9a4SChandler Carruth 521353f9a4SChandler Carruth #define DEBUG_TYPE "simple-loop-unswitch" 531353f9a4SChandler Carruth 541353f9a4SChandler Carruth using namespace llvm; 551353f9a4SChandler Carruth 561353f9a4SChandler Carruth STATISTIC(NumBranches, "Number of branches unswitched"); 571353f9a4SChandler Carruth STATISTIC(NumSwitches, "Number of switches unswitched"); 581353f9a4SChandler Carruth STATISTIC(NumTrivial, "Number of unswitches that are trivial"); 591353f9a4SChandler Carruth 60693eedb1SChandler Carruth static cl::opt<bool> EnableNonTrivialUnswitch( 61693eedb1SChandler Carruth "enable-nontrivial-unswitch", cl::init(false), cl::Hidden, 62693eedb1SChandler Carruth cl::desc("Forcibly enables non-trivial loop unswitching rather than " 63693eedb1SChandler Carruth "following the configuration passed into the pass.")); 64693eedb1SChandler Carruth 65693eedb1SChandler Carruth static cl::opt<int> 66693eedb1SChandler Carruth UnswitchThreshold("unswitch-threshold", cl::init(50), cl::Hidden, 67693eedb1SChandler Carruth cl::desc("The cost threshold for unswitching a loop.")); 68693eedb1SChandler Carruth 691353f9a4SChandler Carruth static void replaceLoopUsesWithConstant(Loop &L, Value &LIC, 701353f9a4SChandler Carruth Constant &Replacement) { 711353f9a4SChandler Carruth assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?"); 721353f9a4SChandler Carruth 731353f9a4SChandler Carruth // Replace uses of LIC in the loop with the given constant. 741353f9a4SChandler Carruth for (auto UI = LIC.use_begin(), UE = LIC.use_end(); UI != UE;) { 751353f9a4SChandler Carruth // Grab the use and walk past it so we can clobber it in the use list. 761353f9a4SChandler Carruth Use *U = &*UI++; 771353f9a4SChandler Carruth Instruction *UserI = dyn_cast<Instruction>(U->getUser()); 781353f9a4SChandler Carruth if (!UserI || !L.contains(UserI)) 791353f9a4SChandler Carruth continue; 801353f9a4SChandler Carruth 811353f9a4SChandler Carruth // Replace this use within the loop body. 821353f9a4SChandler Carruth *U = &Replacement; 831353f9a4SChandler Carruth } 841353f9a4SChandler Carruth } 851353f9a4SChandler Carruth 86693eedb1SChandler Carruth /// Update the IDom for a basic block whose predecessor set has changed. 87693eedb1SChandler Carruth /// 88693eedb1SChandler Carruth /// This routine is designed to work when the domtree update is relatively 89693eedb1SChandler Carruth /// localized by leveraging a known common dominator, often a loop header. 90693eedb1SChandler Carruth /// 91693eedb1SChandler Carruth /// FIXME: Should consider hand-rolling a slightly more efficient non-DFS 92693eedb1SChandler Carruth /// approach here as we can do that easily by persisting the candidate IDom's 93693eedb1SChandler Carruth /// dominating set between each predecessor. 94693eedb1SChandler Carruth /// 95693eedb1SChandler Carruth /// FIXME: Longer term, many uses of this can be replaced by an incremental 96693eedb1SChandler Carruth /// domtree update strategy that starts from a known dominating block and 97693eedb1SChandler Carruth /// rebuilds that subtree. 98693eedb1SChandler Carruth static bool updateIDomWithKnownCommonDominator(BasicBlock *BB, 99693eedb1SChandler Carruth BasicBlock *KnownDominatingBB, 1001353f9a4SChandler Carruth DominatorTree &DT) { 101693eedb1SChandler Carruth assert(pred_begin(BB) != pred_end(BB) && 102693eedb1SChandler Carruth "This routine does not handle unreachable blocks!"); 1031353f9a4SChandler Carruth 104693eedb1SChandler Carruth BasicBlock *OrigIDom = DT[BB]->getIDom()->getBlock(); 105693eedb1SChandler Carruth 106693eedb1SChandler Carruth BasicBlock *IDom = *pred_begin(BB); 107693eedb1SChandler Carruth assert(DT.dominates(KnownDominatingBB, IDom) && 108693eedb1SChandler Carruth "Bad known dominating block!"); 109693eedb1SChandler Carruth 1101353f9a4SChandler Carruth // Walk all of the other predecessors finding the nearest common dominator 1111353f9a4SChandler Carruth // until all predecessors are covered or we reach the loop header. The loop 1121353f9a4SChandler Carruth // header necessarily dominates all loop exit blocks in loop simplified form 1131353f9a4SChandler Carruth // so we can early-exit the moment we hit that block. 114693eedb1SChandler Carruth for (auto PI = std::next(pred_begin(BB)), PE = pred_end(BB); 115693eedb1SChandler Carruth PI != PE && IDom != KnownDominatingBB; ++PI) { 116693eedb1SChandler Carruth assert(DT.dominates(KnownDominatingBB, *PI) && 117693eedb1SChandler Carruth "Bad known dominating block!"); 1181353f9a4SChandler Carruth IDom = DT.findNearestCommonDominator(IDom, *PI); 119693eedb1SChandler Carruth } 1201353f9a4SChandler Carruth 121693eedb1SChandler Carruth if (IDom == OrigIDom) 122693eedb1SChandler Carruth return false; 123693eedb1SChandler Carruth 124693eedb1SChandler Carruth DT.changeImmediateDominator(BB, IDom); 125693eedb1SChandler Carruth return true; 126693eedb1SChandler Carruth } 127693eedb1SChandler Carruth 128693eedb1SChandler Carruth // Note that we don't currently use the IDFCalculator here for two reasons: 129693eedb1SChandler Carruth // 1) It computes dominator tree levels for the entire function on each run 130693eedb1SChandler Carruth // of 'compute'. While this isn't terrible, given that we expect to update 131693eedb1SChandler Carruth // relatively small subtrees of the domtree, it isn't necessarily the right 132693eedb1SChandler Carruth // tradeoff. 133693eedb1SChandler Carruth // 2) The interface doesn't fit this usage well. It doesn't operate in 134693eedb1SChandler Carruth // append-only, and builds several sets that we don't need. 135693eedb1SChandler Carruth // 136693eedb1SChandler Carruth // FIXME: Neither of these issues are a big deal and could be addressed with 137693eedb1SChandler Carruth // some amount of refactoring of IDFCalculator. That would allow us to share 138693eedb1SChandler Carruth // the core logic here (which is solving the same core problem). 139*51ebcaafSBenjamin Kramer static void appendDomFrontier(DomTreeNode *Node, 140693eedb1SChandler Carruth SmallSetVector<BasicBlock *, 4> &Worklist, 141693eedb1SChandler Carruth SmallVectorImpl<DomTreeNode *> &DomNodes, 142693eedb1SChandler Carruth SmallPtrSetImpl<BasicBlock *> &DomSet) { 143693eedb1SChandler Carruth assert(DomNodes.empty() && "Must start with no dominator nodes."); 144693eedb1SChandler Carruth assert(DomSet.empty() && "Must start with an empty dominator set."); 145693eedb1SChandler Carruth 146693eedb1SChandler Carruth // First flatten this subtree into sequence of nodes by doing a pre-order 147693eedb1SChandler Carruth // walk. 148693eedb1SChandler Carruth DomNodes.push_back(Node); 149693eedb1SChandler Carruth // We intentionally re-evaluate the size as each node can add new children. 150693eedb1SChandler Carruth // Because this is a tree walk, this cannot add any duplicates. 151693eedb1SChandler Carruth for (int i = 0; i < (int)DomNodes.size(); ++i) 152693eedb1SChandler Carruth DomNodes.insert(DomNodes.end(), DomNodes[i]->begin(), DomNodes[i]->end()); 153693eedb1SChandler Carruth 154693eedb1SChandler Carruth // Now create a set of the basic blocks so we can quickly test for 155693eedb1SChandler Carruth // dominated successors. We could in theory use the DFS numbers of the 156693eedb1SChandler Carruth // dominator tree for this, but we want this to remain predictably fast 157693eedb1SChandler Carruth // even while we mutate the dominator tree in ways that would invalidate 158693eedb1SChandler Carruth // the DFS numbering. 159693eedb1SChandler Carruth for (DomTreeNode *InnerN : DomNodes) 160693eedb1SChandler Carruth DomSet.insert(InnerN->getBlock()); 161693eedb1SChandler Carruth 162693eedb1SChandler Carruth // Now re-walk the nodes, appending every successor of every node that isn't 163693eedb1SChandler Carruth // in the set. Note that we don't append the node itself, even though if it 164693eedb1SChandler Carruth // is a successor it does not strictly dominate itself and thus it would be 165693eedb1SChandler Carruth // part of the dominance frontier. The reason we don't append it is that 166693eedb1SChandler Carruth // the node passed in came *from* the worklist and so it has already been 167693eedb1SChandler Carruth // processed. 168693eedb1SChandler Carruth for (DomTreeNode *InnerN : DomNodes) 169693eedb1SChandler Carruth for (BasicBlock *SuccBB : successors(InnerN->getBlock())) 170693eedb1SChandler Carruth if (!DomSet.count(SuccBB)) 171693eedb1SChandler Carruth Worklist.insert(SuccBB); 172693eedb1SChandler Carruth 173693eedb1SChandler Carruth DomNodes.clear(); 174693eedb1SChandler Carruth DomSet.clear(); 1751353f9a4SChandler Carruth } 1761353f9a4SChandler Carruth 1771353f9a4SChandler Carruth /// Update the dominator tree after unswitching a particular former exit block. 1781353f9a4SChandler Carruth /// 1791353f9a4SChandler Carruth /// This handles the full update of the dominator tree after hoisting a block 1801353f9a4SChandler Carruth /// that previously was an exit block (or split off of an exit block) up to be 1811353f9a4SChandler Carruth /// reached from the new immediate dominator of the preheader. 1821353f9a4SChandler Carruth /// 1831353f9a4SChandler Carruth /// The common case is simple -- we just move the unswitched block to have an 1841353f9a4SChandler Carruth /// immediate dominator of the old preheader. But in complex cases, there may 1851353f9a4SChandler Carruth /// be other blocks reachable from the unswitched block that are immediately 1861353f9a4SChandler Carruth /// dominated by some node between the unswitched one and the old preheader. 1871353f9a4SChandler Carruth /// All of these also need to be hoisted in the dominator tree. We also want to 1881353f9a4SChandler Carruth /// minimize queries to the dominator tree because each step of this 1891353f9a4SChandler Carruth /// invalidates any DFS numbers that would make queries fast. 1901353f9a4SChandler Carruth static void updateDTAfterUnswitch(BasicBlock *UnswitchedBB, BasicBlock *OldPH, 1911353f9a4SChandler Carruth DominatorTree &DT) { 1921353f9a4SChandler Carruth DomTreeNode *OldPHNode = DT[OldPH]; 1931353f9a4SChandler Carruth DomTreeNode *UnswitchedNode = DT[UnswitchedBB]; 1941353f9a4SChandler Carruth // If the dominator tree has already been updated for this unswitched node, 1951353f9a4SChandler Carruth // we're done. This makes it easier to use this routine if there are multiple 1961353f9a4SChandler Carruth // paths to the same unswitched destination. 1971353f9a4SChandler Carruth if (UnswitchedNode->getIDom() == OldPHNode) 1981353f9a4SChandler Carruth return; 1991353f9a4SChandler Carruth 2001353f9a4SChandler Carruth // First collect the domtree nodes that we are hoisting over. These are the 2011353f9a4SChandler Carruth // set of nodes which may have children that need to be hoisted as well. 2021353f9a4SChandler Carruth SmallPtrSet<DomTreeNode *, 4> DomChain; 2031353f9a4SChandler Carruth for (auto *IDom = UnswitchedNode->getIDom(); IDom != OldPHNode; 2041353f9a4SChandler Carruth IDom = IDom->getIDom()) 2051353f9a4SChandler Carruth DomChain.insert(IDom); 2061353f9a4SChandler Carruth 2071353f9a4SChandler Carruth // The unswitched block ends up immediately dominated by the old preheader -- 2081353f9a4SChandler Carruth // regardless of whether it is the loop exit block or split off of the loop 2091353f9a4SChandler Carruth // exit block. 2101353f9a4SChandler Carruth DT.changeImmediateDominator(UnswitchedNode, OldPHNode); 2111353f9a4SChandler Carruth 212dd2e275aSChandler Carruth // For everything that moves up the dominator tree, we need to examine the 213dd2e275aSChandler Carruth // dominator frontier to see if it additionally should move up the dominator 214dd2e275aSChandler Carruth // tree. This lambda appends the dominator frontier for a node on the 215dd2e275aSChandler Carruth // worklist. 2161353f9a4SChandler Carruth SmallSetVector<BasicBlock *, 4> Worklist; 217693eedb1SChandler Carruth 218693eedb1SChandler Carruth // Scratch data structures reused by domfrontier finding. 219dd2e275aSChandler Carruth SmallVector<DomTreeNode *, 4> DomNodes; 220dd2e275aSChandler Carruth SmallPtrSet<BasicBlock *, 4> DomSet; 221dd2e275aSChandler Carruth 222dd2e275aSChandler Carruth // Append the initial dom frontier nodes. 223693eedb1SChandler Carruth appendDomFrontier(UnswitchedNode, Worklist, DomNodes, DomSet); 224dd2e275aSChandler Carruth 2251353f9a4SChandler Carruth // Walk the worklist. We grow the list in the loop and so must recompute size. 2261353f9a4SChandler Carruth for (int i = 0; i < (int)Worklist.size(); ++i) { 2271353f9a4SChandler Carruth auto *BB = Worklist[i]; 2281353f9a4SChandler Carruth 2291353f9a4SChandler Carruth DomTreeNode *Node = DT[BB]; 2301353f9a4SChandler Carruth assert(!DomChain.count(Node) && 2311353f9a4SChandler Carruth "Cannot be dominated by a block you can reach!"); 232dd2e275aSChandler Carruth 233dd2e275aSChandler Carruth // If this block had an immediate dominator somewhere in the chain 234dd2e275aSChandler Carruth // we hoisted over, then its position in the domtree needs to move as it is 235dd2e275aSChandler Carruth // reachable from a node hoisted over this chain. 2361353f9a4SChandler Carruth if (!DomChain.count(Node->getIDom())) 2371353f9a4SChandler Carruth continue; 2381353f9a4SChandler Carruth 2391353f9a4SChandler Carruth DT.changeImmediateDominator(Node, OldPHNode); 240dd2e275aSChandler Carruth 241dd2e275aSChandler Carruth // Now add this node's dominator frontier to the worklist as well. 242693eedb1SChandler Carruth appendDomFrontier(Node, Worklist, DomNodes, DomSet); 2431353f9a4SChandler Carruth } 2441353f9a4SChandler Carruth } 2451353f9a4SChandler Carruth 246d869b188SChandler Carruth /// Check that all the LCSSA PHI nodes in the loop exit block have trivial 247d869b188SChandler Carruth /// incoming values along this edge. 248d869b188SChandler Carruth static bool areLoopExitPHIsLoopInvariant(Loop &L, BasicBlock &ExitingBB, 249d869b188SChandler Carruth BasicBlock &ExitBB) { 250d869b188SChandler Carruth for (Instruction &I : ExitBB) { 251d869b188SChandler Carruth auto *PN = dyn_cast<PHINode>(&I); 252d869b188SChandler Carruth if (!PN) 253d869b188SChandler Carruth // No more PHIs to check. 254d869b188SChandler Carruth return true; 255d869b188SChandler Carruth 256d869b188SChandler Carruth // If the incoming value for this edge isn't loop invariant the unswitch 257d869b188SChandler Carruth // won't be trivial. 258d869b188SChandler Carruth if (!L.isLoopInvariant(PN->getIncomingValueForBlock(&ExitingBB))) 259d869b188SChandler Carruth return false; 260d869b188SChandler Carruth } 261d869b188SChandler Carruth llvm_unreachable("Basic blocks should never be empty!"); 262d869b188SChandler Carruth } 263d869b188SChandler Carruth 264d869b188SChandler Carruth /// Rewrite the PHI nodes in an unswitched loop exit basic block. 265d869b188SChandler Carruth /// 266d869b188SChandler Carruth /// Requires that the loop exit and unswitched basic block are the same, and 267d869b188SChandler Carruth /// that the exiting block was a unique predecessor of that block. Rewrites the 268d869b188SChandler Carruth /// PHI nodes in that block such that what were LCSSA PHI nodes become trivial 269d869b188SChandler Carruth /// PHI nodes from the old preheader that now contains the unswitched 270d869b188SChandler Carruth /// terminator. 271d869b188SChandler Carruth static void rewritePHINodesForUnswitchedExitBlock(BasicBlock &UnswitchedBB, 272d869b188SChandler Carruth BasicBlock &OldExitingBB, 273d869b188SChandler Carruth BasicBlock &OldPH) { 274d869b188SChandler Carruth for (Instruction &I : UnswitchedBB) { 275d869b188SChandler Carruth auto *PN = dyn_cast<PHINode>(&I); 276d869b188SChandler Carruth if (!PN) 277d869b188SChandler Carruth // No more PHIs to check. 278d869b188SChandler Carruth break; 279d869b188SChandler Carruth 280d869b188SChandler Carruth // When the loop exit is directly unswitched we just need to update the 281d869b188SChandler Carruth // incoming basic block. We loop to handle weird cases with repeated 282d869b188SChandler Carruth // incoming blocks, but expect to typically only have one operand here. 283a369a457SEugene Zelenko for (auto i : seq<int>(0, PN->getNumOperands())) { 284d869b188SChandler Carruth assert(PN->getIncomingBlock(i) == &OldExitingBB && 285d869b188SChandler Carruth "Found incoming block different from unique predecessor!"); 286d869b188SChandler Carruth PN->setIncomingBlock(i, &OldPH); 287d869b188SChandler Carruth } 288d869b188SChandler Carruth } 289d869b188SChandler Carruth } 290d869b188SChandler Carruth 291d869b188SChandler Carruth /// Rewrite the PHI nodes in the loop exit basic block and the split off 292d869b188SChandler Carruth /// unswitched block. 293d869b188SChandler Carruth /// 294d869b188SChandler Carruth /// Because the exit block remains an exit from the loop, this rewrites the 295d869b188SChandler Carruth /// LCSSA PHI nodes in it to remove the unswitched edge and introduces PHI 296d869b188SChandler Carruth /// nodes into the unswitched basic block to select between the value in the 297d869b188SChandler Carruth /// old preheader and the loop exit. 298d869b188SChandler Carruth static void rewritePHINodesForExitAndUnswitchedBlocks(BasicBlock &ExitBB, 299d869b188SChandler Carruth BasicBlock &UnswitchedBB, 300d869b188SChandler Carruth BasicBlock &OldExitingBB, 301d869b188SChandler Carruth BasicBlock &OldPH) { 302d869b188SChandler Carruth assert(&ExitBB != &UnswitchedBB && 303d869b188SChandler Carruth "Must have different loop exit and unswitched blocks!"); 304d869b188SChandler Carruth Instruction *InsertPt = &*UnswitchedBB.begin(); 305d869b188SChandler Carruth for (Instruction &I : ExitBB) { 306d869b188SChandler Carruth auto *PN = dyn_cast<PHINode>(&I); 307d869b188SChandler Carruth if (!PN) 308d869b188SChandler Carruth // No more PHIs to check. 309d869b188SChandler Carruth break; 310d869b188SChandler Carruth 311d869b188SChandler Carruth auto *NewPN = PHINode::Create(PN->getType(), /*NumReservedValues*/ 2, 312d869b188SChandler Carruth PN->getName() + ".split", InsertPt); 313d869b188SChandler Carruth 314d869b188SChandler Carruth // Walk backwards over the old PHI node's inputs to minimize the cost of 315d869b188SChandler Carruth // removing each one. We have to do this weird loop manually so that we 316d869b188SChandler Carruth // create the same number of new incoming edges in the new PHI as we expect 317d869b188SChandler Carruth // each case-based edge to be included in the unswitched switch in some 318d869b188SChandler Carruth // cases. 319d869b188SChandler Carruth // FIXME: This is really, really gross. It would be much cleaner if LLVM 320d869b188SChandler Carruth // allowed us to create a single entry for a predecessor block without 321d869b188SChandler Carruth // having separate entries for each "edge" even though these edges are 322d869b188SChandler Carruth // required to produce identical results. 323d869b188SChandler Carruth for (int i = PN->getNumIncomingValues() - 1; i >= 0; --i) { 324d869b188SChandler Carruth if (PN->getIncomingBlock(i) != &OldExitingBB) 325d869b188SChandler Carruth continue; 326d869b188SChandler Carruth 327d869b188SChandler Carruth Value *Incoming = PN->removeIncomingValue(i); 328d869b188SChandler Carruth NewPN->addIncoming(Incoming, &OldPH); 329d869b188SChandler Carruth } 330d869b188SChandler Carruth 331d869b188SChandler Carruth // Now replace the old PHI with the new one and wire the old one in as an 332d869b188SChandler Carruth // input to the new one. 333d869b188SChandler Carruth PN->replaceAllUsesWith(NewPN); 334d869b188SChandler Carruth NewPN->addIncoming(PN, &ExitBB); 335d869b188SChandler Carruth } 336d869b188SChandler Carruth } 337d869b188SChandler Carruth 3381353f9a4SChandler Carruth /// Unswitch a trivial branch if the condition is loop invariant. 3391353f9a4SChandler Carruth /// 3401353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the branch has 3411353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the 3421353f9a4SChandler Carruth /// condition is invariant and one of the successors is a loop exit. This 3431353f9a4SChandler Carruth /// allows us to unswitch without duplicating the loop, making it trivial. 3441353f9a4SChandler Carruth /// 3451353f9a4SChandler Carruth /// If this routine fails to unswitch the branch it returns false. 3461353f9a4SChandler Carruth /// 3471353f9a4SChandler Carruth /// If the branch can be unswitched, this routine splits the preheader and 3481353f9a4SChandler Carruth /// hoists the branch above that split. Preserves loop simplified form 3491353f9a4SChandler Carruth /// (splitting the exit block as necessary). It simplifies the branch within 3501353f9a4SChandler Carruth /// the loop to an unconditional branch but doesn't remove it entirely. Further 3511353f9a4SChandler Carruth /// cleanup can be done with some simplify-cfg like pass. 3521353f9a4SChandler Carruth static bool unswitchTrivialBranch(Loop &L, BranchInst &BI, DominatorTree &DT, 3531353f9a4SChandler Carruth LoopInfo &LI) { 3541353f9a4SChandler Carruth assert(BI.isConditional() && "Can only unswitch a conditional branch!"); 3551353f9a4SChandler Carruth DEBUG(dbgs() << " Trying to unswitch branch: " << BI << "\n"); 3561353f9a4SChandler Carruth 3571353f9a4SChandler Carruth Value *LoopCond = BI.getCondition(); 3581353f9a4SChandler Carruth 3591353f9a4SChandler Carruth // Need a trivial loop condition to unswitch. 3601353f9a4SChandler Carruth if (!L.isLoopInvariant(LoopCond)) 3611353f9a4SChandler Carruth return false; 3621353f9a4SChandler Carruth 3631353f9a4SChandler Carruth // FIXME: We should compute this once at the start and update it! 3641353f9a4SChandler Carruth SmallVector<BasicBlock *, 16> ExitBlocks; 3651353f9a4SChandler Carruth L.getExitBlocks(ExitBlocks); 3661353f9a4SChandler Carruth SmallPtrSet<BasicBlock *, 16> ExitBlockSet(ExitBlocks.begin(), 3671353f9a4SChandler Carruth ExitBlocks.end()); 3681353f9a4SChandler Carruth 3691353f9a4SChandler Carruth // Check to see if a successor of the branch is guaranteed to 3701353f9a4SChandler Carruth // exit through a unique exit block without having any 3711353f9a4SChandler Carruth // side-effects. If so, determine the value of Cond that causes 3721353f9a4SChandler Carruth // it to do this. 3731353f9a4SChandler Carruth ConstantInt *CondVal = ConstantInt::getTrue(BI.getContext()); 3741353f9a4SChandler Carruth ConstantInt *Replacement = ConstantInt::getFalse(BI.getContext()); 3751353f9a4SChandler Carruth int LoopExitSuccIdx = 0; 3761353f9a4SChandler Carruth auto *LoopExitBB = BI.getSuccessor(0); 3771353f9a4SChandler Carruth if (!ExitBlockSet.count(LoopExitBB)) { 3781353f9a4SChandler Carruth std::swap(CondVal, Replacement); 3791353f9a4SChandler Carruth LoopExitSuccIdx = 1; 3801353f9a4SChandler Carruth LoopExitBB = BI.getSuccessor(1); 3811353f9a4SChandler Carruth if (!ExitBlockSet.count(LoopExitBB)) 3821353f9a4SChandler Carruth return false; 3831353f9a4SChandler Carruth } 3841353f9a4SChandler Carruth auto *ContinueBB = BI.getSuccessor(1 - LoopExitSuccIdx); 3851353f9a4SChandler Carruth assert(L.contains(ContinueBB) && 3861353f9a4SChandler Carruth "Cannot have both successors exit and still be in the loop!"); 3871353f9a4SChandler Carruth 388d869b188SChandler Carruth auto *ParentBB = BI.getParent(); 389d869b188SChandler Carruth if (!areLoopExitPHIsLoopInvariant(L, *ParentBB, *LoopExitBB)) 3901353f9a4SChandler Carruth return false; 3911353f9a4SChandler Carruth 3921353f9a4SChandler Carruth DEBUG(dbgs() << " unswitching trivial branch when: " << CondVal 3931353f9a4SChandler Carruth << " == " << LoopCond << "\n"); 3941353f9a4SChandler Carruth 3951353f9a4SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert 3961353f9a4SChandler Carruth // the conditional branch. We will change the preheader to have a conditional 3971353f9a4SChandler Carruth // branch on LoopCond. 3981353f9a4SChandler Carruth BasicBlock *OldPH = L.getLoopPreheader(); 3991353f9a4SChandler Carruth BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI); 4001353f9a4SChandler Carruth 4011353f9a4SChandler Carruth // Now that we have a place to insert the conditional branch, create a place 4021353f9a4SChandler Carruth // to branch to: this is the exit block out of the loop that we are 4031353f9a4SChandler Carruth // unswitching. We need to split this if there are other loop predecessors. 4041353f9a4SChandler Carruth // Because the loop is in simplified form, *any* other predecessor is enough. 4051353f9a4SChandler Carruth BasicBlock *UnswitchedBB; 4061353f9a4SChandler Carruth if (BasicBlock *PredBB = LoopExitBB->getUniquePredecessor()) { 4071353f9a4SChandler Carruth (void)PredBB; 408d869b188SChandler Carruth assert(PredBB == BI.getParent() && 409d869b188SChandler Carruth "A branch's parent isn't a predecessor!"); 4101353f9a4SChandler Carruth UnswitchedBB = LoopExitBB; 4111353f9a4SChandler Carruth } else { 4121353f9a4SChandler Carruth UnswitchedBB = SplitBlock(LoopExitBB, &LoopExitBB->front(), &DT, &LI); 4131353f9a4SChandler Carruth } 4141353f9a4SChandler Carruth 4151353f9a4SChandler Carruth // Now splice the branch to gate reaching the new preheader and re-point its 4161353f9a4SChandler Carruth // successors. 4171353f9a4SChandler Carruth OldPH->getInstList().splice(std::prev(OldPH->end()), 4181353f9a4SChandler Carruth BI.getParent()->getInstList(), BI); 4191353f9a4SChandler Carruth OldPH->getTerminator()->eraseFromParent(); 4201353f9a4SChandler Carruth BI.setSuccessor(LoopExitSuccIdx, UnswitchedBB); 4211353f9a4SChandler Carruth BI.setSuccessor(1 - LoopExitSuccIdx, NewPH); 4221353f9a4SChandler Carruth 4231353f9a4SChandler Carruth // Create a new unconditional branch that will continue the loop as a new 4241353f9a4SChandler Carruth // terminator. 4251353f9a4SChandler Carruth BranchInst::Create(ContinueBB, ParentBB); 4261353f9a4SChandler Carruth 427d869b188SChandler Carruth // Rewrite the relevant PHI nodes. 428d869b188SChandler Carruth if (UnswitchedBB == LoopExitBB) 429d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*UnswitchedBB, *ParentBB, *OldPH); 430d869b188SChandler Carruth else 431d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*LoopExitBB, *UnswitchedBB, 432d869b188SChandler Carruth *ParentBB, *OldPH); 433d869b188SChandler Carruth 4341353f9a4SChandler Carruth // Now we need to update the dominator tree. 4351353f9a4SChandler Carruth updateDTAfterUnswitch(UnswitchedBB, OldPH, DT); 4361353f9a4SChandler Carruth // But if we split something off of the loop exit block then we also removed 4371353f9a4SChandler Carruth // one of the predecessors for the loop exit block and may need to update its 4381353f9a4SChandler Carruth // idom. 4391353f9a4SChandler Carruth if (UnswitchedBB != LoopExitBB) 440693eedb1SChandler Carruth updateIDomWithKnownCommonDominator(LoopExitBB, L.getHeader(), DT); 4411353f9a4SChandler Carruth 4421353f9a4SChandler Carruth // Since this is an i1 condition we can also trivially replace uses of it 4431353f9a4SChandler Carruth // within the loop with a constant. 4441353f9a4SChandler Carruth replaceLoopUsesWithConstant(L, *LoopCond, *Replacement); 4451353f9a4SChandler Carruth 4461353f9a4SChandler Carruth ++NumTrivial; 4471353f9a4SChandler Carruth ++NumBranches; 4481353f9a4SChandler Carruth return true; 4491353f9a4SChandler Carruth } 4501353f9a4SChandler Carruth 4511353f9a4SChandler Carruth /// Unswitch a trivial switch if the condition is loop invariant. 4521353f9a4SChandler Carruth /// 4531353f9a4SChandler Carruth /// This routine should only be called when loop code leading to the switch has 4541353f9a4SChandler Carruth /// been validated as trivial (no side effects). This routine checks if the 4551353f9a4SChandler Carruth /// condition is invariant and that at least one of the successors is a loop 4561353f9a4SChandler Carruth /// exit. This allows us to unswitch without duplicating the loop, making it 4571353f9a4SChandler Carruth /// trivial. 4581353f9a4SChandler Carruth /// 4591353f9a4SChandler Carruth /// If this routine fails to unswitch the switch it returns false. 4601353f9a4SChandler Carruth /// 4611353f9a4SChandler Carruth /// If the switch can be unswitched, this routine splits the preheader and 4621353f9a4SChandler Carruth /// copies the switch above that split. If the default case is one of the 4631353f9a4SChandler Carruth /// exiting cases, it copies the non-exiting cases and points them at the new 4641353f9a4SChandler Carruth /// preheader. If the default case is not exiting, it copies the exiting cases 4651353f9a4SChandler Carruth /// and points the default at the preheader. It preserves loop simplified form 4661353f9a4SChandler Carruth /// (splitting the exit blocks as necessary). It simplifies the switch within 4671353f9a4SChandler Carruth /// the loop by removing now-dead cases. If the default case is one of those 4681353f9a4SChandler Carruth /// unswitched, it replaces its destination with a new basic block containing 4691353f9a4SChandler Carruth /// only unreachable. Such basic blocks, while technically loop exits, are not 4701353f9a4SChandler Carruth /// considered for unswitching so this is a stable transform and the same 4711353f9a4SChandler Carruth /// switch will not be revisited. If after unswitching there is only a single 4721353f9a4SChandler Carruth /// in-loop successor, the switch is further simplified to an unconditional 4731353f9a4SChandler Carruth /// branch. Still more cleanup can be done with some simplify-cfg like pass. 4741353f9a4SChandler Carruth static bool unswitchTrivialSwitch(Loop &L, SwitchInst &SI, DominatorTree &DT, 4751353f9a4SChandler Carruth LoopInfo &LI) { 4761353f9a4SChandler Carruth DEBUG(dbgs() << " Trying to unswitch switch: " << SI << "\n"); 4771353f9a4SChandler Carruth Value *LoopCond = SI.getCondition(); 4781353f9a4SChandler Carruth 4791353f9a4SChandler Carruth // If this isn't switching on an invariant condition, we can't unswitch it. 4801353f9a4SChandler Carruth if (!L.isLoopInvariant(LoopCond)) 4811353f9a4SChandler Carruth return false; 4821353f9a4SChandler Carruth 483d869b188SChandler Carruth auto *ParentBB = SI.getParent(); 484d869b188SChandler Carruth 4851353f9a4SChandler Carruth // FIXME: We should compute this once at the start and update it! 4861353f9a4SChandler Carruth SmallVector<BasicBlock *, 16> ExitBlocks; 4871353f9a4SChandler Carruth L.getExitBlocks(ExitBlocks); 4881353f9a4SChandler Carruth SmallPtrSet<BasicBlock *, 16> ExitBlockSet(ExitBlocks.begin(), 4891353f9a4SChandler Carruth ExitBlocks.end()); 4901353f9a4SChandler Carruth 4911353f9a4SChandler Carruth SmallVector<int, 4> ExitCaseIndices; 4921353f9a4SChandler Carruth for (auto Case : SI.cases()) { 4931353f9a4SChandler Carruth auto *SuccBB = Case.getCaseSuccessor(); 494d869b188SChandler Carruth if (ExitBlockSet.count(SuccBB) && 495d869b188SChandler Carruth areLoopExitPHIsLoopInvariant(L, *ParentBB, *SuccBB)) 4961353f9a4SChandler Carruth ExitCaseIndices.push_back(Case.getCaseIndex()); 4971353f9a4SChandler Carruth } 4981353f9a4SChandler Carruth BasicBlock *DefaultExitBB = nullptr; 4991353f9a4SChandler Carruth if (ExitBlockSet.count(SI.getDefaultDest()) && 500d869b188SChandler Carruth areLoopExitPHIsLoopInvariant(L, *ParentBB, *SI.getDefaultDest()) && 5011353f9a4SChandler Carruth !isa<UnreachableInst>(SI.getDefaultDest()->getTerminator())) 5021353f9a4SChandler Carruth DefaultExitBB = SI.getDefaultDest(); 5031353f9a4SChandler Carruth else if (ExitCaseIndices.empty()) 5041353f9a4SChandler Carruth return false; 5051353f9a4SChandler Carruth 5061353f9a4SChandler Carruth DEBUG(dbgs() << " unswitching trivial cases...\n"); 5071353f9a4SChandler Carruth 5081353f9a4SChandler Carruth SmallVector<std::pair<ConstantInt *, BasicBlock *>, 4> ExitCases; 5091353f9a4SChandler Carruth ExitCases.reserve(ExitCaseIndices.size()); 5101353f9a4SChandler Carruth // We walk the case indices backwards so that we remove the last case first 5111353f9a4SChandler Carruth // and don't disrupt the earlier indices. 5121353f9a4SChandler Carruth for (unsigned Index : reverse(ExitCaseIndices)) { 5131353f9a4SChandler Carruth auto CaseI = SI.case_begin() + Index; 5141353f9a4SChandler Carruth // Save the value of this case. 5151353f9a4SChandler Carruth ExitCases.push_back({CaseI->getCaseValue(), CaseI->getCaseSuccessor()}); 5161353f9a4SChandler Carruth // Delete the unswitched cases. 5171353f9a4SChandler Carruth SI.removeCase(CaseI); 5181353f9a4SChandler Carruth } 5191353f9a4SChandler Carruth 5201353f9a4SChandler Carruth // Check if after this all of the remaining cases point at the same 5211353f9a4SChandler Carruth // successor. 5221353f9a4SChandler Carruth BasicBlock *CommonSuccBB = nullptr; 5231353f9a4SChandler Carruth if (SI.getNumCases() > 0 && 5241353f9a4SChandler Carruth std::all_of(std::next(SI.case_begin()), SI.case_end(), 5251353f9a4SChandler Carruth [&SI](const SwitchInst::CaseHandle &Case) { 5261353f9a4SChandler Carruth return Case.getCaseSuccessor() == 5271353f9a4SChandler Carruth SI.case_begin()->getCaseSuccessor(); 5281353f9a4SChandler Carruth })) 5291353f9a4SChandler Carruth CommonSuccBB = SI.case_begin()->getCaseSuccessor(); 5301353f9a4SChandler Carruth 5311353f9a4SChandler Carruth if (DefaultExitBB) { 5321353f9a4SChandler Carruth // We can't remove the default edge so replace it with an edge to either 5331353f9a4SChandler Carruth // the single common remaining successor (if we have one) or an unreachable 5341353f9a4SChandler Carruth // block. 5351353f9a4SChandler Carruth if (CommonSuccBB) { 5361353f9a4SChandler Carruth SI.setDefaultDest(CommonSuccBB); 5371353f9a4SChandler Carruth } else { 5381353f9a4SChandler Carruth BasicBlock *UnreachableBB = BasicBlock::Create( 5391353f9a4SChandler Carruth ParentBB->getContext(), 5401353f9a4SChandler Carruth Twine(ParentBB->getName()) + ".unreachable_default", 5411353f9a4SChandler Carruth ParentBB->getParent()); 5421353f9a4SChandler Carruth new UnreachableInst(ParentBB->getContext(), UnreachableBB); 5431353f9a4SChandler Carruth SI.setDefaultDest(UnreachableBB); 5441353f9a4SChandler Carruth DT.addNewBlock(UnreachableBB, ParentBB); 5451353f9a4SChandler Carruth } 5461353f9a4SChandler Carruth } else { 5471353f9a4SChandler Carruth // If we're not unswitching the default, we need it to match any cases to 5481353f9a4SChandler Carruth // have a common successor or if we have no cases it is the common 5491353f9a4SChandler Carruth // successor. 5501353f9a4SChandler Carruth if (SI.getNumCases() == 0) 5511353f9a4SChandler Carruth CommonSuccBB = SI.getDefaultDest(); 5521353f9a4SChandler Carruth else if (SI.getDefaultDest() != CommonSuccBB) 5531353f9a4SChandler Carruth CommonSuccBB = nullptr; 5541353f9a4SChandler Carruth } 5551353f9a4SChandler Carruth 5561353f9a4SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert 5571353f9a4SChandler Carruth // the switch. 5581353f9a4SChandler Carruth BasicBlock *OldPH = L.getLoopPreheader(); 5591353f9a4SChandler Carruth BasicBlock *NewPH = SplitEdge(OldPH, L.getHeader(), &DT, &LI); 5601353f9a4SChandler Carruth OldPH->getTerminator()->eraseFromParent(); 5611353f9a4SChandler Carruth 5621353f9a4SChandler Carruth // Now add the unswitched switch. 5631353f9a4SChandler Carruth auto *NewSI = SwitchInst::Create(LoopCond, NewPH, ExitCases.size(), OldPH); 5641353f9a4SChandler Carruth 565d869b188SChandler Carruth // Rewrite the IR for the unswitched basic blocks. This requires two steps. 566d869b188SChandler Carruth // First, we split any exit blocks with remaining in-loop predecessors. Then 567d869b188SChandler Carruth // we update the PHIs in one of two ways depending on if there was a split. 568d869b188SChandler Carruth // We walk in reverse so that we split in the same order as the cases 569d869b188SChandler Carruth // appeared. This is purely for convenience of reading the resulting IR, but 570d869b188SChandler Carruth // it doesn't cost anything really. 571d869b188SChandler Carruth SmallPtrSet<BasicBlock *, 2> UnswitchedExitBBs; 5721353f9a4SChandler Carruth SmallDenseMap<BasicBlock *, BasicBlock *, 2> SplitExitBBMap; 5731353f9a4SChandler Carruth // Handle the default exit if necessary. 5741353f9a4SChandler Carruth // FIXME: It'd be great if we could merge this with the loop below but LLVM's 5751353f9a4SChandler Carruth // ranges aren't quite powerful enough yet. 576d869b188SChandler Carruth if (DefaultExitBB) { 577d869b188SChandler Carruth if (pred_empty(DefaultExitBB)) { 578d869b188SChandler Carruth UnswitchedExitBBs.insert(DefaultExitBB); 579d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*DefaultExitBB, *ParentBB, *OldPH); 580d869b188SChandler Carruth } else { 5811353f9a4SChandler Carruth auto *SplitBB = 5821353f9a4SChandler Carruth SplitBlock(DefaultExitBB, &DefaultExitBB->front(), &DT, &LI); 583d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*DefaultExitBB, *SplitBB, 584d869b188SChandler Carruth *ParentBB, *OldPH); 585693eedb1SChandler Carruth updateIDomWithKnownCommonDominator(DefaultExitBB, L.getHeader(), DT); 5861353f9a4SChandler Carruth DefaultExitBB = SplitExitBBMap[DefaultExitBB] = SplitBB; 5871353f9a4SChandler Carruth } 588d869b188SChandler Carruth } 5891353f9a4SChandler Carruth // Note that we must use a reference in the for loop so that we update the 5901353f9a4SChandler Carruth // container. 5911353f9a4SChandler Carruth for (auto &CasePair : reverse(ExitCases)) { 5921353f9a4SChandler Carruth // Grab a reference to the exit block in the pair so that we can update it. 593d869b188SChandler Carruth BasicBlock *ExitBB = CasePair.second; 5941353f9a4SChandler Carruth 5951353f9a4SChandler Carruth // If this case is the last edge into the exit block, we can simply reuse it 5961353f9a4SChandler Carruth // as it will no longer be a loop exit. No mapping necessary. 597d869b188SChandler Carruth if (pred_empty(ExitBB)) { 598d869b188SChandler Carruth // Only rewrite once. 599d869b188SChandler Carruth if (UnswitchedExitBBs.insert(ExitBB).second) 600d869b188SChandler Carruth rewritePHINodesForUnswitchedExitBlock(*ExitBB, *ParentBB, *OldPH); 6011353f9a4SChandler Carruth continue; 602d869b188SChandler Carruth } 6031353f9a4SChandler Carruth 6041353f9a4SChandler Carruth // Otherwise we need to split the exit block so that we retain an exit 6051353f9a4SChandler Carruth // block from the loop and a target for the unswitched condition. 6061353f9a4SChandler Carruth BasicBlock *&SplitExitBB = SplitExitBBMap[ExitBB]; 6071353f9a4SChandler Carruth if (!SplitExitBB) { 6081353f9a4SChandler Carruth // If this is the first time we see this, do the split and remember it. 6091353f9a4SChandler Carruth SplitExitBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI); 610d869b188SChandler Carruth rewritePHINodesForExitAndUnswitchedBlocks(*ExitBB, *SplitExitBB, 611d869b188SChandler Carruth *ParentBB, *OldPH); 612693eedb1SChandler Carruth updateIDomWithKnownCommonDominator(ExitBB, L.getHeader(), DT); 6131353f9a4SChandler Carruth } 614d869b188SChandler Carruth // Update the case pair to point to the split block. 615d869b188SChandler Carruth CasePair.second = SplitExitBB; 6161353f9a4SChandler Carruth } 6171353f9a4SChandler Carruth 6181353f9a4SChandler Carruth // Now add the unswitched cases. We do this in reverse order as we built them 6191353f9a4SChandler Carruth // in reverse order. 6201353f9a4SChandler Carruth for (auto CasePair : reverse(ExitCases)) { 6211353f9a4SChandler Carruth ConstantInt *CaseVal = CasePair.first; 6221353f9a4SChandler Carruth BasicBlock *UnswitchedBB = CasePair.second; 6231353f9a4SChandler Carruth 6241353f9a4SChandler Carruth NewSI->addCase(CaseVal, UnswitchedBB); 6251353f9a4SChandler Carruth updateDTAfterUnswitch(UnswitchedBB, OldPH, DT); 6261353f9a4SChandler Carruth } 6271353f9a4SChandler Carruth 6281353f9a4SChandler Carruth // If the default was unswitched, re-point it and add explicit cases for 6291353f9a4SChandler Carruth // entering the loop. 6301353f9a4SChandler Carruth if (DefaultExitBB) { 6311353f9a4SChandler Carruth NewSI->setDefaultDest(DefaultExitBB); 6321353f9a4SChandler Carruth updateDTAfterUnswitch(DefaultExitBB, OldPH, DT); 6331353f9a4SChandler Carruth 6341353f9a4SChandler Carruth // We removed all the exit cases, so we just copy the cases to the 6351353f9a4SChandler Carruth // unswitched switch. 6361353f9a4SChandler Carruth for (auto Case : SI.cases()) 6371353f9a4SChandler Carruth NewSI->addCase(Case.getCaseValue(), NewPH); 6381353f9a4SChandler Carruth } 6391353f9a4SChandler Carruth 6401353f9a4SChandler Carruth // If we ended up with a common successor for every path through the switch 6411353f9a4SChandler Carruth // after unswitching, rewrite it to an unconditional branch to make it easy 6421353f9a4SChandler Carruth // to recognize. Otherwise we potentially have to recognize the default case 6431353f9a4SChandler Carruth // pointing at unreachable and other complexity. 6441353f9a4SChandler Carruth if (CommonSuccBB) { 6451353f9a4SChandler Carruth BasicBlock *BB = SI.getParent(); 6461353f9a4SChandler Carruth SI.eraseFromParent(); 6471353f9a4SChandler Carruth BranchInst::Create(CommonSuccBB, BB); 6481353f9a4SChandler Carruth } 6491353f9a4SChandler Carruth 6501353f9a4SChandler Carruth DT.verifyDomTree(); 6511353f9a4SChandler Carruth ++NumTrivial; 6521353f9a4SChandler Carruth ++NumSwitches; 6531353f9a4SChandler Carruth return true; 6541353f9a4SChandler Carruth } 6551353f9a4SChandler Carruth 6561353f9a4SChandler Carruth /// This routine scans the loop to find a branch or switch which occurs before 6571353f9a4SChandler Carruth /// any side effects occur. These can potentially be unswitched without 6581353f9a4SChandler Carruth /// duplicating the loop. If a branch or switch is successfully unswitched the 6591353f9a4SChandler Carruth /// scanning continues to see if subsequent branches or switches have become 6601353f9a4SChandler Carruth /// trivial. Once all trivial candidates have been unswitched, this routine 6611353f9a4SChandler Carruth /// returns. 6621353f9a4SChandler Carruth /// 6631353f9a4SChandler Carruth /// The return value indicates whether anything was unswitched (and therefore 6641353f9a4SChandler Carruth /// changed). 6651353f9a4SChandler Carruth static bool unswitchAllTrivialConditions(Loop &L, DominatorTree &DT, 6661353f9a4SChandler Carruth LoopInfo &LI) { 6671353f9a4SChandler Carruth bool Changed = false; 6681353f9a4SChandler Carruth 6691353f9a4SChandler Carruth // If loop header has only one reachable successor we should keep looking for 6701353f9a4SChandler Carruth // trivial condition candidates in the successor as well. An alternative is 6711353f9a4SChandler Carruth // to constant fold conditions and merge successors into loop header (then we 6721353f9a4SChandler Carruth // only need to check header's terminator). The reason for not doing this in 6731353f9a4SChandler Carruth // LoopUnswitch pass is that it could potentially break LoopPassManager's 6741353f9a4SChandler Carruth // invariants. Folding dead branches could either eliminate the current loop 6751353f9a4SChandler Carruth // or make other loops unreachable. LCSSA form might also not be preserved 6761353f9a4SChandler Carruth // after deleting branches. The following code keeps traversing loop header's 6771353f9a4SChandler Carruth // successors until it finds the trivial condition candidate (condition that 6781353f9a4SChandler Carruth // is not a constant). Since unswitching generates branches with constant 6791353f9a4SChandler Carruth // conditions, this scenario could be very common in practice. 6801353f9a4SChandler Carruth BasicBlock *CurrentBB = L.getHeader(); 6811353f9a4SChandler Carruth SmallPtrSet<BasicBlock *, 8> Visited; 6821353f9a4SChandler Carruth Visited.insert(CurrentBB); 6831353f9a4SChandler Carruth do { 6841353f9a4SChandler Carruth // Check if there are any side-effecting instructions (e.g. stores, calls, 6851353f9a4SChandler Carruth // volatile loads) in the part of the loop that the code *would* execute 6861353f9a4SChandler Carruth // without unswitching. 6871353f9a4SChandler Carruth if (llvm::any_of(*CurrentBB, 6881353f9a4SChandler Carruth [](Instruction &I) { return I.mayHaveSideEffects(); })) 6891353f9a4SChandler Carruth return Changed; 6901353f9a4SChandler Carruth 6911353f9a4SChandler Carruth TerminatorInst *CurrentTerm = CurrentBB->getTerminator(); 6921353f9a4SChandler Carruth 6931353f9a4SChandler Carruth if (auto *SI = dyn_cast<SwitchInst>(CurrentTerm)) { 6941353f9a4SChandler Carruth // Don't bother trying to unswitch past a switch with a constant 6951353f9a4SChandler Carruth // condition. This should be removed prior to running this pass by 6961353f9a4SChandler Carruth // simplify-cfg. 6971353f9a4SChandler Carruth if (isa<Constant>(SI->getCondition())) 6981353f9a4SChandler Carruth return Changed; 6991353f9a4SChandler Carruth 7001353f9a4SChandler Carruth if (!unswitchTrivialSwitch(L, *SI, DT, LI)) 7011353f9a4SChandler Carruth // Coludn't unswitch this one so we're done. 7021353f9a4SChandler Carruth return Changed; 7031353f9a4SChandler Carruth 7041353f9a4SChandler Carruth // Mark that we managed to unswitch something. 7051353f9a4SChandler Carruth Changed = true; 7061353f9a4SChandler Carruth 7071353f9a4SChandler Carruth // If unswitching turned the terminator into an unconditional branch then 7081353f9a4SChandler Carruth // we can continue. The unswitching logic specifically works to fold any 7091353f9a4SChandler Carruth // cases it can into an unconditional branch to make it easier to 7101353f9a4SChandler Carruth // recognize here. 7111353f9a4SChandler Carruth auto *BI = dyn_cast<BranchInst>(CurrentBB->getTerminator()); 7121353f9a4SChandler Carruth if (!BI || BI->isConditional()) 7131353f9a4SChandler Carruth return Changed; 7141353f9a4SChandler Carruth 7151353f9a4SChandler Carruth CurrentBB = BI->getSuccessor(0); 7161353f9a4SChandler Carruth continue; 7171353f9a4SChandler Carruth } 7181353f9a4SChandler Carruth 7191353f9a4SChandler Carruth auto *BI = dyn_cast<BranchInst>(CurrentTerm); 7201353f9a4SChandler Carruth if (!BI) 7211353f9a4SChandler Carruth // We do not understand other terminator instructions. 7221353f9a4SChandler Carruth return Changed; 7231353f9a4SChandler Carruth 7241353f9a4SChandler Carruth // Don't bother trying to unswitch past an unconditional branch or a branch 7251353f9a4SChandler Carruth // with a constant value. These should be removed by simplify-cfg prior to 7261353f9a4SChandler Carruth // running this pass. 7271353f9a4SChandler Carruth if (!BI->isConditional() || isa<Constant>(BI->getCondition())) 7281353f9a4SChandler Carruth return Changed; 7291353f9a4SChandler Carruth 7301353f9a4SChandler Carruth // Found a trivial condition candidate: non-foldable conditional branch. If 7311353f9a4SChandler Carruth // we fail to unswitch this, we can't do anything else that is trivial. 7321353f9a4SChandler Carruth if (!unswitchTrivialBranch(L, *BI, DT, LI)) 7331353f9a4SChandler Carruth return Changed; 7341353f9a4SChandler Carruth 7351353f9a4SChandler Carruth // Mark that we managed to unswitch something. 7361353f9a4SChandler Carruth Changed = true; 7371353f9a4SChandler Carruth 7381353f9a4SChandler Carruth // We unswitched the branch. This should always leave us with an 7391353f9a4SChandler Carruth // unconditional branch that we can follow now. 7401353f9a4SChandler Carruth BI = cast<BranchInst>(CurrentBB->getTerminator()); 7411353f9a4SChandler Carruth assert(!BI->isConditional() && 7421353f9a4SChandler Carruth "Cannot form a conditional branch by unswitching1"); 7431353f9a4SChandler Carruth CurrentBB = BI->getSuccessor(0); 7441353f9a4SChandler Carruth 7451353f9a4SChandler Carruth // When continuing, if we exit the loop or reach a previous visited block, 7461353f9a4SChandler Carruth // then we can not reach any trivial condition candidates (unfoldable 7471353f9a4SChandler Carruth // branch instructions or switch instructions) and no unswitch can happen. 7481353f9a4SChandler Carruth } while (L.contains(CurrentBB) && Visited.insert(CurrentBB).second); 7491353f9a4SChandler Carruth 7501353f9a4SChandler Carruth return Changed; 7511353f9a4SChandler Carruth } 7521353f9a4SChandler Carruth 753693eedb1SChandler Carruth /// Build the cloned blocks for an unswitched copy of the given loop. 754693eedb1SChandler Carruth /// 755693eedb1SChandler Carruth /// The cloned blocks are inserted before the loop preheader (`LoopPH`) and 756693eedb1SChandler Carruth /// after the split block (`SplitBB`) that will be used to select between the 757693eedb1SChandler Carruth /// cloned and original loop. 758693eedb1SChandler Carruth /// 759693eedb1SChandler Carruth /// This routine handles cloning all of the necessary loop blocks and exit 760693eedb1SChandler Carruth /// blocks including rewriting their instructions and the relevant PHI nodes. 761693eedb1SChandler Carruth /// It skips loop and exit blocks that are not necessary based on the provided 762693eedb1SChandler Carruth /// set. It also correctly creates the unconditional branch in the cloned 763693eedb1SChandler Carruth /// unswitched parent block to only point at the unswitched successor. 764693eedb1SChandler Carruth /// 765693eedb1SChandler Carruth /// This does not handle most of the necessary updates to `LoopInfo`. Only exit 766693eedb1SChandler Carruth /// block splitting is correctly reflected in `LoopInfo`, essentially all of 767693eedb1SChandler Carruth /// the cloned blocks (and their loops) are left without full `LoopInfo` 768693eedb1SChandler Carruth /// updates. This also doesn't fully update `DominatorTree`. It adds the cloned 769693eedb1SChandler Carruth /// blocks to them but doesn't create the cloned `DominatorTree` structure and 770693eedb1SChandler Carruth /// instead the caller must recompute an accurate DT. It *does* correctly 771693eedb1SChandler Carruth /// update the `AssumptionCache` provided in `AC`. 772693eedb1SChandler Carruth static BasicBlock *buildClonedLoopBlocks( 773693eedb1SChandler Carruth Loop &L, BasicBlock *LoopPH, BasicBlock *SplitBB, 774693eedb1SChandler Carruth ArrayRef<BasicBlock *> ExitBlocks, BasicBlock *ParentBB, 775693eedb1SChandler Carruth BasicBlock *UnswitchedSuccBB, BasicBlock *ContinueSuccBB, 776693eedb1SChandler Carruth const SmallPtrSetImpl<BasicBlock *> &SkippedLoopAndExitBlocks, 777693eedb1SChandler Carruth ValueToValueMapTy &VMap, AssumptionCache &AC, DominatorTree &DT, 778693eedb1SChandler Carruth LoopInfo &LI) { 779693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> NewBlocks; 780693eedb1SChandler Carruth NewBlocks.reserve(L.getNumBlocks() + ExitBlocks.size()); 781693eedb1SChandler Carruth 782693eedb1SChandler Carruth // We will need to clone a bunch of blocks, wrap up the clone operation in 783693eedb1SChandler Carruth // a helper. 784693eedb1SChandler Carruth auto CloneBlock = [&](BasicBlock *OldBB) { 785693eedb1SChandler Carruth // Clone the basic block and insert it before the new preheader. 786693eedb1SChandler Carruth BasicBlock *NewBB = CloneBasicBlock(OldBB, VMap, ".us", OldBB->getParent()); 787693eedb1SChandler Carruth NewBB->moveBefore(LoopPH); 788693eedb1SChandler Carruth 789693eedb1SChandler Carruth // Record this block and the mapping. 790693eedb1SChandler Carruth NewBlocks.push_back(NewBB); 791693eedb1SChandler Carruth VMap[OldBB] = NewBB; 792693eedb1SChandler Carruth 793693eedb1SChandler Carruth // Add the block to the domtree. We'll move it to the correct position 794693eedb1SChandler Carruth // below. 795693eedb1SChandler Carruth DT.addNewBlock(NewBB, SplitBB); 796693eedb1SChandler Carruth 797693eedb1SChandler Carruth return NewBB; 798693eedb1SChandler Carruth }; 799693eedb1SChandler Carruth 800693eedb1SChandler Carruth // First, clone the preheader. 801693eedb1SChandler Carruth auto *ClonedPH = CloneBlock(LoopPH); 802693eedb1SChandler Carruth 803693eedb1SChandler Carruth // Then clone all the loop blocks, skipping the ones that aren't necessary. 804693eedb1SChandler Carruth for (auto *LoopBB : L.blocks()) 805693eedb1SChandler Carruth if (!SkippedLoopAndExitBlocks.count(LoopBB)) 806693eedb1SChandler Carruth CloneBlock(LoopBB); 807693eedb1SChandler Carruth 808693eedb1SChandler Carruth // Split all the loop exit edges so that when we clone the exit blocks, if 809693eedb1SChandler Carruth // any of the exit blocks are *also* a preheader for some other loop, we 810693eedb1SChandler Carruth // don't create multiple predecessors entering the loop header. 811693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) { 812693eedb1SChandler Carruth if (SkippedLoopAndExitBlocks.count(ExitBB)) 813693eedb1SChandler Carruth continue; 814693eedb1SChandler Carruth 815693eedb1SChandler Carruth // When we are going to clone an exit, we don't need to clone all the 816693eedb1SChandler Carruth // instructions in the exit block and we want to ensure we have an easy 817693eedb1SChandler Carruth // place to merge the CFG, so split the exit first. This is always safe to 818693eedb1SChandler Carruth // do because there cannot be any non-loop predecessors of a loop exit in 819693eedb1SChandler Carruth // loop simplified form. 820693eedb1SChandler Carruth auto *MergeBB = SplitBlock(ExitBB, &ExitBB->front(), &DT, &LI); 821693eedb1SChandler Carruth 822693eedb1SChandler Carruth // Rearrange the names to make it easier to write test cases by having the 823693eedb1SChandler Carruth // exit block carry the suffix rather than the merge block carrying the 824693eedb1SChandler Carruth // suffix. 825693eedb1SChandler Carruth MergeBB->takeName(ExitBB); 826693eedb1SChandler Carruth ExitBB->setName(Twine(MergeBB->getName()) + ".split"); 827693eedb1SChandler Carruth 828693eedb1SChandler Carruth // Now clone the original exit block. 829693eedb1SChandler Carruth auto *ClonedExitBB = CloneBlock(ExitBB); 830693eedb1SChandler Carruth assert(ClonedExitBB->getTerminator()->getNumSuccessors() == 1 && 831693eedb1SChandler Carruth "Exit block should have been split to have one successor!"); 832693eedb1SChandler Carruth assert(ClonedExitBB->getTerminator()->getSuccessor(0) == MergeBB && 833693eedb1SChandler Carruth "Cloned exit block has the wrong successor!"); 834693eedb1SChandler Carruth 835693eedb1SChandler Carruth // Move the merge block's idom to be the split point as one exit is 836693eedb1SChandler Carruth // dominated by one header, and the other by another, so we know the split 837693eedb1SChandler Carruth // point dominates both. While the dominator tree isn't fully accurate, we 838693eedb1SChandler Carruth // want sub-trees within the original loop to be correctly reflect 839693eedb1SChandler Carruth // dominance within that original loop (at least) and that requires moving 840693eedb1SChandler Carruth // the merge block out of that subtree. 841693eedb1SChandler Carruth // FIXME: This is very brittle as we essentially have a partial contract on 842693eedb1SChandler Carruth // the dominator tree. We really need to instead update it and keep it 843693eedb1SChandler Carruth // valid or stop relying on it. 844693eedb1SChandler Carruth DT.changeImmediateDominator(MergeBB, SplitBB); 845693eedb1SChandler Carruth 846693eedb1SChandler Carruth // Remap any cloned instructions and create a merge phi node for them. 847693eedb1SChandler Carruth for (auto ZippedInsts : llvm::zip_first( 848693eedb1SChandler Carruth llvm::make_range(ExitBB->begin(), std::prev(ExitBB->end())), 849693eedb1SChandler Carruth llvm::make_range(ClonedExitBB->begin(), 850693eedb1SChandler Carruth std::prev(ClonedExitBB->end())))) { 851693eedb1SChandler Carruth Instruction &I = std::get<0>(ZippedInsts); 852693eedb1SChandler Carruth Instruction &ClonedI = std::get<1>(ZippedInsts); 853693eedb1SChandler Carruth 854693eedb1SChandler Carruth // The only instructions in the exit block should be PHI nodes and 855693eedb1SChandler Carruth // potentially a landing pad. 856693eedb1SChandler Carruth assert( 857693eedb1SChandler Carruth (isa<PHINode>(I) || isa<LandingPadInst>(I) || isa<CatchPadInst>(I)) && 858693eedb1SChandler Carruth "Bad instruction in exit block!"); 859693eedb1SChandler Carruth // We should have a value map between the instruction and its clone. 860693eedb1SChandler Carruth assert(VMap.lookup(&I) == &ClonedI && "Mismatch in the value map!"); 861693eedb1SChandler Carruth 862693eedb1SChandler Carruth auto *MergePN = 863693eedb1SChandler Carruth PHINode::Create(I.getType(), /*NumReservedValues*/ 2, ".us-phi", 864693eedb1SChandler Carruth &*MergeBB->getFirstInsertionPt()); 865693eedb1SChandler Carruth I.replaceAllUsesWith(MergePN); 866693eedb1SChandler Carruth MergePN->addIncoming(&I, ExitBB); 867693eedb1SChandler Carruth MergePN->addIncoming(&ClonedI, ClonedExitBB); 868693eedb1SChandler Carruth } 869693eedb1SChandler Carruth } 870693eedb1SChandler Carruth 871693eedb1SChandler Carruth // Rewrite the instructions in the cloned blocks to refer to the instructions 872693eedb1SChandler Carruth // in the cloned blocks. We have to do this as a second pass so that we have 873693eedb1SChandler Carruth // everything available. Also, we have inserted new instructions which may 874693eedb1SChandler Carruth // include assume intrinsics, so we update the assumption cache while 875693eedb1SChandler Carruth // processing this. 876693eedb1SChandler Carruth for (auto *ClonedBB : NewBlocks) 877693eedb1SChandler Carruth for (Instruction &I : *ClonedBB) { 878693eedb1SChandler Carruth RemapInstruction(&I, VMap, 879693eedb1SChandler Carruth RF_NoModuleLevelChanges | RF_IgnoreMissingLocals); 880693eedb1SChandler Carruth if (auto *II = dyn_cast<IntrinsicInst>(&I)) 881693eedb1SChandler Carruth if (II->getIntrinsicID() == Intrinsic::assume) 882693eedb1SChandler Carruth AC.registerAssumption(II); 883693eedb1SChandler Carruth } 884693eedb1SChandler Carruth 885693eedb1SChandler Carruth // Remove the cloned parent as a predecessor of the cloned continue successor 886693eedb1SChandler Carruth // if we did in fact clone it. 887693eedb1SChandler Carruth auto *ClonedParentBB = cast<BasicBlock>(VMap.lookup(ParentBB)); 888693eedb1SChandler Carruth if (auto *ClonedContinueSuccBB = 889693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ContinueSuccBB))) 890693eedb1SChandler Carruth ClonedContinueSuccBB->removePredecessor(ClonedParentBB, 891693eedb1SChandler Carruth /*DontDeleteUselessPHIs*/ true); 892693eedb1SChandler Carruth // Replace the cloned branch with an unconditional branch to the cloneed 893693eedb1SChandler Carruth // unswitched successor. 894693eedb1SChandler Carruth auto *ClonedSuccBB = cast<BasicBlock>(VMap.lookup(UnswitchedSuccBB)); 895693eedb1SChandler Carruth ClonedParentBB->getTerminator()->eraseFromParent(); 896693eedb1SChandler Carruth BranchInst::Create(ClonedSuccBB, ClonedParentBB); 897693eedb1SChandler Carruth 898693eedb1SChandler Carruth // Update any PHI nodes in the cloned successors of the skipped blocks to not 899693eedb1SChandler Carruth // have spurious incoming values. 900693eedb1SChandler Carruth for (auto *LoopBB : L.blocks()) 901693eedb1SChandler Carruth if (SkippedLoopAndExitBlocks.count(LoopBB)) 902693eedb1SChandler Carruth for (auto *SuccBB : successors(LoopBB)) 903693eedb1SChandler Carruth if (auto *ClonedSuccBB = cast_or_null<BasicBlock>(VMap.lookup(SuccBB))) 904693eedb1SChandler Carruth for (PHINode &PN : ClonedSuccBB->phis()) 905693eedb1SChandler Carruth PN.removeIncomingValue(LoopBB, /*DeletePHIIfEmpty*/ false); 906693eedb1SChandler Carruth 907693eedb1SChandler Carruth return ClonedPH; 908693eedb1SChandler Carruth } 909693eedb1SChandler Carruth 910693eedb1SChandler Carruth /// Recursively clone the specified loop and all of its children. 911693eedb1SChandler Carruth /// 912693eedb1SChandler Carruth /// The target parent loop for the clone should be provided, or can be null if 913693eedb1SChandler Carruth /// the clone is a top-level loop. While cloning, all the blocks are mapped 914693eedb1SChandler Carruth /// with the provided value map. The entire original loop must be present in 915693eedb1SChandler Carruth /// the value map. The cloned loop is returned. 916693eedb1SChandler Carruth static Loop *cloneLoopNest(Loop &OrigRootL, Loop *RootParentL, 917693eedb1SChandler Carruth const ValueToValueMapTy &VMap, LoopInfo &LI) { 918693eedb1SChandler Carruth auto AddClonedBlocksToLoop = [&](Loop &OrigL, Loop &ClonedL) { 919693eedb1SChandler Carruth assert(ClonedL.getBlocks().empty() && "Must start with an empty loop!"); 920693eedb1SChandler Carruth ClonedL.reserveBlocks(OrigL.getNumBlocks()); 921693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) { 922693eedb1SChandler Carruth auto *ClonedBB = cast<BasicBlock>(VMap.lookup(BB)); 923693eedb1SChandler Carruth ClonedL.addBlockEntry(ClonedBB); 924693eedb1SChandler Carruth if (LI.getLoopFor(BB) == &OrigL) { 925693eedb1SChandler Carruth assert(!LI.getLoopFor(ClonedBB) && 926693eedb1SChandler Carruth "Should not have an existing loop for this block!"); 927693eedb1SChandler Carruth LI.changeLoopFor(ClonedBB, &ClonedL); 928693eedb1SChandler Carruth } 929693eedb1SChandler Carruth } 930693eedb1SChandler Carruth }; 931693eedb1SChandler Carruth 932693eedb1SChandler Carruth // We specially handle the first loop because it may get cloned into 933693eedb1SChandler Carruth // a different parent and because we most commonly are cloning leaf loops. 934693eedb1SChandler Carruth Loop *ClonedRootL = LI.AllocateLoop(); 935693eedb1SChandler Carruth if (RootParentL) 936693eedb1SChandler Carruth RootParentL->addChildLoop(ClonedRootL); 937693eedb1SChandler Carruth else 938693eedb1SChandler Carruth LI.addTopLevelLoop(ClonedRootL); 939693eedb1SChandler Carruth AddClonedBlocksToLoop(OrigRootL, *ClonedRootL); 940693eedb1SChandler Carruth 941693eedb1SChandler Carruth if (OrigRootL.empty()) 942693eedb1SChandler Carruth return ClonedRootL; 943693eedb1SChandler Carruth 944693eedb1SChandler Carruth // If we have a nest, we can quickly clone the entire loop nest using an 945693eedb1SChandler Carruth // iterative approach because it is a tree. We keep the cloned parent in the 946693eedb1SChandler Carruth // data structure to avoid repeatedly querying through a map to find it. 947693eedb1SChandler Carruth SmallVector<std::pair<Loop *, Loop *>, 16> LoopsToClone; 948693eedb1SChandler Carruth // Build up the loops to clone in reverse order as we'll clone them from the 949693eedb1SChandler Carruth // back. 950693eedb1SChandler Carruth for (Loop *ChildL : llvm::reverse(OrigRootL)) 951693eedb1SChandler Carruth LoopsToClone.push_back({ClonedRootL, ChildL}); 952693eedb1SChandler Carruth do { 953693eedb1SChandler Carruth Loop *ClonedParentL, *L; 954693eedb1SChandler Carruth std::tie(ClonedParentL, L) = LoopsToClone.pop_back_val(); 955693eedb1SChandler Carruth Loop *ClonedL = LI.AllocateLoop(); 956693eedb1SChandler Carruth ClonedParentL->addChildLoop(ClonedL); 957693eedb1SChandler Carruth AddClonedBlocksToLoop(*L, *ClonedL); 958693eedb1SChandler Carruth for (Loop *ChildL : llvm::reverse(*L)) 959693eedb1SChandler Carruth LoopsToClone.push_back({ClonedL, ChildL}); 960693eedb1SChandler Carruth } while (!LoopsToClone.empty()); 961693eedb1SChandler Carruth 962693eedb1SChandler Carruth return ClonedRootL; 963693eedb1SChandler Carruth } 964693eedb1SChandler Carruth 965693eedb1SChandler Carruth /// Build the cloned loops of an original loop from unswitching. 966693eedb1SChandler Carruth /// 967693eedb1SChandler Carruth /// Because unswitching simplifies the CFG of the loop, this isn't a trivial 968693eedb1SChandler Carruth /// operation. We need to re-verify that there even is a loop (as the backedge 969693eedb1SChandler Carruth /// may not have been cloned), and even if there are remaining backedges the 970693eedb1SChandler Carruth /// backedge set may be different. However, we know that each child loop is 971693eedb1SChandler Carruth /// undisturbed, we only need to find where to place each child loop within 972693eedb1SChandler Carruth /// either any parent loop or within a cloned version of the original loop. 973693eedb1SChandler Carruth /// 974693eedb1SChandler Carruth /// Because child loops may end up cloned outside of any cloned version of the 975693eedb1SChandler Carruth /// original loop, multiple cloned sibling loops may be created. All of them 976693eedb1SChandler Carruth /// are returned so that the newly introduced loop nest roots can be 977693eedb1SChandler Carruth /// identified. 978693eedb1SChandler Carruth static Loop *buildClonedLoops(Loop &OrigL, ArrayRef<BasicBlock *> ExitBlocks, 979693eedb1SChandler Carruth const ValueToValueMapTy &VMap, LoopInfo &LI, 980693eedb1SChandler Carruth SmallVectorImpl<Loop *> &NonChildClonedLoops) { 981693eedb1SChandler Carruth Loop *ClonedL = nullptr; 982693eedb1SChandler Carruth 983693eedb1SChandler Carruth auto *OrigPH = OrigL.getLoopPreheader(); 984693eedb1SChandler Carruth auto *OrigHeader = OrigL.getHeader(); 985693eedb1SChandler Carruth 986693eedb1SChandler Carruth auto *ClonedPH = cast<BasicBlock>(VMap.lookup(OrigPH)); 987693eedb1SChandler Carruth auto *ClonedHeader = cast<BasicBlock>(VMap.lookup(OrigHeader)); 988693eedb1SChandler Carruth 989693eedb1SChandler Carruth // We need to know the loops of the cloned exit blocks to even compute the 990693eedb1SChandler Carruth // accurate parent loop. If we only clone exits to some parent of the 991693eedb1SChandler Carruth // original parent, we want to clone into that outer loop. We also keep track 992693eedb1SChandler Carruth // of the loops that our cloned exit blocks participate in. 993693eedb1SChandler Carruth Loop *ParentL = nullptr; 994693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ClonedExitsInLoops; 995693eedb1SChandler Carruth SmallDenseMap<BasicBlock *, Loop *, 16> ExitLoopMap; 996693eedb1SChandler Carruth ClonedExitsInLoops.reserve(ExitBlocks.size()); 997693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) 998693eedb1SChandler Carruth if (auto *ClonedExitBB = cast_or_null<BasicBlock>(VMap.lookup(ExitBB))) 999693eedb1SChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1000693eedb1SChandler Carruth ExitLoopMap[ClonedExitBB] = ExitL; 1001693eedb1SChandler Carruth ClonedExitsInLoops.push_back(ClonedExitBB); 1002693eedb1SChandler Carruth if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1003693eedb1SChandler Carruth ParentL = ExitL; 1004693eedb1SChandler Carruth } 1005693eedb1SChandler Carruth assert((!ParentL || ParentL == OrigL.getParentLoop() || 1006693eedb1SChandler Carruth ParentL->contains(OrigL.getParentLoop())) && 1007693eedb1SChandler Carruth "The computed parent loop should always contain (or be) the parent of " 1008693eedb1SChandler Carruth "the original loop."); 1009693eedb1SChandler Carruth 1010693eedb1SChandler Carruth // We build the set of blocks dominated by the cloned header from the set of 1011693eedb1SChandler Carruth // cloned blocks out of the original loop. While not all of these will 1012693eedb1SChandler Carruth // necessarily be in the cloned loop, it is enough to establish that they 1013693eedb1SChandler Carruth // aren't in unreachable cycles, etc. 1014693eedb1SChandler Carruth SmallSetVector<BasicBlock *, 16> ClonedLoopBlocks; 1015693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) 1016693eedb1SChandler Carruth if (auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB))) 1017693eedb1SChandler Carruth ClonedLoopBlocks.insert(ClonedBB); 1018693eedb1SChandler Carruth 1019693eedb1SChandler Carruth // Rebuild the set of blocks that will end up in the cloned loop. We may have 1020693eedb1SChandler Carruth // skipped cloning some region of this loop which can in turn skip some of 1021693eedb1SChandler Carruth // the backedges so we have to rebuild the blocks in the loop based on the 1022693eedb1SChandler Carruth // backedges that remain after cloning. 1023693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist; 1024693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> BlocksInClonedLoop; 1025693eedb1SChandler Carruth for (auto *Pred : predecessors(ClonedHeader)) { 1026693eedb1SChandler Carruth // The only possible non-loop header predecessor is the preheader because 1027693eedb1SChandler Carruth // we know we cloned the loop in simplified form. 1028693eedb1SChandler Carruth if (Pred == ClonedPH) 1029693eedb1SChandler Carruth continue; 1030693eedb1SChandler Carruth 1031693eedb1SChandler Carruth // Because the loop was in simplified form, the only non-loop predecessor 1032693eedb1SChandler Carruth // should be the preheader. 1033693eedb1SChandler Carruth assert(ClonedLoopBlocks.count(Pred) && "Found a predecessor of the loop " 1034693eedb1SChandler Carruth "header other than the preheader " 1035693eedb1SChandler Carruth "that is not part of the loop!"); 1036693eedb1SChandler Carruth 1037693eedb1SChandler Carruth // Insert this block into the loop set and on the first visit (and if it 1038693eedb1SChandler Carruth // isn't the header we're currently walking) put it into the worklist to 1039693eedb1SChandler Carruth // recurse through. 1040693eedb1SChandler Carruth if (BlocksInClonedLoop.insert(Pred).second && Pred != ClonedHeader) 1041693eedb1SChandler Carruth Worklist.push_back(Pred); 1042693eedb1SChandler Carruth } 1043693eedb1SChandler Carruth 1044693eedb1SChandler Carruth // If we had any backedges then there *is* a cloned loop. Put the header into 1045693eedb1SChandler Carruth // the loop set and then walk the worklist backwards to find all the blocks 1046693eedb1SChandler Carruth // that remain within the loop after cloning. 1047693eedb1SChandler Carruth if (!BlocksInClonedLoop.empty()) { 1048693eedb1SChandler Carruth BlocksInClonedLoop.insert(ClonedHeader); 1049693eedb1SChandler Carruth 1050693eedb1SChandler Carruth while (!Worklist.empty()) { 1051693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 1052693eedb1SChandler Carruth assert(BlocksInClonedLoop.count(BB) && 1053693eedb1SChandler Carruth "Didn't put block into the loop set!"); 1054693eedb1SChandler Carruth 1055693eedb1SChandler Carruth // Insert any predecessors that are in the possible set into the cloned 1056693eedb1SChandler Carruth // set, and if the insert is successful, add them to the worklist. Note 1057693eedb1SChandler Carruth // that we filter on the blocks that are definitely reachable via the 1058693eedb1SChandler Carruth // backedge to the loop header so we may prune out dead code within the 1059693eedb1SChandler Carruth // cloned loop. 1060693eedb1SChandler Carruth for (auto *Pred : predecessors(BB)) 1061693eedb1SChandler Carruth if (ClonedLoopBlocks.count(Pred) && 1062693eedb1SChandler Carruth BlocksInClonedLoop.insert(Pred).second) 1063693eedb1SChandler Carruth Worklist.push_back(Pred); 1064693eedb1SChandler Carruth } 1065693eedb1SChandler Carruth 1066693eedb1SChandler Carruth ClonedL = LI.AllocateLoop(); 1067693eedb1SChandler Carruth if (ParentL) { 1068693eedb1SChandler Carruth ParentL->addBasicBlockToLoop(ClonedPH, LI); 1069693eedb1SChandler Carruth ParentL->addChildLoop(ClonedL); 1070693eedb1SChandler Carruth } else { 1071693eedb1SChandler Carruth LI.addTopLevelLoop(ClonedL); 1072693eedb1SChandler Carruth } 1073693eedb1SChandler Carruth 1074693eedb1SChandler Carruth ClonedL->reserveBlocks(BlocksInClonedLoop.size()); 1075693eedb1SChandler Carruth // We don't want to just add the cloned loop blocks based on how we 1076693eedb1SChandler Carruth // discovered them. The original order of blocks was carefully built in 1077693eedb1SChandler Carruth // a way that doesn't rely on predecessor ordering. Rather than re-invent 1078693eedb1SChandler Carruth // that logic, we just re-walk the original blocks (and those of the child 1079693eedb1SChandler Carruth // loops) and filter them as we add them into the cloned loop. 1080693eedb1SChandler Carruth for (auto *BB : OrigL.blocks()) { 1081693eedb1SChandler Carruth auto *ClonedBB = cast_or_null<BasicBlock>(VMap.lookup(BB)); 1082693eedb1SChandler Carruth if (!ClonedBB || !BlocksInClonedLoop.count(ClonedBB)) 1083693eedb1SChandler Carruth continue; 1084693eedb1SChandler Carruth 1085693eedb1SChandler Carruth // Directly add the blocks that are only in this loop. 1086693eedb1SChandler Carruth if (LI.getLoopFor(BB) == &OrigL) { 1087693eedb1SChandler Carruth ClonedL->addBasicBlockToLoop(ClonedBB, LI); 1088693eedb1SChandler Carruth continue; 1089693eedb1SChandler Carruth } 1090693eedb1SChandler Carruth 1091693eedb1SChandler Carruth // We want to manually add it to this loop and parents. 1092693eedb1SChandler Carruth // Registering it with LoopInfo will happen when we clone the top 1093693eedb1SChandler Carruth // loop for this block. 1094693eedb1SChandler Carruth for (Loop *PL = ClonedL; PL; PL = PL->getParentLoop()) 1095693eedb1SChandler Carruth PL->addBlockEntry(ClonedBB); 1096693eedb1SChandler Carruth } 1097693eedb1SChandler Carruth 1098693eedb1SChandler Carruth // Now add each child loop whose header remains within the cloned loop. All 1099693eedb1SChandler Carruth // of the blocks within the loop must satisfy the same constraints as the 1100693eedb1SChandler Carruth // header so once we pass the header checks we can just clone the entire 1101693eedb1SChandler Carruth // child loop nest. 1102693eedb1SChandler Carruth for (Loop *ChildL : OrigL) { 1103693eedb1SChandler Carruth auto *ClonedChildHeader = 1104693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1105693eedb1SChandler Carruth if (!ClonedChildHeader || !BlocksInClonedLoop.count(ClonedChildHeader)) 1106693eedb1SChandler Carruth continue; 1107693eedb1SChandler Carruth 1108693eedb1SChandler Carruth #ifndef NDEBUG 1109693eedb1SChandler Carruth // We should never have a cloned child loop header but fail to have 1110693eedb1SChandler Carruth // all of the blocks for that child loop. 1111693eedb1SChandler Carruth for (auto *ChildLoopBB : ChildL->blocks()) 1112693eedb1SChandler Carruth assert(BlocksInClonedLoop.count( 1113693eedb1SChandler Carruth cast<BasicBlock>(VMap.lookup(ChildLoopBB))) && 1114693eedb1SChandler Carruth "Child cloned loop has a header within the cloned outer " 1115693eedb1SChandler Carruth "loop but not all of its blocks!"); 1116693eedb1SChandler Carruth #endif 1117693eedb1SChandler Carruth 1118693eedb1SChandler Carruth cloneLoopNest(*ChildL, ClonedL, VMap, LI); 1119693eedb1SChandler Carruth } 1120693eedb1SChandler Carruth } 1121693eedb1SChandler Carruth 1122693eedb1SChandler Carruth // Now that we've handled all the components of the original loop that were 1123693eedb1SChandler Carruth // cloned into a new loop, we still need to handle anything from the original 1124693eedb1SChandler Carruth // loop that wasn't in a cloned loop. 1125693eedb1SChandler Carruth 1126693eedb1SChandler Carruth // Figure out what blocks are left to place within any loop nest containing 1127693eedb1SChandler Carruth // the unswitched loop. If we never formed a loop, the cloned PH is one of 1128693eedb1SChandler Carruth // them. 1129693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> UnloopedBlockSet; 1130693eedb1SChandler Carruth if (BlocksInClonedLoop.empty()) 1131693eedb1SChandler Carruth UnloopedBlockSet.insert(ClonedPH); 1132693eedb1SChandler Carruth for (auto *ClonedBB : ClonedLoopBlocks) 1133693eedb1SChandler Carruth if (!BlocksInClonedLoop.count(ClonedBB)) 1134693eedb1SChandler Carruth UnloopedBlockSet.insert(ClonedBB); 1135693eedb1SChandler Carruth 1136693eedb1SChandler Carruth // Copy the cloned exits and sort them in ascending loop depth, we'll work 1137693eedb1SChandler Carruth // backwards across these to process them inside out. The order shouldn't 1138693eedb1SChandler Carruth // matter as we're just trying to build up the map from inside-out; we use 1139693eedb1SChandler Carruth // the map in a more stably ordered way below. 1140693eedb1SChandler Carruth auto OrderedClonedExitsInLoops = ClonedExitsInLoops; 1141693eedb1SChandler Carruth std::sort(OrderedClonedExitsInLoops.begin(), OrderedClonedExitsInLoops.end(), 1142693eedb1SChandler Carruth [&](BasicBlock *LHS, BasicBlock *RHS) { 1143693eedb1SChandler Carruth return ExitLoopMap.lookup(LHS)->getLoopDepth() < 1144693eedb1SChandler Carruth ExitLoopMap.lookup(RHS)->getLoopDepth(); 1145693eedb1SChandler Carruth }); 1146693eedb1SChandler Carruth 1147693eedb1SChandler Carruth // Populate the existing ExitLoopMap with everything reachable from each 1148693eedb1SChandler Carruth // exit, starting from the inner most exit. 1149693eedb1SChandler Carruth while (!UnloopedBlockSet.empty() && !OrderedClonedExitsInLoops.empty()) { 1150693eedb1SChandler Carruth assert(Worklist.empty() && "Didn't clear worklist!"); 1151693eedb1SChandler Carruth 1152693eedb1SChandler Carruth BasicBlock *ExitBB = OrderedClonedExitsInLoops.pop_back_val(); 1153693eedb1SChandler Carruth Loop *ExitL = ExitLoopMap.lookup(ExitBB); 1154693eedb1SChandler Carruth 1155693eedb1SChandler Carruth // Walk the CFG back until we hit the cloned PH adding everything reachable 1156693eedb1SChandler Carruth // and in the unlooped set to this exit block's loop. 1157693eedb1SChandler Carruth Worklist.push_back(ExitBB); 1158693eedb1SChandler Carruth do { 1159693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 1160693eedb1SChandler Carruth // We can stop recursing at the cloned preheader (if we get there). 1161693eedb1SChandler Carruth if (BB == ClonedPH) 1162693eedb1SChandler Carruth continue; 1163693eedb1SChandler Carruth 1164693eedb1SChandler Carruth for (BasicBlock *PredBB : predecessors(BB)) { 1165693eedb1SChandler Carruth // If this pred has already been moved to our set or is part of some 1166693eedb1SChandler Carruth // (inner) loop, no update needed. 1167693eedb1SChandler Carruth if (!UnloopedBlockSet.erase(PredBB)) { 1168693eedb1SChandler Carruth assert( 1169693eedb1SChandler Carruth (BlocksInClonedLoop.count(PredBB) || ExitLoopMap.count(PredBB)) && 1170693eedb1SChandler Carruth "Predecessor not mapped to a loop!"); 1171693eedb1SChandler Carruth continue; 1172693eedb1SChandler Carruth } 1173693eedb1SChandler Carruth 1174693eedb1SChandler Carruth // We just insert into the loop set here. We'll add these blocks to the 1175693eedb1SChandler Carruth // exit loop after we build up the set in an order that doesn't rely on 1176693eedb1SChandler Carruth // predecessor order (which in turn relies on use list order). 1177693eedb1SChandler Carruth bool Inserted = ExitLoopMap.insert({PredBB, ExitL}).second; 1178693eedb1SChandler Carruth (void)Inserted; 1179693eedb1SChandler Carruth assert(Inserted && "Should only visit an unlooped block once!"); 1180693eedb1SChandler Carruth 1181693eedb1SChandler Carruth // And recurse through to its predecessors. 1182693eedb1SChandler Carruth Worklist.push_back(PredBB); 1183693eedb1SChandler Carruth } 1184693eedb1SChandler Carruth } while (!Worklist.empty()); 1185693eedb1SChandler Carruth } 1186693eedb1SChandler Carruth 1187693eedb1SChandler Carruth // Now that the ExitLoopMap gives as mapping for all the non-looping cloned 1188693eedb1SChandler Carruth // blocks to their outer loops, walk the cloned blocks and the cloned exits 1189693eedb1SChandler Carruth // in their original order adding them to the correct loop. 1190693eedb1SChandler Carruth 1191693eedb1SChandler Carruth // We need a stable insertion order. We use the order of the original loop 1192693eedb1SChandler Carruth // order and map into the correct parent loop. 1193693eedb1SChandler Carruth for (auto *BB : llvm::concat<BasicBlock *const>( 1194693eedb1SChandler Carruth makeArrayRef(ClonedPH), ClonedLoopBlocks, ClonedExitsInLoops)) 1195693eedb1SChandler Carruth if (Loop *OuterL = ExitLoopMap.lookup(BB)) 1196693eedb1SChandler Carruth OuterL->addBasicBlockToLoop(BB, LI); 1197693eedb1SChandler Carruth 1198693eedb1SChandler Carruth #ifndef NDEBUG 1199693eedb1SChandler Carruth for (auto &BBAndL : ExitLoopMap) { 1200693eedb1SChandler Carruth auto *BB = BBAndL.first; 1201693eedb1SChandler Carruth auto *OuterL = BBAndL.second; 1202693eedb1SChandler Carruth assert(LI.getLoopFor(BB) == OuterL && 1203693eedb1SChandler Carruth "Failed to put all blocks into outer loops!"); 1204693eedb1SChandler Carruth } 1205693eedb1SChandler Carruth #endif 1206693eedb1SChandler Carruth 1207693eedb1SChandler Carruth // Now that all the blocks are placed into the correct containing loop in the 1208693eedb1SChandler Carruth // absence of child loops, find all the potentially cloned child loops and 1209693eedb1SChandler Carruth // clone them into whatever outer loop we placed their header into. 1210693eedb1SChandler Carruth for (Loop *ChildL : OrigL) { 1211693eedb1SChandler Carruth auto *ClonedChildHeader = 1212693eedb1SChandler Carruth cast_or_null<BasicBlock>(VMap.lookup(ChildL->getHeader())); 1213693eedb1SChandler Carruth if (!ClonedChildHeader || BlocksInClonedLoop.count(ClonedChildHeader)) 1214693eedb1SChandler Carruth continue; 1215693eedb1SChandler Carruth 1216693eedb1SChandler Carruth #ifndef NDEBUG 1217693eedb1SChandler Carruth for (auto *ChildLoopBB : ChildL->blocks()) 1218693eedb1SChandler Carruth assert(VMap.count(ChildLoopBB) && 1219693eedb1SChandler Carruth "Cloned a child loop header but not all of that loops blocks!"); 1220693eedb1SChandler Carruth #endif 1221693eedb1SChandler Carruth 1222693eedb1SChandler Carruth NonChildClonedLoops.push_back(cloneLoopNest( 1223693eedb1SChandler Carruth *ChildL, ExitLoopMap.lookup(ClonedChildHeader), VMap, LI)); 1224693eedb1SChandler Carruth } 1225693eedb1SChandler Carruth 1226693eedb1SChandler Carruth // Return the main cloned loop if any. 1227693eedb1SChandler Carruth return ClonedL; 1228693eedb1SChandler Carruth } 1229693eedb1SChandler Carruth 1230693eedb1SChandler Carruth static void deleteDeadBlocksFromLoop(Loop &L, BasicBlock *DeadSubtreeRoot, 1231693eedb1SChandler Carruth SmallVectorImpl<BasicBlock *> &ExitBlocks, 1232693eedb1SChandler Carruth DominatorTree &DT, LoopInfo &LI) { 1233693eedb1SChandler Carruth // Walk the dominator tree to build up the set of blocks we will delete here. 1234693eedb1SChandler Carruth // The order is designed to allow us to always delete bottom-up and avoid any 1235693eedb1SChandler Carruth // dangling uses. 1236693eedb1SChandler Carruth SmallSetVector<BasicBlock *, 16> DeadBlocks; 1237693eedb1SChandler Carruth DeadBlocks.insert(DeadSubtreeRoot); 1238693eedb1SChandler Carruth for (int i = 0; i < (int)DeadBlocks.size(); ++i) 1239693eedb1SChandler Carruth for (DomTreeNode *ChildN : *DT[DeadBlocks[i]]) { 1240693eedb1SChandler Carruth // FIXME: This assert should pass and that means we don't change nearly 1241693eedb1SChandler Carruth // as much below! Consider rewriting all of this to avoid deleting 1242693eedb1SChandler Carruth // blocks. They are always cloned before being deleted, and so instead 1243693eedb1SChandler Carruth // could just be moved. 1244693eedb1SChandler Carruth // FIXME: This in turn means that we might actually be more able to 1245693eedb1SChandler Carruth // update the domtree. 1246693eedb1SChandler Carruth assert((L.contains(ChildN->getBlock()) || 1247693eedb1SChandler Carruth llvm::find(ExitBlocks, ChildN->getBlock()) != ExitBlocks.end()) && 1248693eedb1SChandler Carruth "Should never reach beyond the loop and exits when deleting!"); 1249693eedb1SChandler Carruth DeadBlocks.insert(ChildN->getBlock()); 1250693eedb1SChandler Carruth } 1251693eedb1SChandler Carruth 1252693eedb1SChandler Carruth // Filter out the dead blocks from the exit blocks list so that it can be 1253693eedb1SChandler Carruth // used in the caller. 1254693eedb1SChandler Carruth llvm::erase_if(ExitBlocks, 1255693eedb1SChandler Carruth [&](BasicBlock *BB) { return DeadBlocks.count(BB); }); 1256693eedb1SChandler Carruth 1257693eedb1SChandler Carruth // Remove these blocks from their successors. 1258693eedb1SChandler Carruth for (auto *BB : DeadBlocks) 1259693eedb1SChandler Carruth for (BasicBlock *SuccBB : successors(BB)) 1260693eedb1SChandler Carruth SuccBB->removePredecessor(BB, /*DontDeleteUselessPHIs*/ true); 1261693eedb1SChandler Carruth 1262693eedb1SChandler Carruth // Walk from this loop up through its parents removing all of the dead blocks. 1263693eedb1SChandler Carruth for (Loop *ParentL = &L; ParentL; ParentL = ParentL->getParentLoop()) { 1264693eedb1SChandler Carruth for (auto *BB : DeadBlocks) 1265693eedb1SChandler Carruth ParentL->getBlocksSet().erase(BB); 1266693eedb1SChandler Carruth llvm::erase_if(ParentL->getBlocksVector(), 1267693eedb1SChandler Carruth [&](BasicBlock *BB) { return DeadBlocks.count(BB); }); 1268693eedb1SChandler Carruth } 1269693eedb1SChandler Carruth 1270693eedb1SChandler Carruth // Now delete the dead child loops. This raw delete will clear them 1271693eedb1SChandler Carruth // recursively. 1272693eedb1SChandler Carruth llvm::erase_if(L.getSubLoopsVector(), [&](Loop *ChildL) { 1273693eedb1SChandler Carruth if (!DeadBlocks.count(ChildL->getHeader())) 1274693eedb1SChandler Carruth return false; 1275693eedb1SChandler Carruth 1276693eedb1SChandler Carruth assert(llvm::all_of(ChildL->blocks(), 1277693eedb1SChandler Carruth [&](BasicBlock *ChildBB) { 1278693eedb1SChandler Carruth return DeadBlocks.count(ChildBB); 1279693eedb1SChandler Carruth }) && 1280693eedb1SChandler Carruth "If the child loop header is dead all blocks in the child loop must " 1281693eedb1SChandler Carruth "be dead as well!"); 1282693eedb1SChandler Carruth LI.destroy(ChildL); 1283693eedb1SChandler Carruth return true; 1284693eedb1SChandler Carruth }); 1285693eedb1SChandler Carruth 1286693eedb1SChandler Carruth // Remove the mappings for the dead blocks. 1287693eedb1SChandler Carruth for (auto *BB : DeadBlocks) 1288693eedb1SChandler Carruth LI.changeLoopFor(BB, nullptr); 1289693eedb1SChandler Carruth 1290693eedb1SChandler Carruth // Drop all the references from these blocks to others to handle cyclic 1291693eedb1SChandler Carruth // references as we start deleting the blocks themselves. 1292693eedb1SChandler Carruth for (auto *BB : DeadBlocks) 1293693eedb1SChandler Carruth BB->dropAllReferences(); 1294693eedb1SChandler Carruth 1295693eedb1SChandler Carruth for (auto *BB : llvm::reverse(DeadBlocks)) { 1296693eedb1SChandler Carruth DT.eraseNode(BB); 1297693eedb1SChandler Carruth BB->eraseFromParent(); 1298693eedb1SChandler Carruth } 1299693eedb1SChandler Carruth } 1300693eedb1SChandler Carruth 1301693eedb1SChandler Carruth /// Recompute the set of blocks in a loop after unswitching. 1302693eedb1SChandler Carruth /// 1303693eedb1SChandler Carruth /// This walks from the original headers predecessors to rebuild the loop. We 1304693eedb1SChandler Carruth /// take advantage of the fact that new blocks can't have been added, and so we 1305693eedb1SChandler Carruth /// filter by the original loop's blocks. This also handles potentially 1306693eedb1SChandler Carruth /// unreachable code that we don't want to explore but might be found examining 1307693eedb1SChandler Carruth /// the predecessors of the header. 1308693eedb1SChandler Carruth /// 1309693eedb1SChandler Carruth /// If the original loop is no longer a loop, this will return an empty set. If 1310693eedb1SChandler Carruth /// it remains a loop, all the blocks within it will be added to the set 1311693eedb1SChandler Carruth /// (including those blocks in inner loops). 1312693eedb1SChandler Carruth static SmallPtrSet<const BasicBlock *, 16> recomputeLoopBlockSet(Loop &L, 1313693eedb1SChandler Carruth LoopInfo &LI) { 1314693eedb1SChandler Carruth SmallPtrSet<const BasicBlock *, 16> LoopBlockSet; 1315693eedb1SChandler Carruth 1316693eedb1SChandler Carruth auto *PH = L.getLoopPreheader(); 1317693eedb1SChandler Carruth auto *Header = L.getHeader(); 1318693eedb1SChandler Carruth 1319693eedb1SChandler Carruth // A worklist to use while walking backwards from the header. 1320693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist; 1321693eedb1SChandler Carruth 1322693eedb1SChandler Carruth // First walk the predecessors of the header to find the backedges. This will 1323693eedb1SChandler Carruth // form the basis of our walk. 1324693eedb1SChandler Carruth for (auto *Pred : predecessors(Header)) { 1325693eedb1SChandler Carruth // Skip the preheader. 1326693eedb1SChandler Carruth if (Pred == PH) 1327693eedb1SChandler Carruth continue; 1328693eedb1SChandler Carruth 1329693eedb1SChandler Carruth // Because the loop was in simplified form, the only non-loop predecessor 1330693eedb1SChandler Carruth // is the preheader. 1331693eedb1SChandler Carruth assert(L.contains(Pred) && "Found a predecessor of the loop header other " 1332693eedb1SChandler Carruth "than the preheader that is not part of the " 1333693eedb1SChandler Carruth "loop!"); 1334693eedb1SChandler Carruth 1335693eedb1SChandler Carruth // Insert this block into the loop set and on the first visit and, if it 1336693eedb1SChandler Carruth // isn't the header we're currently walking, put it into the worklist to 1337693eedb1SChandler Carruth // recurse through. 1338693eedb1SChandler Carruth if (LoopBlockSet.insert(Pred).second && Pred != Header) 1339693eedb1SChandler Carruth Worklist.push_back(Pred); 1340693eedb1SChandler Carruth } 1341693eedb1SChandler Carruth 1342693eedb1SChandler Carruth // If no backedges were found, we're done. 1343693eedb1SChandler Carruth if (LoopBlockSet.empty()) 1344693eedb1SChandler Carruth return LoopBlockSet; 1345693eedb1SChandler Carruth 1346693eedb1SChandler Carruth // Add the loop header to the set. 1347693eedb1SChandler Carruth LoopBlockSet.insert(Header); 1348693eedb1SChandler Carruth 1349693eedb1SChandler Carruth // We found backedges, recurse through them to identify the loop blocks. 1350693eedb1SChandler Carruth while (!Worklist.empty()) { 1351693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 1352693eedb1SChandler Carruth assert(LoopBlockSet.count(BB) && "Didn't put block into the loop set!"); 1353693eedb1SChandler Carruth 1354693eedb1SChandler Carruth // Because we know the inner loop structure remains valid we can use the 1355693eedb1SChandler Carruth // loop structure to jump immediately across the entire nested loop. 1356693eedb1SChandler Carruth // Further, because it is in loop simplified form, we can directly jump 1357693eedb1SChandler Carruth // to its preheader afterward. 1358693eedb1SChandler Carruth if (Loop *InnerL = LI.getLoopFor(BB)) 1359693eedb1SChandler Carruth if (InnerL != &L) { 1360693eedb1SChandler Carruth assert(L.contains(InnerL) && 1361693eedb1SChandler Carruth "Should not reach a loop *outside* this loop!"); 1362693eedb1SChandler Carruth // The preheader is the only possible predecessor of the loop so 1363693eedb1SChandler Carruth // insert it into the set and check whether it was already handled. 1364693eedb1SChandler Carruth auto *InnerPH = InnerL->getLoopPreheader(); 1365693eedb1SChandler Carruth assert(L.contains(InnerPH) && "Cannot contain an inner loop block " 1366693eedb1SChandler Carruth "but not contain the inner loop " 1367693eedb1SChandler Carruth "preheader!"); 1368693eedb1SChandler Carruth if (!LoopBlockSet.insert(InnerPH).second) 1369693eedb1SChandler Carruth // The only way to reach the preheader is through the loop body 1370693eedb1SChandler Carruth // itself so if it has been visited the loop is already handled. 1371693eedb1SChandler Carruth continue; 1372693eedb1SChandler Carruth 1373693eedb1SChandler Carruth // Insert all of the blocks (other than those already present) into 1374693eedb1SChandler Carruth // the loop set. The only block we expect to already be in the set is 1375693eedb1SChandler Carruth // the one we used to find this loop as we immediately handle the 1376693eedb1SChandler Carruth // others the first time we encounter the loop. 1377693eedb1SChandler Carruth for (auto *InnerBB : InnerL->blocks()) { 1378693eedb1SChandler Carruth if (InnerBB == BB) { 1379693eedb1SChandler Carruth assert(LoopBlockSet.count(InnerBB) && 1380693eedb1SChandler Carruth "Block should already be in the set!"); 1381693eedb1SChandler Carruth continue; 1382693eedb1SChandler Carruth } 1383693eedb1SChandler Carruth 1384693eedb1SChandler Carruth bool Inserted = LoopBlockSet.insert(InnerBB).second; 1385693eedb1SChandler Carruth (void)Inserted; 1386693eedb1SChandler Carruth assert(Inserted && "Should only insert an inner loop once!"); 1387693eedb1SChandler Carruth } 1388693eedb1SChandler Carruth 1389693eedb1SChandler Carruth // Add the preheader to the worklist so we will continue past the 1390693eedb1SChandler Carruth // loop body. 1391693eedb1SChandler Carruth Worklist.push_back(InnerPH); 1392693eedb1SChandler Carruth continue; 1393693eedb1SChandler Carruth } 1394693eedb1SChandler Carruth 1395693eedb1SChandler Carruth // Insert any predecessors that were in the original loop into the new 1396693eedb1SChandler Carruth // set, and if the insert is successful, add them to the worklist. 1397693eedb1SChandler Carruth for (auto *Pred : predecessors(BB)) 1398693eedb1SChandler Carruth if (L.contains(Pred) && LoopBlockSet.insert(Pred).second) 1399693eedb1SChandler Carruth Worklist.push_back(Pred); 1400693eedb1SChandler Carruth } 1401693eedb1SChandler Carruth 1402693eedb1SChandler Carruth // We've found all the blocks participating in the loop, return our completed 1403693eedb1SChandler Carruth // set. 1404693eedb1SChandler Carruth return LoopBlockSet; 1405693eedb1SChandler Carruth } 1406693eedb1SChandler Carruth 1407693eedb1SChandler Carruth /// Rebuild a loop after unswitching removes some subset of blocks and edges. 1408693eedb1SChandler Carruth /// 1409693eedb1SChandler Carruth /// The removal may have removed some child loops entirely but cannot have 1410693eedb1SChandler Carruth /// disturbed any remaining child loops. However, they may need to be hoisted 1411693eedb1SChandler Carruth /// to the parent loop (or to be top-level loops). The original loop may be 1412693eedb1SChandler Carruth /// completely removed. 1413693eedb1SChandler Carruth /// 1414693eedb1SChandler Carruth /// The sibling loops resulting from this update are returned. If the original 1415693eedb1SChandler Carruth /// loop remains a valid loop, it will be the first entry in this list with all 1416693eedb1SChandler Carruth /// of the newly sibling loops following it. 1417693eedb1SChandler Carruth /// 1418693eedb1SChandler Carruth /// Returns true if the loop remains a loop after unswitching, and false if it 1419693eedb1SChandler Carruth /// is no longer a loop after unswitching (and should not continue to be 1420693eedb1SChandler Carruth /// referenced). 1421693eedb1SChandler Carruth static bool rebuildLoopAfterUnswitch(Loop &L, ArrayRef<BasicBlock *> ExitBlocks, 1422693eedb1SChandler Carruth LoopInfo &LI, 1423693eedb1SChandler Carruth SmallVectorImpl<Loop *> &HoistedLoops) { 1424693eedb1SChandler Carruth auto *PH = L.getLoopPreheader(); 1425693eedb1SChandler Carruth 1426693eedb1SChandler Carruth // Compute the actual parent loop from the exit blocks. Because we may have 1427693eedb1SChandler Carruth // pruned some exits the loop may be different from the original parent. 1428693eedb1SChandler Carruth Loop *ParentL = nullptr; 1429693eedb1SChandler Carruth SmallVector<Loop *, 4> ExitLoops; 1430693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ExitsInLoops; 1431693eedb1SChandler Carruth ExitsInLoops.reserve(ExitBlocks.size()); 1432693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) 1433693eedb1SChandler Carruth if (Loop *ExitL = LI.getLoopFor(ExitBB)) { 1434693eedb1SChandler Carruth ExitLoops.push_back(ExitL); 1435693eedb1SChandler Carruth ExitsInLoops.push_back(ExitBB); 1436693eedb1SChandler Carruth if (!ParentL || (ParentL != ExitL && ParentL->contains(ExitL))) 1437693eedb1SChandler Carruth ParentL = ExitL; 1438693eedb1SChandler Carruth } 1439693eedb1SChandler Carruth 1440693eedb1SChandler Carruth // Recompute the blocks participating in this loop. This may be empty if it 1441693eedb1SChandler Carruth // is no longer a loop. 1442693eedb1SChandler Carruth auto LoopBlockSet = recomputeLoopBlockSet(L, LI); 1443693eedb1SChandler Carruth 1444693eedb1SChandler Carruth // If we still have a loop, we need to re-set the loop's parent as the exit 1445693eedb1SChandler Carruth // block set changing may have moved it within the loop nest. Note that this 1446693eedb1SChandler Carruth // can only happen when this loop has a parent as it can only hoist the loop 1447693eedb1SChandler Carruth // *up* the nest. 1448693eedb1SChandler Carruth if (!LoopBlockSet.empty() && L.getParentLoop() != ParentL) { 1449693eedb1SChandler Carruth // Remove this loop's (original) blocks from all of the intervening loops. 1450693eedb1SChandler Carruth for (Loop *IL = L.getParentLoop(); IL != ParentL; 1451693eedb1SChandler Carruth IL = IL->getParentLoop()) { 1452693eedb1SChandler Carruth IL->getBlocksSet().erase(PH); 1453693eedb1SChandler Carruth for (auto *BB : L.blocks()) 1454693eedb1SChandler Carruth IL->getBlocksSet().erase(BB); 1455693eedb1SChandler Carruth llvm::erase_if(IL->getBlocksVector(), [&](BasicBlock *BB) { 1456693eedb1SChandler Carruth return BB == PH || L.contains(BB); 1457693eedb1SChandler Carruth }); 1458693eedb1SChandler Carruth } 1459693eedb1SChandler Carruth 1460693eedb1SChandler Carruth LI.changeLoopFor(PH, ParentL); 1461693eedb1SChandler Carruth L.getParentLoop()->removeChildLoop(&L); 1462693eedb1SChandler Carruth if (ParentL) 1463693eedb1SChandler Carruth ParentL->addChildLoop(&L); 1464693eedb1SChandler Carruth else 1465693eedb1SChandler Carruth LI.addTopLevelLoop(&L); 1466693eedb1SChandler Carruth } 1467693eedb1SChandler Carruth 1468693eedb1SChandler Carruth // Now we update all the blocks which are no longer within the loop. 1469693eedb1SChandler Carruth auto &Blocks = L.getBlocksVector(); 1470693eedb1SChandler Carruth auto BlocksSplitI = 1471693eedb1SChandler Carruth LoopBlockSet.empty() 1472693eedb1SChandler Carruth ? Blocks.begin() 1473693eedb1SChandler Carruth : std::stable_partition( 1474693eedb1SChandler Carruth Blocks.begin(), Blocks.end(), 1475693eedb1SChandler Carruth [&](BasicBlock *BB) { return LoopBlockSet.count(BB); }); 1476693eedb1SChandler Carruth 1477693eedb1SChandler Carruth // Before we erase the list of unlooped blocks, build a set of them. 1478693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> UnloopedBlocks(BlocksSplitI, Blocks.end()); 1479693eedb1SChandler Carruth if (LoopBlockSet.empty()) 1480693eedb1SChandler Carruth UnloopedBlocks.insert(PH); 1481693eedb1SChandler Carruth 1482693eedb1SChandler Carruth // Now erase these blocks from the loop. 1483693eedb1SChandler Carruth for (auto *BB : make_range(BlocksSplitI, Blocks.end())) 1484693eedb1SChandler Carruth L.getBlocksSet().erase(BB); 1485693eedb1SChandler Carruth Blocks.erase(BlocksSplitI, Blocks.end()); 1486693eedb1SChandler Carruth 1487693eedb1SChandler Carruth // Sort the exits in ascending loop depth, we'll work backwards across these 1488693eedb1SChandler Carruth // to process them inside out. 1489693eedb1SChandler Carruth std::stable_sort(ExitsInLoops.begin(), ExitsInLoops.end(), 1490693eedb1SChandler Carruth [&](BasicBlock *LHS, BasicBlock *RHS) { 1491693eedb1SChandler Carruth return LI.getLoopDepth(LHS) < LI.getLoopDepth(RHS); 1492693eedb1SChandler Carruth }); 1493693eedb1SChandler Carruth 1494693eedb1SChandler Carruth // We'll build up a set for each exit loop. 1495693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 16> NewExitLoopBlocks; 1496693eedb1SChandler Carruth Loop *PrevExitL = L.getParentLoop(); // The deepest possible exit loop. 1497693eedb1SChandler Carruth 1498693eedb1SChandler Carruth auto RemoveUnloopedBlocksFromLoop = 1499693eedb1SChandler Carruth [](Loop &L, SmallPtrSetImpl<BasicBlock *> &UnloopedBlocks) { 1500693eedb1SChandler Carruth for (auto *BB : UnloopedBlocks) 1501693eedb1SChandler Carruth L.getBlocksSet().erase(BB); 1502693eedb1SChandler Carruth llvm::erase_if(L.getBlocksVector(), [&](BasicBlock *BB) { 1503693eedb1SChandler Carruth return UnloopedBlocks.count(BB); 1504693eedb1SChandler Carruth }); 1505693eedb1SChandler Carruth }; 1506693eedb1SChandler Carruth 1507693eedb1SChandler Carruth SmallVector<BasicBlock *, 16> Worklist; 1508693eedb1SChandler Carruth while (!UnloopedBlocks.empty() && !ExitsInLoops.empty()) { 1509693eedb1SChandler Carruth assert(Worklist.empty() && "Didn't clear worklist!"); 1510693eedb1SChandler Carruth assert(NewExitLoopBlocks.empty() && "Didn't clear loop set!"); 1511693eedb1SChandler Carruth 1512693eedb1SChandler Carruth // Grab the next exit block, in decreasing loop depth order. 1513693eedb1SChandler Carruth BasicBlock *ExitBB = ExitsInLoops.pop_back_val(); 1514693eedb1SChandler Carruth Loop &ExitL = *LI.getLoopFor(ExitBB); 1515693eedb1SChandler Carruth assert(ExitL.contains(&L) && "Exit loop must contain the inner loop!"); 1516693eedb1SChandler Carruth 1517693eedb1SChandler Carruth // Erase all of the unlooped blocks from the loops between the previous 1518693eedb1SChandler Carruth // exit loop and this exit loop. This works because the ExitInLoops list is 1519693eedb1SChandler Carruth // sorted in increasing order of loop depth and thus we visit loops in 1520693eedb1SChandler Carruth // decreasing order of loop depth. 1521693eedb1SChandler Carruth for (; PrevExitL != &ExitL; PrevExitL = PrevExitL->getParentLoop()) 1522693eedb1SChandler Carruth RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 1523693eedb1SChandler Carruth 1524693eedb1SChandler Carruth // Walk the CFG back until we hit the cloned PH adding everything reachable 1525693eedb1SChandler Carruth // and in the unlooped set to this exit block's loop. 1526693eedb1SChandler Carruth Worklist.push_back(ExitBB); 1527693eedb1SChandler Carruth do { 1528693eedb1SChandler Carruth BasicBlock *BB = Worklist.pop_back_val(); 1529693eedb1SChandler Carruth // We can stop recursing at the cloned preheader (if we get there). 1530693eedb1SChandler Carruth if (BB == PH) 1531693eedb1SChandler Carruth continue; 1532693eedb1SChandler Carruth 1533693eedb1SChandler Carruth for (BasicBlock *PredBB : predecessors(BB)) { 1534693eedb1SChandler Carruth // If this pred has already been moved to our set or is part of some 1535693eedb1SChandler Carruth // (inner) loop, no update needed. 1536693eedb1SChandler Carruth if (!UnloopedBlocks.erase(PredBB)) { 1537693eedb1SChandler Carruth assert((NewExitLoopBlocks.count(PredBB) || 1538693eedb1SChandler Carruth ExitL.contains(LI.getLoopFor(PredBB))) && 1539693eedb1SChandler Carruth "Predecessor not in a nested loop (or already visited)!"); 1540693eedb1SChandler Carruth continue; 1541693eedb1SChandler Carruth } 1542693eedb1SChandler Carruth 1543693eedb1SChandler Carruth // We just insert into the loop set here. We'll add these blocks to the 1544693eedb1SChandler Carruth // exit loop after we build up the set in a deterministic order rather 1545693eedb1SChandler Carruth // than the predecessor-influenced visit order. 1546693eedb1SChandler Carruth bool Inserted = NewExitLoopBlocks.insert(PredBB).second; 1547693eedb1SChandler Carruth (void)Inserted; 1548693eedb1SChandler Carruth assert(Inserted && "Should only visit an unlooped block once!"); 1549693eedb1SChandler Carruth 1550693eedb1SChandler Carruth // And recurse through to its predecessors. 1551693eedb1SChandler Carruth Worklist.push_back(PredBB); 1552693eedb1SChandler Carruth } 1553693eedb1SChandler Carruth } while (!Worklist.empty()); 1554693eedb1SChandler Carruth 1555693eedb1SChandler Carruth // If blocks in this exit loop were directly part of the original loop (as 1556693eedb1SChandler Carruth // opposed to a child loop) update the map to point to this exit loop. This 1557693eedb1SChandler Carruth // just updates a map and so the fact that the order is unstable is fine. 1558693eedb1SChandler Carruth for (auto *BB : NewExitLoopBlocks) 1559693eedb1SChandler Carruth if (Loop *BBL = LI.getLoopFor(BB)) 1560693eedb1SChandler Carruth if (BBL == &L || !L.contains(BBL)) 1561693eedb1SChandler Carruth LI.changeLoopFor(BB, &ExitL); 1562693eedb1SChandler Carruth 1563693eedb1SChandler Carruth // We will remove the remaining unlooped blocks from this loop in the next 1564693eedb1SChandler Carruth // iteration or below. 1565693eedb1SChandler Carruth NewExitLoopBlocks.clear(); 1566693eedb1SChandler Carruth } 1567693eedb1SChandler Carruth 1568693eedb1SChandler Carruth // Any remaining unlooped blocks are no longer part of any loop unless they 1569693eedb1SChandler Carruth // are part of some child loop. 1570693eedb1SChandler Carruth for (; PrevExitL; PrevExitL = PrevExitL->getParentLoop()) 1571693eedb1SChandler Carruth RemoveUnloopedBlocksFromLoop(*PrevExitL, UnloopedBlocks); 1572693eedb1SChandler Carruth for (auto *BB : UnloopedBlocks) 1573693eedb1SChandler Carruth if (Loop *BBL = LI.getLoopFor(BB)) 1574693eedb1SChandler Carruth if (BBL == &L || !L.contains(BBL)) 1575693eedb1SChandler Carruth LI.changeLoopFor(BB, nullptr); 1576693eedb1SChandler Carruth 1577693eedb1SChandler Carruth // Sink all the child loops whose headers are no longer in the loop set to 1578693eedb1SChandler Carruth // the parent (or to be top level loops). We reach into the loop and directly 1579693eedb1SChandler Carruth // update its subloop vector to make this batch update efficient. 1580693eedb1SChandler Carruth auto &SubLoops = L.getSubLoopsVector(); 1581693eedb1SChandler Carruth auto SubLoopsSplitI = 1582693eedb1SChandler Carruth LoopBlockSet.empty() 1583693eedb1SChandler Carruth ? SubLoops.begin() 1584693eedb1SChandler Carruth : std::stable_partition( 1585693eedb1SChandler Carruth SubLoops.begin(), SubLoops.end(), [&](Loop *SubL) { 1586693eedb1SChandler Carruth return LoopBlockSet.count(SubL->getHeader()); 1587693eedb1SChandler Carruth }); 1588693eedb1SChandler Carruth for (auto *HoistedL : make_range(SubLoopsSplitI, SubLoops.end())) { 1589693eedb1SChandler Carruth HoistedLoops.push_back(HoistedL); 1590693eedb1SChandler Carruth HoistedL->setParentLoop(nullptr); 1591693eedb1SChandler Carruth 1592693eedb1SChandler Carruth // To compute the new parent of this hoisted loop we look at where we 1593693eedb1SChandler Carruth // placed the preheader above. We can't lookup the header itself because we 1594693eedb1SChandler Carruth // retained the mapping from the header to the hoisted loop. But the 1595693eedb1SChandler Carruth // preheader and header should have the exact same new parent computed 1596693eedb1SChandler Carruth // based on the set of exit blocks from the original loop as the preheader 1597693eedb1SChandler Carruth // is a predecessor of the header and so reached in the reverse walk. And 1598693eedb1SChandler Carruth // because the loops were all in simplified form the preheader of the 1599693eedb1SChandler Carruth // hoisted loop can't be part of some *other* loop. 1600693eedb1SChandler Carruth if (auto *NewParentL = LI.getLoopFor(HoistedL->getLoopPreheader())) 1601693eedb1SChandler Carruth NewParentL->addChildLoop(HoistedL); 1602693eedb1SChandler Carruth else 1603693eedb1SChandler Carruth LI.addTopLevelLoop(HoistedL); 1604693eedb1SChandler Carruth } 1605693eedb1SChandler Carruth SubLoops.erase(SubLoopsSplitI, SubLoops.end()); 1606693eedb1SChandler Carruth 1607693eedb1SChandler Carruth // Actually delete the loop if nothing remained within it. 1608693eedb1SChandler Carruth if (Blocks.empty()) { 1609693eedb1SChandler Carruth assert(SubLoops.empty() && 1610693eedb1SChandler Carruth "Failed to remove all subloops from the original loop!"); 1611693eedb1SChandler Carruth if (Loop *ParentL = L.getParentLoop()) 1612693eedb1SChandler Carruth ParentL->removeChildLoop(llvm::find(*ParentL, &L)); 1613693eedb1SChandler Carruth else 1614693eedb1SChandler Carruth LI.removeLoop(llvm::find(LI, &L)); 1615693eedb1SChandler Carruth LI.destroy(&L); 1616693eedb1SChandler Carruth return false; 1617693eedb1SChandler Carruth } 1618693eedb1SChandler Carruth 1619693eedb1SChandler Carruth return true; 1620693eedb1SChandler Carruth } 1621693eedb1SChandler Carruth 1622693eedb1SChandler Carruth /// Helper to visit a dominator subtree, invoking a callable on each node. 1623693eedb1SChandler Carruth /// 1624693eedb1SChandler Carruth /// Returning false at any point will stop walking past that node of the tree. 1625693eedb1SChandler Carruth template <typename CallableT> 1626693eedb1SChandler Carruth void visitDomSubTree(DominatorTree &DT, BasicBlock *BB, CallableT Callable) { 1627693eedb1SChandler Carruth SmallVector<DomTreeNode *, 4> DomWorklist; 1628693eedb1SChandler Carruth DomWorklist.push_back(DT[BB]); 1629693eedb1SChandler Carruth #ifndef NDEBUG 1630693eedb1SChandler Carruth SmallPtrSet<DomTreeNode *, 4> Visited; 1631693eedb1SChandler Carruth Visited.insert(DT[BB]); 1632693eedb1SChandler Carruth #endif 1633693eedb1SChandler Carruth do { 1634693eedb1SChandler Carruth DomTreeNode *N = DomWorklist.pop_back_val(); 1635693eedb1SChandler Carruth 1636693eedb1SChandler Carruth // Visit this node. 1637693eedb1SChandler Carruth if (!Callable(N->getBlock())) 1638693eedb1SChandler Carruth continue; 1639693eedb1SChandler Carruth 1640693eedb1SChandler Carruth // Accumulate the child nodes. 1641693eedb1SChandler Carruth for (DomTreeNode *ChildN : *N) { 1642693eedb1SChandler Carruth assert(Visited.insert(ChildN).second && 1643693eedb1SChandler Carruth "Cannot visit a node twice when walking a tree!"); 1644693eedb1SChandler Carruth DomWorklist.push_back(ChildN); 1645693eedb1SChandler Carruth } 1646693eedb1SChandler Carruth } while (!DomWorklist.empty()); 1647693eedb1SChandler Carruth } 1648693eedb1SChandler Carruth 1649693eedb1SChandler Carruth /// Take an invariant branch that has been determined to be safe and worthwhile 1650693eedb1SChandler Carruth /// to unswitch despite being non-trivial to do so and perform the unswitch. 1651693eedb1SChandler Carruth /// 1652693eedb1SChandler Carruth /// This directly updates the CFG to hoist the predicate out of the loop, and 1653693eedb1SChandler Carruth /// clone the necessary parts of the loop to maintain behavior. 1654693eedb1SChandler Carruth /// 1655693eedb1SChandler Carruth /// It also updates both dominator tree and loopinfo based on the unswitching. 1656693eedb1SChandler Carruth /// 1657693eedb1SChandler Carruth /// Once unswitching has been performed it runs the provided callback to report 1658693eedb1SChandler Carruth /// the new loops and no-longer valid loops to the caller. 1659693eedb1SChandler Carruth static bool unswitchInvariantBranch( 1660693eedb1SChandler Carruth Loop &L, BranchInst &BI, DominatorTree &DT, LoopInfo &LI, 1661693eedb1SChandler Carruth AssumptionCache &AC, 1662693eedb1SChandler Carruth function_ref<void(bool, ArrayRef<Loop *>)> NonTrivialUnswitchCB) { 1663693eedb1SChandler Carruth assert(BI.isConditional() && "Can only unswitch a conditional branch!"); 1664693eedb1SChandler Carruth assert(L.isLoopInvariant(BI.getCondition()) && 1665693eedb1SChandler Carruth "Can only unswitch an invariant branch condition!"); 1666693eedb1SChandler Carruth 1667693eedb1SChandler Carruth // Constant and BBs tracking the cloned and continuing successor. 1668693eedb1SChandler Carruth const int ClonedSucc = 0; 1669693eedb1SChandler Carruth auto *ParentBB = BI.getParent(); 1670693eedb1SChandler Carruth auto *UnswitchedSuccBB = BI.getSuccessor(ClonedSucc); 1671693eedb1SChandler Carruth auto *ContinueSuccBB = BI.getSuccessor(1 - ClonedSucc); 1672693eedb1SChandler Carruth 1673693eedb1SChandler Carruth assert(UnswitchedSuccBB != ContinueSuccBB && 1674693eedb1SChandler Carruth "Should not unswitch a branch that always goes to the same place!"); 1675693eedb1SChandler Carruth 1676693eedb1SChandler Carruth // The branch should be in this exact loop. Any inner loop's invariant branch 1677693eedb1SChandler Carruth // should be handled by unswitching that inner loop. The caller of this 1678693eedb1SChandler Carruth // routine should filter out any candidates that remain (but were skipped for 1679693eedb1SChandler Carruth // whatever reason). 1680693eedb1SChandler Carruth assert(LI.getLoopFor(ParentBB) == &L && "Branch in an inner loop!"); 1681693eedb1SChandler Carruth 1682693eedb1SChandler Carruth SmallVector<BasicBlock *, 4> ExitBlocks; 1683693eedb1SChandler Carruth L.getUniqueExitBlocks(ExitBlocks); 1684693eedb1SChandler Carruth 1685693eedb1SChandler Carruth // We cannot unswitch if exit blocks contain a cleanuppad instruction as we 1686693eedb1SChandler Carruth // don't know how to split those exit blocks. 1687693eedb1SChandler Carruth // FIXME: We should teach SplitBlock to handle this and remove this 1688693eedb1SChandler Carruth // restriction. 1689693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) 1690693eedb1SChandler Carruth if (isa<CleanupPadInst>(ExitBB->getFirstNonPHI())) 1691693eedb1SChandler Carruth return false; 1692693eedb1SChandler Carruth 1693693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> ExitBlockSet(ExitBlocks.begin(), 1694693eedb1SChandler Carruth ExitBlocks.end()); 1695693eedb1SChandler Carruth 1696693eedb1SChandler Carruth // Compute the parent loop now before we start hacking on things. 1697693eedb1SChandler Carruth Loop *ParentL = L.getParentLoop(); 1698693eedb1SChandler Carruth 1699693eedb1SChandler Carruth // Compute the outer-most loop containing one of our exit blocks. This is the 1700693eedb1SChandler Carruth // furthest up our loopnest which can be mutated, which we will use below to 1701693eedb1SChandler Carruth // update things. 1702693eedb1SChandler Carruth Loop *OuterExitL = &L; 1703693eedb1SChandler Carruth for (auto *ExitBB : ExitBlocks) { 1704693eedb1SChandler Carruth Loop *NewOuterExitL = LI.getLoopFor(ExitBB); 1705693eedb1SChandler Carruth if (!NewOuterExitL) { 1706693eedb1SChandler Carruth // We exited the entire nest with this block, so we're done. 1707693eedb1SChandler Carruth OuterExitL = nullptr; 1708693eedb1SChandler Carruth break; 1709693eedb1SChandler Carruth } 1710693eedb1SChandler Carruth if (NewOuterExitL != OuterExitL && NewOuterExitL->contains(OuterExitL)) 1711693eedb1SChandler Carruth OuterExitL = NewOuterExitL; 1712693eedb1SChandler Carruth } 1713693eedb1SChandler Carruth 1714693eedb1SChandler Carruth // If the edge we *aren't* cloning in the unswitch (the continuing edge) 1715693eedb1SChandler Carruth // dominates its target, we can skip cloning the dominated region of the loop 1716693eedb1SChandler Carruth // and its exits. We compute this as a set of nodes to be skipped. 1717693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> SkippedLoopAndExitBlocks; 1718693eedb1SChandler Carruth if (ContinueSuccBB->getUniquePredecessor() || 1719693eedb1SChandler Carruth llvm::all_of(predecessors(ContinueSuccBB), [&](BasicBlock *PredBB) { 1720693eedb1SChandler Carruth return PredBB == ParentBB || DT.dominates(ContinueSuccBB, PredBB); 1721693eedb1SChandler Carruth })) { 1722693eedb1SChandler Carruth visitDomSubTree(DT, ContinueSuccBB, [&](BasicBlock *BB) { 1723693eedb1SChandler Carruth SkippedLoopAndExitBlocks.insert(BB); 1724693eedb1SChandler Carruth return true; 1725693eedb1SChandler Carruth }); 1726693eedb1SChandler Carruth } 1727693eedb1SChandler Carruth // Similarly, if the edge we *are* cloning in the unswitch (the unswitched 1728693eedb1SChandler Carruth // edge) dominates its target, we will end up with dead nodes in the original 1729693eedb1SChandler Carruth // loop and its exits that will need to be deleted. Here, we just retain that 1730693eedb1SChandler Carruth // the property holds and will compute the deleted set later. 1731693eedb1SChandler Carruth bool DeleteUnswitchedSucc = 1732693eedb1SChandler Carruth UnswitchedSuccBB->getUniquePredecessor() || 1733693eedb1SChandler Carruth llvm::all_of(predecessors(UnswitchedSuccBB), [&](BasicBlock *PredBB) { 1734693eedb1SChandler Carruth return PredBB == ParentBB || DT.dominates(UnswitchedSuccBB, PredBB); 1735693eedb1SChandler Carruth }); 1736693eedb1SChandler Carruth 1737693eedb1SChandler Carruth // Split the preheader, so that we know that there is a safe place to insert 1738693eedb1SChandler Carruth // the conditional branch. We will change the preheader to have a conditional 1739693eedb1SChandler Carruth // branch on LoopCond. The original preheader will become the split point 1740693eedb1SChandler Carruth // between the unswitched versions, and we will have a new preheader for the 1741693eedb1SChandler Carruth // original loop. 1742693eedb1SChandler Carruth BasicBlock *SplitBB = L.getLoopPreheader(); 1743693eedb1SChandler Carruth BasicBlock *LoopPH = SplitEdge(SplitBB, L.getHeader(), &DT, &LI); 1744693eedb1SChandler Carruth 1745693eedb1SChandler Carruth // Keep a mapping for the cloned values. 1746693eedb1SChandler Carruth ValueToValueMapTy VMap; 1747693eedb1SChandler Carruth 1748693eedb1SChandler Carruth // Build the cloned blocks from the loop. 1749693eedb1SChandler Carruth auto *ClonedPH = buildClonedLoopBlocks( 1750693eedb1SChandler Carruth L, LoopPH, SplitBB, ExitBlocks, ParentBB, UnswitchedSuccBB, 1751693eedb1SChandler Carruth ContinueSuccBB, SkippedLoopAndExitBlocks, VMap, AC, DT, LI); 1752693eedb1SChandler Carruth 1753693eedb1SChandler Carruth // Build the cloned loop structure itself. This may be substantially 1754693eedb1SChandler Carruth // different from the original structure due to the simplified CFG. This also 1755693eedb1SChandler Carruth // handles inserting all the cloned blocks into the correct loops. 1756693eedb1SChandler Carruth SmallVector<Loop *, 4> NonChildClonedLoops; 1757693eedb1SChandler Carruth Loop *ClonedL = 1758693eedb1SChandler Carruth buildClonedLoops(L, ExitBlocks, VMap, LI, NonChildClonedLoops); 1759693eedb1SChandler Carruth 1760693eedb1SChandler Carruth // Remove the parent as a predecessor of the unswitched successor. 1761693eedb1SChandler Carruth UnswitchedSuccBB->removePredecessor(ParentBB, /*DontDeleteUselessPHIs*/ true); 1762693eedb1SChandler Carruth 1763693eedb1SChandler Carruth // Now splice the branch from the original loop and use it to select between 1764693eedb1SChandler Carruth // the two loops. 1765693eedb1SChandler Carruth SplitBB->getTerminator()->eraseFromParent(); 1766693eedb1SChandler Carruth SplitBB->getInstList().splice(SplitBB->end(), ParentBB->getInstList(), BI); 1767693eedb1SChandler Carruth BI.setSuccessor(ClonedSucc, ClonedPH); 1768693eedb1SChandler Carruth BI.setSuccessor(1 - ClonedSucc, LoopPH); 1769693eedb1SChandler Carruth 1770693eedb1SChandler Carruth // Create a new unconditional branch to the continuing block (as opposed to 1771693eedb1SChandler Carruth // the one cloned). 1772693eedb1SChandler Carruth BranchInst::Create(ContinueSuccBB, ParentBB); 1773693eedb1SChandler Carruth 1774693eedb1SChandler Carruth // Delete anything that was made dead in the original loop due to 1775693eedb1SChandler Carruth // unswitching. 1776693eedb1SChandler Carruth if (DeleteUnswitchedSucc) 1777693eedb1SChandler Carruth deleteDeadBlocksFromLoop(L, UnswitchedSuccBB, ExitBlocks, DT, LI); 1778693eedb1SChandler Carruth 1779693eedb1SChandler Carruth SmallVector<Loop *, 4> HoistedLoops; 1780693eedb1SChandler Carruth bool IsStillLoop = rebuildLoopAfterUnswitch(L, ExitBlocks, LI, HoistedLoops); 1781693eedb1SChandler Carruth 1782693eedb1SChandler Carruth // This will have completely invalidated the dominator tree. We can't easily 1783693eedb1SChandler Carruth // bound how much is invalid because in some cases we will refine the 1784693eedb1SChandler Carruth // predecessor set of exit blocks of the loop which can move large unrelated 1785693eedb1SChandler Carruth // regions of code into a new subtree. 1786693eedb1SChandler Carruth // 1787693eedb1SChandler Carruth // FIXME: Eventually, we should use an incremental update utility that 1788693eedb1SChandler Carruth // leverages the existing information in the dominator tree (and potentially 1789693eedb1SChandler Carruth // the nature of the change) to more efficiently update things. 1790693eedb1SChandler Carruth DT.recalculate(*SplitBB->getParent()); 1791693eedb1SChandler Carruth 1792693eedb1SChandler Carruth // We can change which blocks are exit blocks of all the cloned sibling 1793693eedb1SChandler Carruth // loops, the current loop, and any parent loops which shared exit blocks 1794693eedb1SChandler Carruth // with the current loop. As a consequence, we need to re-form LCSSA for 1795693eedb1SChandler Carruth // them. But we shouldn't need to re-form LCSSA for any child loops. 1796693eedb1SChandler Carruth // FIXME: This could be made more efficient by tracking which exit blocks are 1797693eedb1SChandler Carruth // new, and focusing on them, but that isn't likely to be necessary. 1798693eedb1SChandler Carruth // 1799693eedb1SChandler Carruth // In order to reasonably rebuild LCSSA we need to walk inside-out across the 1800693eedb1SChandler Carruth // loop nest and update every loop that could have had its exits changed. We 1801693eedb1SChandler Carruth // also need to cover any intervening loops. We add all of these loops to 1802693eedb1SChandler Carruth // a list and sort them by loop depth to achieve this without updating 1803693eedb1SChandler Carruth // unnecessary loops. 1804693eedb1SChandler Carruth auto UpdateLCSSA = [&](Loop &UpdateL) { 1805693eedb1SChandler Carruth #ifndef NDEBUG 1806693eedb1SChandler Carruth for (Loop *ChildL : UpdateL) 1807693eedb1SChandler Carruth assert(ChildL->isRecursivelyLCSSAForm(DT, LI) && 1808693eedb1SChandler Carruth "Perturbed a child loop's LCSSA form!"); 1809693eedb1SChandler Carruth #endif 1810693eedb1SChandler Carruth formLCSSA(UpdateL, DT, &LI, nullptr); 1811693eedb1SChandler Carruth }; 1812693eedb1SChandler Carruth 1813693eedb1SChandler Carruth // For non-child cloned loops and hoisted loops, we just need to update LCSSA 1814693eedb1SChandler Carruth // and we can do it in any order as they don't nest relative to each other. 1815693eedb1SChandler Carruth for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) 1816693eedb1SChandler Carruth UpdateLCSSA(*UpdatedL); 1817693eedb1SChandler Carruth 1818693eedb1SChandler Carruth // If the original loop had exit blocks, walk up through the outer most loop 1819693eedb1SChandler Carruth // of those exit blocks to update LCSSA and form updated dedicated exits. 1820693eedb1SChandler Carruth if (OuterExitL != &L) { 1821693eedb1SChandler Carruth SmallVector<Loop *, 4> OuterLoops; 1822693eedb1SChandler Carruth // We start with the cloned loop and the current loop if they are loops and 1823693eedb1SChandler Carruth // move toward OuterExitL. Also, if either the cloned loop or the current 1824693eedb1SChandler Carruth // loop have become top level loops we need to walk all the way out. 1825693eedb1SChandler Carruth if (ClonedL) { 1826693eedb1SChandler Carruth OuterLoops.push_back(ClonedL); 1827693eedb1SChandler Carruth if (!ClonedL->getParentLoop()) 1828693eedb1SChandler Carruth OuterExitL = nullptr; 1829693eedb1SChandler Carruth } 1830693eedb1SChandler Carruth if (IsStillLoop) { 1831693eedb1SChandler Carruth OuterLoops.push_back(&L); 1832693eedb1SChandler Carruth if (!L.getParentLoop()) 1833693eedb1SChandler Carruth OuterExitL = nullptr; 1834693eedb1SChandler Carruth } 1835693eedb1SChandler Carruth // Grab all of the enclosing loops now. 1836693eedb1SChandler Carruth for (Loop *OuterL = ParentL; OuterL != OuterExitL; 1837693eedb1SChandler Carruth OuterL = OuterL->getParentLoop()) 1838693eedb1SChandler Carruth OuterLoops.push_back(OuterL); 1839693eedb1SChandler Carruth 1840693eedb1SChandler Carruth // Finally, update our list of outer loops. This is nicely ordered to work 1841693eedb1SChandler Carruth // inside-out. 1842693eedb1SChandler Carruth for (Loop *OuterL : OuterLoops) { 1843693eedb1SChandler Carruth // First build LCSSA for this loop so that we can preserve it when 1844693eedb1SChandler Carruth // forming dedicated exits. We don't want to perturb some other loop's 1845693eedb1SChandler Carruth // LCSSA while doing that CFG edit. 1846693eedb1SChandler Carruth UpdateLCSSA(*OuterL); 1847693eedb1SChandler Carruth 1848693eedb1SChandler Carruth // For loops reached by this loop's original exit blocks we may 1849693eedb1SChandler Carruth // introduced new, non-dedicated exits. At least try to re-form dedicated 1850693eedb1SChandler Carruth // exits for these loops. This may fail if they couldn't have dedicated 1851693eedb1SChandler Carruth // exits to start with. 1852693eedb1SChandler Carruth formDedicatedExitBlocks(OuterL, &DT, &LI, /*PreserveLCSSA*/ true); 1853693eedb1SChandler Carruth } 1854693eedb1SChandler Carruth } 1855693eedb1SChandler Carruth 1856693eedb1SChandler Carruth #ifndef NDEBUG 1857693eedb1SChandler Carruth // Verify the entire loop structure to catch any incorrect updates before we 1858693eedb1SChandler Carruth // progress in the pass pipeline. 1859693eedb1SChandler Carruth LI.verify(DT); 1860693eedb1SChandler Carruth #endif 1861693eedb1SChandler Carruth 1862693eedb1SChandler Carruth // Now that we've unswitched something, make callbacks to report the changes. 1863693eedb1SChandler Carruth // For that we need to merge together the updated loops and the cloned loops 1864693eedb1SChandler Carruth // and check whether the original loop survived. 1865693eedb1SChandler Carruth SmallVector<Loop *, 4> SibLoops; 1866693eedb1SChandler Carruth for (Loop *UpdatedL : llvm::concat<Loop *>(NonChildClonedLoops, HoistedLoops)) 1867693eedb1SChandler Carruth if (UpdatedL->getParentLoop() == ParentL) 1868693eedb1SChandler Carruth SibLoops.push_back(UpdatedL); 1869693eedb1SChandler Carruth NonTrivialUnswitchCB(IsStillLoop, SibLoops); 1870693eedb1SChandler Carruth 1871693eedb1SChandler Carruth ++NumBranches; 1872693eedb1SChandler Carruth return true; 1873693eedb1SChandler Carruth } 1874693eedb1SChandler Carruth 1875693eedb1SChandler Carruth /// Recursively compute the cost of a dominator subtree based on the per-block 1876693eedb1SChandler Carruth /// cost map provided. 1877693eedb1SChandler Carruth /// 1878693eedb1SChandler Carruth /// The recursive computation is memozied into the provided DT-indexed cost map 1879693eedb1SChandler Carruth /// to allow querying it for most nodes in the domtree without it becoming 1880693eedb1SChandler Carruth /// quadratic. 1881693eedb1SChandler Carruth static int 1882693eedb1SChandler Carruth computeDomSubtreeCost(DomTreeNode &N, 1883693eedb1SChandler Carruth const SmallDenseMap<BasicBlock *, int, 4> &BBCostMap, 1884693eedb1SChandler Carruth SmallDenseMap<DomTreeNode *, int, 4> &DTCostMap) { 1885693eedb1SChandler Carruth // Don't accumulate cost (or recurse through) blocks not in our block cost 1886693eedb1SChandler Carruth // map and thus not part of the duplication cost being considered. 1887693eedb1SChandler Carruth auto BBCostIt = BBCostMap.find(N.getBlock()); 1888693eedb1SChandler Carruth if (BBCostIt == BBCostMap.end()) 1889693eedb1SChandler Carruth return 0; 1890693eedb1SChandler Carruth 1891693eedb1SChandler Carruth // Lookup this node to see if we already computed its cost. 1892693eedb1SChandler Carruth auto DTCostIt = DTCostMap.find(&N); 1893693eedb1SChandler Carruth if (DTCostIt != DTCostMap.end()) 1894693eedb1SChandler Carruth return DTCostIt->second; 1895693eedb1SChandler Carruth 1896693eedb1SChandler Carruth // If not, we have to compute it. We can't use insert above and update 1897693eedb1SChandler Carruth // because computing the cost may insert more things into the map. 1898693eedb1SChandler Carruth int Cost = std::accumulate( 1899693eedb1SChandler Carruth N.begin(), N.end(), BBCostIt->second, [&](int Sum, DomTreeNode *ChildN) { 1900693eedb1SChandler Carruth return Sum + computeDomSubtreeCost(*ChildN, BBCostMap, DTCostMap); 1901693eedb1SChandler Carruth }); 1902693eedb1SChandler Carruth bool Inserted = DTCostMap.insert({&N, Cost}).second; 1903693eedb1SChandler Carruth (void)Inserted; 1904693eedb1SChandler Carruth assert(Inserted && "Should not insert a node while visiting children!"); 1905693eedb1SChandler Carruth return Cost; 1906693eedb1SChandler Carruth } 1907693eedb1SChandler Carruth 19081353f9a4SChandler Carruth /// Unswitch control flow predicated on loop invariant conditions. 19091353f9a4SChandler Carruth /// 19101353f9a4SChandler Carruth /// This first hoists all branches or switches which are trivial (IE, do not 19111353f9a4SChandler Carruth /// require duplicating any part of the loop) out of the loop body. It then 19121353f9a4SChandler Carruth /// looks at other loop invariant control flows and tries to unswitch those as 19131353f9a4SChandler Carruth /// well by cloning the loop if the result is small enough. 1914693eedb1SChandler Carruth static bool 1915693eedb1SChandler Carruth unswitchLoop(Loop &L, DominatorTree &DT, LoopInfo &LI, AssumptionCache &AC, 1916693eedb1SChandler Carruth TargetTransformInfo &TTI, bool NonTrivial, 1917693eedb1SChandler Carruth function_ref<void(bool, ArrayRef<Loop *>)> NonTrivialUnswitchCB) { 1918693eedb1SChandler Carruth assert(L.isRecursivelyLCSSAForm(DT, LI) && 19191353f9a4SChandler Carruth "Loops must be in LCSSA form before unswitching."); 19201353f9a4SChandler Carruth bool Changed = false; 19211353f9a4SChandler Carruth 19221353f9a4SChandler Carruth // Must be in loop simplified form: we need a preheader and dedicated exits. 19231353f9a4SChandler Carruth if (!L.isLoopSimplifyForm()) 19241353f9a4SChandler Carruth return false; 19251353f9a4SChandler Carruth 19261353f9a4SChandler Carruth // Try trivial unswitch first before loop over other basic blocks in the loop. 19271353f9a4SChandler Carruth Changed |= unswitchAllTrivialConditions(L, DT, LI); 19281353f9a4SChandler Carruth 1929693eedb1SChandler Carruth // If we're not doing non-trivial unswitching, we're done. We both accept 1930693eedb1SChandler Carruth // a parameter but also check a local flag that can be used for testing 1931693eedb1SChandler Carruth // a debugging. 1932693eedb1SChandler Carruth if (!NonTrivial && !EnableNonTrivialUnswitch) 1933693eedb1SChandler Carruth return Changed; 1934693eedb1SChandler Carruth 1935693eedb1SChandler Carruth // Collect all remaining invariant branch conditions within this loop (as 1936693eedb1SChandler Carruth // opposed to an inner loop which would be handled when visiting that inner 1937693eedb1SChandler Carruth // loop). 1938693eedb1SChandler Carruth SmallVector<TerminatorInst *, 4> UnswitchCandidates; 1939693eedb1SChandler Carruth for (auto *BB : L.blocks()) 1940693eedb1SChandler Carruth if (LI.getLoopFor(BB) == &L) 1941693eedb1SChandler Carruth if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) 1942693eedb1SChandler Carruth if (BI->isConditional() && L.isLoopInvariant(BI->getCondition()) && 1943693eedb1SChandler Carruth BI->getSuccessor(0) != BI->getSuccessor(1)) 1944693eedb1SChandler Carruth UnswitchCandidates.push_back(BI); 1945693eedb1SChandler Carruth 1946693eedb1SChandler Carruth // If we didn't find any candidates, we're done. 1947693eedb1SChandler Carruth if (UnswitchCandidates.empty()) 1948693eedb1SChandler Carruth return Changed; 1949693eedb1SChandler Carruth 1950693eedb1SChandler Carruth DEBUG(dbgs() << "Considering " << UnswitchCandidates.size() 1951693eedb1SChandler Carruth << " non-trivial loop invariant conditions for unswitching.\n"); 1952693eedb1SChandler Carruth 1953693eedb1SChandler Carruth // Given that unswitching these terminators will require duplicating parts of 1954693eedb1SChandler Carruth // the loop, so we need to be able to model that cost. Compute the ephemeral 1955693eedb1SChandler Carruth // values and set up a data structure to hold per-BB costs. We cache each 1956693eedb1SChandler Carruth // block's cost so that we don't recompute this when considering different 1957693eedb1SChandler Carruth // subsets of the loop for duplication during unswitching. 1958693eedb1SChandler Carruth SmallPtrSet<const Value *, 4> EphValues; 1959693eedb1SChandler Carruth CodeMetrics::collectEphemeralValues(&L, &AC, EphValues); 1960693eedb1SChandler Carruth SmallDenseMap<BasicBlock *, int, 4> BBCostMap; 1961693eedb1SChandler Carruth 1962693eedb1SChandler Carruth // Compute the cost of each block, as well as the total loop cost. Also, bail 1963693eedb1SChandler Carruth // out if we see instructions which are incompatible with loop unswitching 1964693eedb1SChandler Carruth // (convergent, noduplicate, or cross-basic-block tokens). 1965693eedb1SChandler Carruth // FIXME: We might be able to safely handle some of these in non-duplicated 1966693eedb1SChandler Carruth // regions. 1967693eedb1SChandler Carruth int LoopCost = 0; 1968693eedb1SChandler Carruth for (auto *BB : L.blocks()) { 1969693eedb1SChandler Carruth int Cost = 0; 1970693eedb1SChandler Carruth for (auto &I : *BB) { 1971693eedb1SChandler Carruth if (EphValues.count(&I)) 1972693eedb1SChandler Carruth continue; 1973693eedb1SChandler Carruth 1974693eedb1SChandler Carruth if (I.getType()->isTokenTy() && I.isUsedOutsideOfBlock(BB)) 1975693eedb1SChandler Carruth return Changed; 1976693eedb1SChandler Carruth if (auto CS = CallSite(&I)) 1977693eedb1SChandler Carruth if (CS.isConvergent() || CS.cannotDuplicate()) 1978693eedb1SChandler Carruth return Changed; 1979693eedb1SChandler Carruth 1980693eedb1SChandler Carruth Cost += TTI.getUserCost(&I); 1981693eedb1SChandler Carruth } 1982693eedb1SChandler Carruth assert(Cost >= 0 && "Must not have negative costs!"); 1983693eedb1SChandler Carruth LoopCost += Cost; 1984693eedb1SChandler Carruth assert(LoopCost >= 0 && "Must not have negative loop costs!"); 1985693eedb1SChandler Carruth BBCostMap[BB] = Cost; 1986693eedb1SChandler Carruth } 1987693eedb1SChandler Carruth DEBUG(dbgs() << " Total loop cost: " << LoopCost << "\n"); 1988693eedb1SChandler Carruth 1989693eedb1SChandler Carruth // Now we find the best candidate by searching for the one with the following 1990693eedb1SChandler Carruth // properties in order: 1991693eedb1SChandler Carruth // 1992693eedb1SChandler Carruth // 1) An unswitching cost below the threshold 1993693eedb1SChandler Carruth // 2) The smallest number of duplicated unswitch candidates (to avoid 1994693eedb1SChandler Carruth // creating redundant subsequent unswitching) 1995693eedb1SChandler Carruth // 3) The smallest cost after unswitching. 1996693eedb1SChandler Carruth // 1997693eedb1SChandler Carruth // We prioritize reducing fanout of unswitch candidates provided the cost 1998693eedb1SChandler Carruth // remains below the threshold because this has a multiplicative effect. 1999693eedb1SChandler Carruth // 2000693eedb1SChandler Carruth // This requires memoizing each dominator subtree to avoid redundant work. 2001693eedb1SChandler Carruth // 2002693eedb1SChandler Carruth // FIXME: Need to actually do the number of candidates part above. 2003693eedb1SChandler Carruth SmallDenseMap<DomTreeNode *, int, 4> DTCostMap; 2004693eedb1SChandler Carruth // Given a terminator which might be unswitched, computes the non-duplicated 2005693eedb1SChandler Carruth // cost for that terminator. 2006693eedb1SChandler Carruth auto ComputeUnswitchedCost = [&](TerminatorInst *TI) { 2007693eedb1SChandler Carruth BasicBlock &BB = *TI->getParent(); 2008693eedb1SChandler Carruth SmallPtrSet<BasicBlock *, 4> Visited; 2009693eedb1SChandler Carruth 2010693eedb1SChandler Carruth int Cost = LoopCost; 2011693eedb1SChandler Carruth for (BasicBlock *SuccBB : successors(&BB)) { 2012693eedb1SChandler Carruth // Don't count successors more than once. 2013693eedb1SChandler Carruth if (!Visited.insert(SuccBB).second) 2014693eedb1SChandler Carruth continue; 2015693eedb1SChandler Carruth 2016693eedb1SChandler Carruth // This successor's domtree will not need to be duplicated after 2017693eedb1SChandler Carruth // unswitching if the edge to the successor dominates it (and thus the 2018693eedb1SChandler Carruth // entire tree). This essentially means there is no other path into this 2019693eedb1SChandler Carruth // subtree and so it will end up live in only one clone of the loop. 2020693eedb1SChandler Carruth if (SuccBB->getUniquePredecessor() || 2021693eedb1SChandler Carruth llvm::all_of(predecessors(SuccBB), [&](BasicBlock *PredBB) { 2022693eedb1SChandler Carruth return PredBB == &BB || DT.dominates(SuccBB, PredBB); 2023693eedb1SChandler Carruth })) { 2024693eedb1SChandler Carruth Cost -= computeDomSubtreeCost(*DT[SuccBB], BBCostMap, DTCostMap); 2025693eedb1SChandler Carruth assert(Cost >= 0 && 2026693eedb1SChandler Carruth "Non-duplicated cost should never exceed total loop cost!"); 2027693eedb1SChandler Carruth } 2028693eedb1SChandler Carruth } 2029693eedb1SChandler Carruth 2030693eedb1SChandler Carruth // Now scale the cost by the number of unique successors minus one. We 2031693eedb1SChandler Carruth // subtract one because there is already at least one copy of the entire 2032693eedb1SChandler Carruth // loop. This is computing the new cost of unswitching a condition. 2033693eedb1SChandler Carruth assert(Visited.size() > 1 && 2034693eedb1SChandler Carruth "Cannot unswitch a condition without multiple distinct successors!"); 2035693eedb1SChandler Carruth return Cost * (Visited.size() - 1); 2036693eedb1SChandler Carruth }; 2037693eedb1SChandler Carruth TerminatorInst *BestUnswitchTI = nullptr; 2038693eedb1SChandler Carruth int BestUnswitchCost; 2039693eedb1SChandler Carruth for (TerminatorInst *CandidateTI : UnswitchCandidates) { 2040693eedb1SChandler Carruth int CandidateCost = ComputeUnswitchedCost(CandidateTI); 2041693eedb1SChandler Carruth DEBUG(dbgs() << " Computed cost of " << CandidateCost 2042693eedb1SChandler Carruth << " for unswitch candidate: " << *CandidateTI << "\n"); 2043693eedb1SChandler Carruth if (!BestUnswitchTI || CandidateCost < BestUnswitchCost) { 2044693eedb1SChandler Carruth BestUnswitchTI = CandidateTI; 2045693eedb1SChandler Carruth BestUnswitchCost = CandidateCost; 2046693eedb1SChandler Carruth } 2047693eedb1SChandler Carruth } 2048693eedb1SChandler Carruth 2049693eedb1SChandler Carruth if (BestUnswitchCost < UnswitchThreshold) { 2050693eedb1SChandler Carruth DEBUG(dbgs() << " Trying to unswitch non-trivial (cost = " 2051693eedb1SChandler Carruth << BestUnswitchCost << ") branch: " << *BestUnswitchTI 2052693eedb1SChandler Carruth << "\n"); 2053693eedb1SChandler Carruth Changed |= unswitchInvariantBranch(L, cast<BranchInst>(*BestUnswitchTI), DT, 2054693eedb1SChandler Carruth LI, AC, NonTrivialUnswitchCB); 2055693eedb1SChandler Carruth } else { 2056693eedb1SChandler Carruth DEBUG(dbgs() << "Cannot unswitch, lowest cost found: " << BestUnswitchCost 2057693eedb1SChandler Carruth << "\n"); 2058693eedb1SChandler Carruth } 20591353f9a4SChandler Carruth 20601353f9a4SChandler Carruth return Changed; 20611353f9a4SChandler Carruth } 20621353f9a4SChandler Carruth 20631353f9a4SChandler Carruth PreservedAnalyses SimpleLoopUnswitchPass::run(Loop &L, LoopAnalysisManager &AM, 20641353f9a4SChandler Carruth LoopStandardAnalysisResults &AR, 20651353f9a4SChandler Carruth LPMUpdater &U) { 20661353f9a4SChandler Carruth Function &F = *L.getHeader()->getParent(); 20671353f9a4SChandler Carruth (void)F; 20681353f9a4SChandler Carruth 20691353f9a4SChandler Carruth DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << L << "\n"); 20701353f9a4SChandler Carruth 2071693eedb1SChandler Carruth // Save the current loop name in a variable so that we can report it even 2072693eedb1SChandler Carruth // after it has been deleted. 2073693eedb1SChandler Carruth std::string LoopName = L.getName(); 2074693eedb1SChandler Carruth 2075693eedb1SChandler Carruth auto NonTrivialUnswitchCB = [&L, &U, &LoopName](bool CurrentLoopValid, 2076693eedb1SChandler Carruth ArrayRef<Loop *> NewLoops) { 2077693eedb1SChandler Carruth // If we did a non-trivial unswitch, we have added new (cloned) loops. 2078693eedb1SChandler Carruth U.addSiblingLoops(NewLoops); 2079693eedb1SChandler Carruth 2080693eedb1SChandler Carruth // If the current loop remains valid, we should revisit it to catch any 2081693eedb1SChandler Carruth // other unswitch opportunities. Otherwise, we need to mark it as deleted. 2082693eedb1SChandler Carruth if (CurrentLoopValid) 2083693eedb1SChandler Carruth U.revisitCurrentLoop(); 2084693eedb1SChandler Carruth else 2085693eedb1SChandler Carruth U.markLoopAsDeleted(L, LoopName); 2086693eedb1SChandler Carruth }; 2087693eedb1SChandler Carruth 2088693eedb1SChandler Carruth if (!unswitchLoop(L, AR.DT, AR.LI, AR.AC, AR.TTI, NonTrivial, 2089693eedb1SChandler Carruth NonTrivialUnswitchCB)) 20901353f9a4SChandler Carruth return PreservedAnalyses::all(); 20911353f9a4SChandler Carruth 20921353f9a4SChandler Carruth #ifndef NDEBUG 20931353f9a4SChandler Carruth // Historically this pass has had issues with the dominator tree so verify it 20941353f9a4SChandler Carruth // in asserts builds. 20951353f9a4SChandler Carruth AR.DT.verifyDomTree(); 20961353f9a4SChandler Carruth #endif 20971353f9a4SChandler Carruth return getLoopPassPreservedAnalyses(); 20981353f9a4SChandler Carruth } 20991353f9a4SChandler Carruth 21001353f9a4SChandler Carruth namespace { 2101a369a457SEugene Zelenko 21021353f9a4SChandler Carruth class SimpleLoopUnswitchLegacyPass : public LoopPass { 2103693eedb1SChandler Carruth bool NonTrivial; 2104693eedb1SChandler Carruth 21051353f9a4SChandler Carruth public: 21061353f9a4SChandler Carruth static char ID; // Pass ID, replacement for typeid 2107a369a457SEugene Zelenko 2108693eedb1SChandler Carruth explicit SimpleLoopUnswitchLegacyPass(bool NonTrivial = false) 2109693eedb1SChandler Carruth : LoopPass(ID), NonTrivial(NonTrivial) { 21101353f9a4SChandler Carruth initializeSimpleLoopUnswitchLegacyPassPass( 21111353f9a4SChandler Carruth *PassRegistry::getPassRegistry()); 21121353f9a4SChandler Carruth } 21131353f9a4SChandler Carruth 21141353f9a4SChandler Carruth bool runOnLoop(Loop *L, LPPassManager &LPM) override; 21151353f9a4SChandler Carruth 21161353f9a4SChandler Carruth void getAnalysisUsage(AnalysisUsage &AU) const override { 21171353f9a4SChandler Carruth AU.addRequired<AssumptionCacheTracker>(); 2118693eedb1SChandler Carruth AU.addRequired<TargetTransformInfoWrapperPass>(); 21191353f9a4SChandler Carruth getLoopAnalysisUsage(AU); 21201353f9a4SChandler Carruth } 21211353f9a4SChandler Carruth }; 2122a369a457SEugene Zelenko 2123a369a457SEugene Zelenko } // end anonymous namespace 21241353f9a4SChandler Carruth 21251353f9a4SChandler Carruth bool SimpleLoopUnswitchLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) { 21261353f9a4SChandler Carruth if (skipLoop(L)) 21271353f9a4SChandler Carruth return false; 21281353f9a4SChandler Carruth 21291353f9a4SChandler Carruth Function &F = *L->getHeader()->getParent(); 21301353f9a4SChandler Carruth 21311353f9a4SChandler Carruth DEBUG(dbgs() << "Unswitching loop in " << F.getName() << ": " << *L << "\n"); 21321353f9a4SChandler Carruth 21331353f9a4SChandler Carruth auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 21341353f9a4SChandler Carruth auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 21351353f9a4SChandler Carruth auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 2136693eedb1SChandler Carruth auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 21371353f9a4SChandler Carruth 2138693eedb1SChandler Carruth auto NonTrivialUnswitchCB = [&L, &LPM](bool CurrentLoopValid, 2139693eedb1SChandler Carruth ArrayRef<Loop *> NewLoops) { 2140693eedb1SChandler Carruth // If we did a non-trivial unswitch, we have added new (cloned) loops. 2141693eedb1SChandler Carruth for (auto *NewL : NewLoops) 2142693eedb1SChandler Carruth LPM.addLoop(*NewL); 2143693eedb1SChandler Carruth 2144693eedb1SChandler Carruth // If the current loop remains valid, re-add it to the queue. This is 2145693eedb1SChandler Carruth // a little wasteful as we'll finish processing the current loop as well, 2146693eedb1SChandler Carruth // but it is the best we can do in the old PM. 2147693eedb1SChandler Carruth if (CurrentLoopValid) 2148693eedb1SChandler Carruth LPM.addLoop(*L); 2149693eedb1SChandler Carruth else 2150693eedb1SChandler Carruth LPM.markLoopAsDeleted(*L); 2151693eedb1SChandler Carruth }; 2152693eedb1SChandler Carruth 2153693eedb1SChandler Carruth bool Changed = 2154693eedb1SChandler Carruth unswitchLoop(*L, DT, LI, AC, TTI, NonTrivial, NonTrivialUnswitchCB); 2155693eedb1SChandler Carruth 2156693eedb1SChandler Carruth // If anything was unswitched, also clear any cached information about this 2157693eedb1SChandler Carruth // loop. 2158693eedb1SChandler Carruth LPM.deleteSimpleAnalysisLoop(L); 21591353f9a4SChandler Carruth 21601353f9a4SChandler Carruth #ifndef NDEBUG 21611353f9a4SChandler Carruth // Historically this pass has had issues with the dominator tree so verify it 21621353f9a4SChandler Carruth // in asserts builds. 21631353f9a4SChandler Carruth DT.verifyDomTree(); 21641353f9a4SChandler Carruth #endif 21651353f9a4SChandler Carruth return Changed; 21661353f9a4SChandler Carruth } 21671353f9a4SChandler Carruth 21681353f9a4SChandler Carruth char SimpleLoopUnswitchLegacyPass::ID = 0; 21691353f9a4SChandler Carruth INITIALIZE_PASS_BEGIN(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", 21701353f9a4SChandler Carruth "Simple unswitch loops", false, false) 21711353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 2172693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2173693eedb1SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 21741353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(LoopPass) 21751353f9a4SChandler Carruth INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 21761353f9a4SChandler Carruth INITIALIZE_PASS_END(SimpleLoopUnswitchLegacyPass, "simple-loop-unswitch", 21771353f9a4SChandler Carruth "Simple unswitch loops", false, false) 21781353f9a4SChandler Carruth 2179693eedb1SChandler Carruth Pass *llvm::createSimpleLoopUnswitchLegacyPass(bool NonTrivial) { 2180693eedb1SChandler Carruth return new SimpleLoopUnswitchLegacyPass(NonTrivial); 21811353f9a4SChandler Carruth } 2182