1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===// 2950a13cfSDan Gohman // 3950a13cfSDan Gohman // The LLVM Compiler Infrastructure 4950a13cfSDan Gohman // 5950a13cfSDan Gohman // This file is distributed under the University of Illinois Open Source 6950a13cfSDan Gohman // License. See LICENSE.TXT for details. 7950a13cfSDan Gohman // 8950a13cfSDan Gohman //===----------------------------------------------------------------------===// 9950a13cfSDan Gohman /// 10950a13cfSDan Gohman /// \file 11950a13cfSDan Gohman /// \brief This file implements a CFG stacking pass. 12950a13cfSDan Gohman /// 13950a13cfSDan Gohman /// This pass reorders the blocks in a function to put them into a reverse 14950a13cfSDan Gohman /// post-order [0], with special care to keep the order as similar as possible 15950a13cfSDan Gohman /// to the original order, and to keep loops contiguous even in the case of 16950a13cfSDan Gohman /// split backedges. 17950a13cfSDan Gohman /// 18950a13cfSDan Gohman /// Then, it inserts BLOCK and LOOP markers to mark the start of scopes, since 19950a13cfSDan Gohman /// scope boundaries serve as the labels for WebAssembly's control transfers. 20950a13cfSDan Gohman /// 21950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on 22950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry. 23950a13cfSDan Gohman /// 24950a13cfSDan Gohman /// [0] https://en.wikipedia.org/wiki/Depth-first_search#Vertex_orderings 25950a13cfSDan Gohman /// 26950a13cfSDan Gohman //===----------------------------------------------------------------------===// 27950a13cfSDan Gohman 28950a13cfSDan Gohman #include "WebAssembly.h" 29950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 30950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 31950a13cfSDan Gohman #include "llvm/ADT/SCCIterator.h" 328fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h" 3332807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 34950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h" 35950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 36950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h" 37950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h" 38950a13cfSDan Gohman #include "llvm/Support/Debug.h" 39950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h" 40950a13cfSDan Gohman using namespace llvm; 41950a13cfSDan Gohman 42950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 43950a13cfSDan Gohman 44950a13cfSDan Gohman namespace { 45950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 46950a13cfSDan Gohman const char *getPassName() const override { 47950a13cfSDan Gohman return "WebAssembly CFG Stackify"; 48950a13cfSDan Gohman } 49950a13cfSDan Gohman 50950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 51950a13cfSDan Gohman AU.setPreservesCFG(); 5232807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 5332807932SDan Gohman AU.addPreserved<MachineDominatorTree>(); 54950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 55950a13cfSDan Gohman AU.addPreserved<MachineLoopInfo>(); 56950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 57950a13cfSDan Gohman } 58950a13cfSDan Gohman 59950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 60950a13cfSDan Gohman 61950a13cfSDan Gohman public: 62950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 63950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 64950a13cfSDan Gohman }; 65950a13cfSDan Gohman } // end anonymous namespace 66950a13cfSDan Gohman 67950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 68950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 69950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 70950a13cfSDan Gohman } 71950a13cfSDan Gohman 72950a13cfSDan Gohman static void EliminateMultipleEntryLoops(MachineFunction &MF, 73950a13cfSDan Gohman const MachineLoopInfo &MLI) { 74950a13cfSDan Gohman SmallPtrSet<MachineBasicBlock *, 8> InSet; 75950a13cfSDan Gohman for (scc_iterator<MachineFunction *> I = scc_begin(&MF), E = scc_end(&MF); 76950a13cfSDan Gohman I != E; ++I) { 77950a13cfSDan Gohman const std::vector<MachineBasicBlock *> &CurrentSCC = *I; 78950a13cfSDan Gohman 79950a13cfSDan Gohman // Skip trivial SCCs. 80950a13cfSDan Gohman if (CurrentSCC.size() == 1) 81950a13cfSDan Gohman continue; 82950a13cfSDan Gohman 83950a13cfSDan Gohman InSet.insert(CurrentSCC.begin(), CurrentSCC.end()); 84950a13cfSDan Gohman MachineBasicBlock *Header = nullptr; 85950a13cfSDan Gohman for (MachineBasicBlock *MBB : CurrentSCC) { 86950a13cfSDan Gohman for (MachineBasicBlock *Pred : MBB->predecessors()) { 87950a13cfSDan Gohman if (InSet.count(Pred)) 88950a13cfSDan Gohman continue; 89950a13cfSDan Gohman if (!Header) { 90950a13cfSDan Gohman Header = MBB; 91950a13cfSDan Gohman break; 92950a13cfSDan Gohman } 93950a13cfSDan Gohman // TODO: Implement multiple-entry loops. 94950a13cfSDan Gohman report_fatal_error("multiple-entry loops are not supported yet"); 95950a13cfSDan Gohman } 96950a13cfSDan Gohman } 97950a13cfSDan Gohman assert(MLI.isLoopHeader(Header)); 98950a13cfSDan Gohman 99950a13cfSDan Gohman InSet.clear(); 100950a13cfSDan Gohman } 101950a13cfSDan Gohman } 102950a13cfSDan Gohman 103950a13cfSDan Gohman namespace { 104950a13cfSDan Gohman /// Post-order traversal stack entry. 105950a13cfSDan Gohman struct POStackEntry { 106950a13cfSDan Gohman MachineBasicBlock *MBB; 107950a13cfSDan Gohman SmallVector<MachineBasicBlock *, 0> Succs; 108950a13cfSDan Gohman 109950a13cfSDan Gohman POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF, 110950a13cfSDan Gohman const MachineLoopInfo &MLI); 111950a13cfSDan Gohman }; 112950a13cfSDan Gohman } // end anonymous namespace 113950a13cfSDan Gohman 11432807932SDan Gohman static bool LoopContains(const MachineLoop *Loop, 11532807932SDan Gohman const MachineBasicBlock *MBB) { 11632807932SDan Gohman return Loop ? Loop->contains(MBB) : true; 11732807932SDan Gohman } 11832807932SDan Gohman 119950a13cfSDan Gohman POStackEntry::POStackEntry(MachineBasicBlock *MBB, MachineFunction &MF, 120950a13cfSDan Gohman const MachineLoopInfo &MLI) 121950a13cfSDan Gohman : MBB(MBB), Succs(MBB->successors()) { 122950a13cfSDan Gohman // RPO is not a unique form, since at every basic block with multiple 123950a13cfSDan Gohman // successors, the DFS has to pick which order to visit the successors in. 124950a13cfSDan Gohman // Sort them strategically (see below). 125950a13cfSDan Gohman MachineLoop *Loop = MLI.getLoopFor(MBB); 126950a13cfSDan Gohman MachineFunction::iterator Next = next(MachineFunction::iterator(MBB)); 127950a13cfSDan Gohman MachineBasicBlock *LayoutSucc = Next == MF.end() ? nullptr : &*Next; 128950a13cfSDan Gohman std::stable_sort( 129950a13cfSDan Gohman Succs.begin(), Succs.end(), 130950a13cfSDan Gohman [=, &MLI](const MachineBasicBlock *A, const MachineBasicBlock *B) { 131950a13cfSDan Gohman if (A == B) 132950a13cfSDan Gohman return false; 133950a13cfSDan Gohman 134950a13cfSDan Gohman // Keep loops contiguous by preferring the block that's in the same 135950a13cfSDan Gohman // loop. 13632807932SDan Gohman bool LoopContainsA = LoopContains(Loop, A); 13732807932SDan Gohman bool LoopContainsB = LoopContains(Loop, B); 13832807932SDan Gohman if (LoopContainsA && !LoopContainsB) 139950a13cfSDan Gohman return true; 14032807932SDan Gohman if (!LoopContainsA && LoopContainsB) 141950a13cfSDan Gohman return false; 142950a13cfSDan Gohman 143950a13cfSDan Gohman // Minimize perturbation by preferring the block which is the immediate 144950a13cfSDan Gohman // layout successor. 145950a13cfSDan Gohman if (A == LayoutSucc) 146950a13cfSDan Gohman return true; 147950a13cfSDan Gohman if (B == LayoutSucc) 148950a13cfSDan Gohman return false; 149950a13cfSDan Gohman 150950a13cfSDan Gohman // TODO: More sophisticated orderings may be profitable here. 151950a13cfSDan Gohman 152950a13cfSDan Gohman return false; 153950a13cfSDan Gohman }); 154950a13cfSDan Gohman } 155950a13cfSDan Gohman 1568fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from 1578fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is 1588fe7e86bSDan Gohman /// discontiguous. 1598fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) { 1608fe7e86bSDan Gohman MachineBasicBlock *Bottom = Loop->getHeader(); 1618fe7e86bSDan Gohman for (MachineBasicBlock *MBB : Loop->blocks()) 1628fe7e86bSDan Gohman if (MBB->getNumber() > Bottom->getNumber()) 1638fe7e86bSDan Gohman Bottom = MBB; 1648fe7e86bSDan Gohman return Bottom; 1658fe7e86bSDan Gohman } 1668fe7e86bSDan Gohman 167950a13cfSDan Gohman /// Sort the blocks in RPO, taking special care to make sure that loops are 168950a13cfSDan Gohman /// contiguous even in the case of split backedges. 1698fe7e86bSDan Gohman /// 1708fe7e86bSDan Gohman /// TODO: Determine whether RPO is actually worthwhile, or whether we should 1718fe7e86bSDan Gohman /// move to just a stable-topological-sort-based approach that would preserve 1728fe7e86bSDan Gohman /// more of the original order. 173950a13cfSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI) { 174950a13cfSDan Gohman // Note that we do our own RPO rather than using 175950a13cfSDan Gohman // "llvm/ADT/PostOrderIterator.h" because we want control over the order that 176950a13cfSDan Gohman // successors are visited in (see above). Also, we can sort the blocks in the 177950a13cfSDan Gohman // MachineFunction as we go. 178950a13cfSDan Gohman SmallPtrSet<MachineBasicBlock *, 16> Visited; 179950a13cfSDan Gohman SmallVector<POStackEntry, 16> Stack; 180950a13cfSDan Gohman 18196029f78SDan Gohman MachineBasicBlock *EntryBlock = &*MF.begin(); 18296029f78SDan Gohman Visited.insert(EntryBlock); 18396029f78SDan Gohman Stack.push_back(POStackEntry(EntryBlock, MF, MLI)); 184950a13cfSDan Gohman 185950a13cfSDan Gohman for (;;) { 186950a13cfSDan Gohman POStackEntry &Entry = Stack.back(); 187950a13cfSDan Gohman SmallVectorImpl<MachineBasicBlock *> &Succs = Entry.Succs; 188950a13cfSDan Gohman if (!Succs.empty()) { 189950a13cfSDan Gohman MachineBasicBlock *Succ = Succs.pop_back_val(); 190950a13cfSDan Gohman if (Visited.insert(Succ).second) 191950a13cfSDan Gohman Stack.push_back(POStackEntry(Succ, MF, MLI)); 192950a13cfSDan Gohman continue; 193950a13cfSDan Gohman } 194950a13cfSDan Gohman 195950a13cfSDan Gohman // Put the block in its position in the MachineFunction. 196950a13cfSDan Gohman MachineBasicBlock &MBB = *Entry.MBB; 19700406472SNico Weber MBB.moveBefore(&*MF.begin()); 198950a13cfSDan Gohman 199950a13cfSDan Gohman // Branch instructions may utilize a fallthrough, so update them if a 200950a13cfSDan Gohman // fallthrough has been added or removed. 201950a13cfSDan Gohman if (!MBB.empty() && MBB.back().isTerminator() && !MBB.back().isBranch() && 202950a13cfSDan Gohman !MBB.back().isBarrier()) 203950a13cfSDan Gohman report_fatal_error( 204950a13cfSDan Gohman "Non-branch terminator with fallthrough cannot yet be rewritten"); 205950a13cfSDan Gohman if (MBB.empty() || !MBB.back().isTerminator() || MBB.back().isBranch()) 206950a13cfSDan Gohman MBB.updateTerminator(); 207950a13cfSDan Gohman 208950a13cfSDan Gohman Stack.pop_back(); 209950a13cfSDan Gohman if (Stack.empty()) 210950a13cfSDan Gohman break; 211950a13cfSDan Gohman } 212950a13cfSDan Gohman 213950a13cfSDan Gohman // Now that we've sorted the blocks in RPO, renumber them. 214950a13cfSDan Gohman MF.RenumberBlocks(); 215950a13cfSDan Gohman 216950a13cfSDan Gohman #ifndef NDEBUG 2178fe7e86bSDan Gohman SmallSetVector<MachineLoop *, 8> OnStack; 2188fe7e86bSDan Gohman 2198fe7e86bSDan Gohman // Insert a sentinel representing the degenerate loop that starts at the 2208fe7e86bSDan Gohman // function entry block and includes the entire function as a "loop" that 2218fe7e86bSDan Gohman // executes once. 2228fe7e86bSDan Gohman OnStack.insert(nullptr); 2238fe7e86bSDan Gohman 2248fe7e86bSDan Gohman for (auto &MBB : MF) { 2258fe7e86bSDan Gohman assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative."); 2268fe7e86bSDan Gohman 2278fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 2288fe7e86bSDan Gohman if (Loop && &MBB == Loop->getHeader()) { 2298fe7e86bSDan Gohman // Loop header. The loop predecessor should be sorted above, and the other 2308fe7e86bSDan Gohman // predecessors should be backedges below. 2318fe7e86bSDan Gohman for (auto Pred : MBB.predecessors()) 2328fe7e86bSDan Gohman assert( 2338fe7e86bSDan Gohman (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) && 2348fe7e86bSDan Gohman "Loop header predecessors must be loop predecessors or backedges"); 2358fe7e86bSDan Gohman assert(OnStack.insert(Loop) && "Loops should be declared at most once."); 23632807932SDan Gohman } else { 2378fe7e86bSDan Gohman // Not a loop header. All predecessors should be sorted above. 238950a13cfSDan Gohman for (auto Pred : MBB.predecessors()) 239950a13cfSDan Gohman assert(Pred->getNumber() < MBB.getNumber() && 2408fe7e86bSDan Gohman "Non-loop-header predecessors should be topologically sorted"); 2418fe7e86bSDan Gohman assert(OnStack.count(MLI.getLoopFor(&MBB)) && 2428fe7e86bSDan Gohman "Blocks must be nested in their loops"); 243950a13cfSDan Gohman } 2448fe7e86bSDan Gohman while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back())) 2458fe7e86bSDan Gohman OnStack.pop_back(); 2468fe7e86bSDan Gohman } 2478fe7e86bSDan Gohman assert(OnStack.pop_back_val() == nullptr && 2488fe7e86bSDan Gohman "The function entry block shouldn't actually be a loop header"); 2498fe7e86bSDan Gohman assert(OnStack.empty() && 2508fe7e86bSDan Gohman "Control flow stack pushes and pops should be balanced."); 251950a13cfSDan Gohman #endif 252950a13cfSDan Gohman } 253950a13cfSDan Gohman 254b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 255b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 256b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 257b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 258b3aa1ecaSDan Gohman /// explicit mentions. 25935e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 26035e4a289SDan Gohman MachineBasicBlock *MBB) { 261b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 262b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 263b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 264b3aa1ecaSDan Gohman return true; 265b3aa1ecaSDan Gohman return false; 266b3aa1ecaSDan Gohman } 267b3aa1ecaSDan Gohman 26832807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 2698fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF, 2708fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 27132807932SDan Gohman const WebAssemblyInstrInfo &TII, 2728fe7e86bSDan Gohman const MachineLoopInfo &MLI, 2738fe7e86bSDan Gohman MachineDominatorTree &MDT) { 2748fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2758fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2768fe7e86bSDan Gohman // which reduces overall stack height. 27732807932SDan Gohman MachineBasicBlock *Header = nullptr; 27832807932SDan Gohman bool IsBranchedTo = false; 27932807932SDan Gohman int MBBNumber = MBB.getNumber(); 28032807932SDan Gohman for (MachineBasicBlock *Pred : MBB.predecessors()) 28132807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 28232807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 283b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 28432807932SDan Gohman IsBranchedTo = true; 28532807932SDan Gohman } 28632807932SDan Gohman if (!Header) 28732807932SDan Gohman return; 28832807932SDan Gohman if (!IsBranchedTo) 28932807932SDan Gohman return; 29032807932SDan Gohman 2918fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2928fe7e86bSDan Gohman MachineBasicBlock *LayoutPred = &*prev(MachineFunction::iterator(&MBB)); 2938fe7e86bSDan Gohman 2948fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2958fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2968fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2978fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2988fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2998fe7e86bSDan Gohman // Skip over an intervening scope. 3008fe7e86bSDan Gohman I = next(MachineFunction::iterator(ScopeTop)); 3018fe7e86bSDan Gohman } else { 3028fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 3038fe7e86bSDan Gohman Header = ScopeTop; 3048fe7e86bSDan Gohman break; 3058fe7e86bSDan Gohman } 3068fe7e86bSDan Gohman } 3078fe7e86bSDan Gohman } 3088fe7e86bSDan Gohman 3098fe7e86bSDan Gohman // If there's a loop which ends just before MBB which contains Header, we can 3108fe7e86bSDan Gohman // reuse its label instead of inserting a new BLOCK. 3118fe7e86bSDan Gohman for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred); 3128fe7e86bSDan Gohman Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop()) 3138fe7e86bSDan Gohman if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header)) 3148fe7e86bSDan Gohman return; 3158fe7e86bSDan Gohman 3168fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 31732807932SDan Gohman MachineBasicBlock::iterator InsertPos; 31832807932SDan Gohman MachineLoop *HeaderLoop = MLI.getLoopFor(Header); 3198fe7e86bSDan Gohman if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) { 3208fe7e86bSDan Gohman // Header is the header of a loop that does not lexically contain MBB, so 3218fe7e86bSDan Gohman // the BLOCK needs to be above the LOOP. 32232807932SDan Gohman InsertPos = Header->begin(); 32332807932SDan Gohman } else { 3248887d1faSDan Gohman // Otherwise, insert the BLOCK as late in Header as we can, but before the 3258887d1faSDan Gohman // beginning of the local expression tree and any nested BLOCKs. 32632807932SDan Gohman InsertPos = Header->getFirstTerminator(); 32732807932SDan Gohman while (InsertPos != Header->begin() && 3288887d1faSDan Gohman prev(InsertPos)->definesRegister(WebAssembly::EXPR_STACK) && 329*1d68e80fSDan Gohman prev(InsertPos)->getOpcode() != WebAssembly::LOOP && 330*1d68e80fSDan Gohman prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK && 331*1d68e80fSDan Gohman prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP) 33232807932SDan Gohman --InsertPos; 33332807932SDan Gohman } 33432807932SDan Gohman 3358fe7e86bSDan Gohman // Add the BLOCK. 336*1d68e80fSDan Gohman BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK)); 337*1d68e80fSDan Gohman 338*1d68e80fSDan Gohman // Mark the end of the block. 339*1d68e80fSDan Gohman InsertPos = MBB.begin(); 340*1d68e80fSDan Gohman while (InsertPos != MBB.end() && 341*1d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 342*1d68e80fSDan Gohman ++InsertPos; 343*1d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK)); 3448fe7e86bSDan Gohman 3458fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3468fe7e86bSDan Gohman int Number = MBB.getNumber(); 3478fe7e86bSDan Gohman if (!ScopeTops[Number] || 3488fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3498fe7e86bSDan Gohman ScopeTops[Number] = Header; 350950a13cfSDan Gohman } 351950a13cfSDan Gohman 3528fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 353*1d68e80fSDan Gohman static void PlaceLoopMarker( 354*1d68e80fSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 3558fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 356*1d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops, 357*1d68e80fSDan Gohman const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) { 3588fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3598fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3608fe7e86bSDan Gohman return; 3618fe7e86bSDan Gohman 3628fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3638fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 3648fe7e86bSDan Gohman MachineBasicBlock *Bottom = LoopBottom(Loop); 365e3e4a5ffSDan Gohman auto Iter = next(MachineFunction::iterator(Bottom)); 366e3e4a5ffSDan Gohman if (Iter == MF.end()) { 367f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 368f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 369f6857223SDan Gohman Label->addSuccessor(Label); 370f6857223SDan Gohman MF.push_back(Label); 371e3e4a5ffSDan Gohman Iter = next(MachineFunction::iterator(Bottom)); 372e3e4a5ffSDan Gohman } 3738fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 374f6857223SDan Gohman 375*1d68e80fSDan Gohman // Mark the beginning of the loop (after the end of any existing loop that 376*1d68e80fSDan Gohman // ends here). 377*1d68e80fSDan Gohman auto InsertPos = MBB.begin(); 378*1d68e80fSDan Gohman while (InsertPos != MBB.end() && 379*1d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 380*1d68e80fSDan Gohman ++InsertPos; 381*1d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP)); 382*1d68e80fSDan Gohman 383*1d68e80fSDan Gohman // Mark the end of the loop. 384*1d68e80fSDan Gohman MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(), 385*1d68e80fSDan Gohman TII.get(WebAssembly::END_LOOP)); 386*1d68e80fSDan Gohman LoopTops[End] = &MBB; 3878fe7e86bSDan Gohman 3888fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 3898fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 3908fe7e86bSDan Gohman "With RPO we should visit the outer-most loop for a block first."); 3918fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 3928fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 393e3e4a5ffSDan Gohman } 394950a13cfSDan Gohman 395*1d68e80fSDan Gohman static unsigned 396*1d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 397*1d68e80fSDan Gohman const MachineBasicBlock *MBB) { 398*1d68e80fSDan Gohman unsigned Depth = 0; 399*1d68e80fSDan Gohman for (auto X : reverse(Stack)) { 400*1d68e80fSDan Gohman if (X == MBB) 401*1d68e80fSDan Gohman break; 402*1d68e80fSDan Gohman ++Depth; 403*1d68e80fSDan Gohman } 404*1d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 405*1d68e80fSDan Gohman return Depth; 406*1d68e80fSDan Gohman } 407*1d68e80fSDan Gohman 4088fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places. 4098fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 4108fe7e86bSDan Gohman const WebAssemblyInstrInfo &TII, 4118fe7e86bSDan Gohman MachineDominatorTree &MDT) { 4128fe7e86bSDan Gohman // For each block whose label represents the end of a scope, record the block 4138fe7e86bSDan Gohman // which holds the beginning of the scope. This will allow us to quickly skip 4148fe7e86bSDan Gohman // over scoped regions when walking blocks. We allocate one more than the 4158fe7e86bSDan Gohman // number of blocks in the function to accommodate for the possible fake block 4168fe7e86bSDan Gohman // we may insert at the end. 4178fe7e86bSDan Gohman SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 4188fe7e86bSDan Gohman 419*1d68e80fSDan Gohman // For eacn LOOP_END, the corresponding LOOP. 420*1d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops; 421*1d68e80fSDan Gohman 4228fe7e86bSDan Gohman for (auto &MBB : MF) { 4238fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 424*1d68e80fSDan Gohman PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 4258fe7e86bSDan Gohman 42632807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 4278fe7e86bSDan Gohman PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT); 428950a13cfSDan Gohman } 429950a13cfSDan Gohman 430*1d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 431*1d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 432*1d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 433*1d68e80fSDan Gohman for (auto &MI : reverse(MBB)) { 434*1d68e80fSDan Gohman switch (MI.getOpcode()) { 435*1d68e80fSDan Gohman case WebAssembly::BLOCK: 436*1d68e80fSDan Gohman assert(ScopeTops[Stack.back()->getNumber()] == &MBB && 437*1d68e80fSDan Gohman "Block should be balanced"); 438*1d68e80fSDan Gohman Stack.pop_back(); 439*1d68e80fSDan Gohman break; 440*1d68e80fSDan Gohman case WebAssembly::LOOP: 441*1d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 442*1d68e80fSDan Gohman Stack.pop_back(); 443*1d68e80fSDan Gohman Stack.pop_back(); 444*1d68e80fSDan Gohman break; 445*1d68e80fSDan Gohman case WebAssembly::END_BLOCK: 446*1d68e80fSDan Gohman Stack.push_back(&MBB); 447*1d68e80fSDan Gohman break; 448*1d68e80fSDan Gohman case WebAssembly::END_LOOP: 449*1d68e80fSDan Gohman Stack.push_back(&MBB); 450*1d68e80fSDan Gohman Stack.push_back(LoopTops[&MI]); 451*1d68e80fSDan Gohman break; 452*1d68e80fSDan Gohman default: 453*1d68e80fSDan Gohman if (MI.isTerminator()) { 454*1d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 455*1d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 456*1d68e80fSDan Gohman while (MI.getNumOperands() > 0) 457*1d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 458*1d68e80fSDan Gohman for (auto MO : Ops) { 459*1d68e80fSDan Gohman if (MO.isMBB()) 460*1d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 461*1d68e80fSDan Gohman MI.addOperand(MF, MO); 46232807932SDan Gohman } 463*1d68e80fSDan Gohman } 464*1d68e80fSDan Gohman break; 465*1d68e80fSDan Gohman } 466*1d68e80fSDan Gohman } 467*1d68e80fSDan Gohman } 468*1d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 469*1d68e80fSDan Gohman } 47032807932SDan Gohman 471950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 472950a13cfSDan Gohman DEBUG(dbgs() << "********** CFG Stackifying **********\n" 473950a13cfSDan Gohman "********** Function: " 474950a13cfSDan Gohman << MF.getName() << '\n'); 475950a13cfSDan Gohman 476950a13cfSDan Gohman const auto &MLI = getAnalysis<MachineLoopInfo>(); 47732807932SDan Gohman auto &MDT = getAnalysis<MachineDominatorTree>(); 478950a13cfSDan Gohman const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 479950a13cfSDan Gohman 480950a13cfSDan Gohman // RPO sorting needs all loops to be single-entry. 481950a13cfSDan Gohman EliminateMultipleEntryLoops(MF, MLI); 482950a13cfSDan Gohman 483950a13cfSDan Gohman // Sort the blocks in RPO, with contiguous loops. 484950a13cfSDan Gohman SortBlocks(MF, MLI); 485950a13cfSDan Gohman 486950a13cfSDan Gohman // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 48732807932SDan Gohman PlaceMarkers(MF, MLI, TII, MDT); 48832807932SDan Gohman 489950a13cfSDan Gohman return true; 490950a13cfSDan Gohman } 491