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 /// 13442bfcecSDan Gohman /// This pass reorders the blocks in a function to put them into topological 14442bfcecSDan Gohman /// order, ignoring loop backedges, and without any loop being interrupted 15442bfcecSDan Gohman /// by a block not dominated by the loop header, with special care to keep the 16442bfcecSDan Gohman /// order as similar as possible to the original order. 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 //===----------------------------------------------------------------------===// 25950a13cfSDan Gohman 26950a13cfSDan Gohman #include "WebAssembly.h" 27950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 29950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 30442bfcecSDan Gohman #include "llvm/ADT/PriorityQueue.h" 318fe7e86bSDan Gohman #include "llvm/ADT/SetVector.h" 3232807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 33950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h" 34950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 35950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h" 369c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.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 728fe7e86bSDan Gohman /// Return the "bottom" block of a loop. This differs from 738fe7e86bSDan Gohman /// MachineLoop::getBottomBlock in that it works even if the loop is 748fe7e86bSDan Gohman /// discontiguous. 758fe7e86bSDan Gohman static MachineBasicBlock *LoopBottom(const MachineLoop *Loop) { 768fe7e86bSDan Gohman MachineBasicBlock *Bottom = Loop->getHeader(); 778fe7e86bSDan Gohman for (MachineBasicBlock *MBB : Loop->blocks()) 788fe7e86bSDan Gohman if (MBB->getNumber() > Bottom->getNumber()) 798fe7e86bSDan Gohman Bottom = MBB; 808fe7e86bSDan Gohman return Bottom; 818fe7e86bSDan Gohman } 828fe7e86bSDan Gohman 83442bfcecSDan Gohman static void MaybeUpdateTerminator(MachineBasicBlock *MBB) { 84442bfcecSDan Gohman #ifndef NDEBUG 85442bfcecSDan Gohman bool AnyBarrier = false; 86442bfcecSDan Gohman #endif 87442bfcecSDan Gohman bool AllAnalyzable = true; 88442bfcecSDan Gohman for (const MachineInstr &Term : MBB->terminators()) { 89442bfcecSDan Gohman #ifndef NDEBUG 90442bfcecSDan Gohman AnyBarrier |= Term.isBarrier(); 91442bfcecSDan Gohman #endif 92442bfcecSDan Gohman AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch(); 93442bfcecSDan Gohman } 94442bfcecSDan Gohman assert((AnyBarrier || AllAnalyzable) && 95442bfcecSDan Gohman "AnalyzeBranch needs to analyze any block with a fallthrough"); 96442bfcecSDan Gohman if (AllAnalyzable) 97442bfcecSDan Gohman MBB->updateTerminator(); 98442bfcecSDan Gohman } 99950a13cfSDan Gohman 100442bfcecSDan Gohman namespace { 101442bfcecSDan Gohman /// Sort blocks by their number. 102442bfcecSDan Gohman struct CompareBlockNumbers { 103442bfcecSDan Gohman bool operator()(const MachineBasicBlock *A, 104442bfcecSDan Gohman const MachineBasicBlock *B) const { 105442bfcecSDan Gohman return A->getNumber() > B->getNumber(); 106442bfcecSDan Gohman } 107442bfcecSDan Gohman }; 108442bfcecSDan Gohman /// Sort blocks by their number in the opposite order.. 109442bfcecSDan Gohman struct CompareBlockNumbersBackwards { 110442bfcecSDan Gohman bool operator()(const MachineBasicBlock *A, 111442bfcecSDan Gohman const MachineBasicBlock *B) const { 112442bfcecSDan Gohman return A->getNumber() < B->getNumber(); 113442bfcecSDan Gohman } 114442bfcecSDan Gohman }; 115442bfcecSDan Gohman /// Bookkeeping for a loop to help ensure that we don't mix blocks not dominated 116442bfcecSDan Gohman /// by the loop header among the loop's blocks. 117442bfcecSDan Gohman struct Entry { 118442bfcecSDan Gohman const MachineLoop *Loop; 119442bfcecSDan Gohman unsigned NumBlocksLeft; 120950a13cfSDan Gohman 121442bfcecSDan Gohman /// List of blocks not dominated by Loop's header that are deferred until 122442bfcecSDan Gohman /// after all of Loop's blocks have been seen. 123442bfcecSDan Gohman std::vector<MachineBasicBlock *> Deferred; 124442bfcecSDan Gohman 125442bfcecSDan Gohman explicit Entry(const MachineLoop *L) 126442bfcecSDan Gohman : Loop(L), NumBlocksLeft(L->getNumBlocks()) {} 127442bfcecSDan Gohman }; 128442bfcecSDan Gohman } 129442bfcecSDan Gohman 130442bfcecSDan Gohman /// Sort the blocks, taking special care to make sure that loops are not 131442bfcecSDan Gohman /// interrupted by blocks not dominated by their header. 132442bfcecSDan Gohman /// TODO: There are many opportunities for improving the heuristics here. 133442bfcecSDan Gohman /// Explore them. 134442bfcecSDan Gohman static void SortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI, 135442bfcecSDan Gohman const MachineDominatorTree &MDT) { 136442bfcecSDan Gohman // Prepare for a topological sort: Record the number of predecessors each 137442bfcecSDan Gohman // block has, ignoring loop backedges. 138442bfcecSDan Gohman MF.RenumberBlocks(); 139442bfcecSDan Gohman SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0); 140442bfcecSDan Gohman for (MachineBasicBlock &MBB : MF) { 141442bfcecSDan Gohman unsigned N = MBB.pred_size(); 142442bfcecSDan Gohman if (MachineLoop *L = MLI.getLoopFor(&MBB)) 143442bfcecSDan Gohman if (L->getHeader() == &MBB) 144442bfcecSDan Gohman for (const MachineBasicBlock *Pred : MBB.predecessors()) 145442bfcecSDan Gohman if (L->contains(Pred)) 146442bfcecSDan Gohman --N; 147442bfcecSDan Gohman NumPredsLeft[MBB.getNumber()] = N; 148442bfcecSDan Gohman } 149442bfcecSDan Gohman 150442bfcecSDan Gohman // Topological sort the CFG, with additional constraints: 151442bfcecSDan Gohman // - Between a loop header and the last block in the loop, there can be 152442bfcecSDan Gohman // no blocks not dominated by the loop header. 153442bfcecSDan Gohman // - It's desirable to preserve the original block order when possible. 154442bfcecSDan Gohman // We use two ready lists; Preferred and Ready. Preferred has recently 155442bfcecSDan Gohman // processed sucessors, to help preserve block sequences from the original 156442bfcecSDan Gohman // order. Ready has the remaining ready blocks. 157442bfcecSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>, 158442bfcecSDan Gohman CompareBlockNumbers> 159442bfcecSDan Gohman Preferred; 160442bfcecSDan Gohman PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>, 161442bfcecSDan Gohman CompareBlockNumbersBackwards> 162442bfcecSDan Gohman Ready; 163442bfcecSDan Gohman SmallVector<Entry, 4> Loops; 164442bfcecSDan Gohman for (MachineBasicBlock *MBB = &MF.front();;) { 165442bfcecSDan Gohman const MachineLoop *L = MLI.getLoopFor(MBB); 166442bfcecSDan Gohman if (L) { 167442bfcecSDan Gohman // If MBB is a loop header, add it to the active loop list. We can't put 168442bfcecSDan Gohman // any blocks that it doesn't dominate until we see the end of the loop. 169442bfcecSDan Gohman if (L->getHeader() == MBB) 170442bfcecSDan Gohman Loops.push_back(Entry(L)); 171442bfcecSDan Gohman // For each active loop the block is in, decrement the count. If MBB is 172442bfcecSDan Gohman // the last block in an active loop, take it off the list and pick up any 173442bfcecSDan Gohman // blocks deferred because the header didn't dominate them. 174442bfcecSDan Gohman for (Entry &E : Loops) 175442bfcecSDan Gohman if (E.Loop->contains(MBB) && --E.NumBlocksLeft == 0) 176442bfcecSDan Gohman for (auto DeferredBlock : E.Deferred) 177442bfcecSDan Gohman Ready.push(DeferredBlock); 178442bfcecSDan Gohman while (!Loops.empty() && Loops.back().NumBlocksLeft == 0) 179442bfcecSDan Gohman Loops.pop_back(); 180442bfcecSDan Gohman } 181442bfcecSDan Gohman // The main topological sort logic. 182442bfcecSDan Gohman for (MachineBasicBlock *Succ : MBB->successors()) { 183442bfcecSDan Gohman // Ignore backedges. 184442bfcecSDan Gohman if (MachineLoop *SuccL = MLI.getLoopFor(Succ)) 185442bfcecSDan Gohman if (SuccL->getHeader() == Succ && SuccL->contains(MBB)) 186442bfcecSDan Gohman continue; 187442bfcecSDan Gohman // Decrement the predecessor count. If it's now zero, it's ready. 188442bfcecSDan Gohman if (--NumPredsLeft[Succ->getNumber()] == 0) 189442bfcecSDan Gohman Preferred.push(Succ); 190442bfcecSDan Gohman } 191442bfcecSDan Gohman // Determine the block to follow MBB. First try to find a preferred block, 192442bfcecSDan Gohman // to preserve the original block order when possible. 193442bfcecSDan Gohman MachineBasicBlock *Next = nullptr; 194442bfcecSDan Gohman while (!Preferred.empty()) { 195442bfcecSDan Gohman Next = Preferred.top(); 196442bfcecSDan Gohman Preferred.pop(); 197442bfcecSDan Gohman // If X isn't dominated by the top active loop header, defer it until that 198442bfcecSDan Gohman // loop is done. 199442bfcecSDan Gohman if (!Loops.empty() && 200442bfcecSDan Gohman !MDT.dominates(Loops.back().Loop->getHeader(), Next)) { 201442bfcecSDan Gohman Loops.back().Deferred.push_back(Next); 202442bfcecSDan Gohman Next = nullptr; 203950a13cfSDan Gohman continue; 204950a13cfSDan Gohman } 205442bfcecSDan Gohman // If Next was originally ordered before MBB, and it isn't because it was 206442bfcecSDan Gohman // loop-rotated above the header, it's not preferred. 207442bfcecSDan Gohman if (Next->getNumber() < MBB->getNumber() && 208442bfcecSDan Gohman (!L || !L->contains(Next) || 209442bfcecSDan Gohman L->getHeader()->getNumber() < Next->getNumber())) { 210442bfcecSDan Gohman Ready.push(Next); 211442bfcecSDan Gohman Next = nullptr; 212442bfcecSDan Gohman continue; 213442bfcecSDan Gohman } 214950a13cfSDan Gohman break; 215950a13cfSDan Gohman } 216442bfcecSDan Gohman // If we didn't find a suitable block in the Preferred list, check the 217442bfcecSDan Gohman // general Ready list. 218442bfcecSDan Gohman if (!Next) { 219442bfcecSDan Gohman // If there are no more blocks to process, we're done. 220442bfcecSDan Gohman if (Ready.empty()) { 221442bfcecSDan Gohman MaybeUpdateTerminator(MBB); 222442bfcecSDan Gohman break; 223442bfcecSDan Gohman } 224442bfcecSDan Gohman for (;;) { 225442bfcecSDan Gohman Next = Ready.top(); 226442bfcecSDan Gohman Ready.pop(); 227442bfcecSDan Gohman // If Next isn't dominated by the top active loop header, defer it until 228442bfcecSDan Gohman // that loop is done. 229442bfcecSDan Gohman if (!Loops.empty() && 230442bfcecSDan Gohman !MDT.dominates(Loops.back().Loop->getHeader(), Next)) { 231442bfcecSDan Gohman Loops.back().Deferred.push_back(Next); 232442bfcecSDan Gohman continue; 233442bfcecSDan Gohman } 234442bfcecSDan Gohman break; 235442bfcecSDan Gohman } 236442bfcecSDan Gohman } 237442bfcecSDan Gohman // Move the next block into place and iterate. 238442bfcecSDan Gohman Next->moveAfter(MBB); 239442bfcecSDan Gohman MaybeUpdateTerminator(MBB); 240442bfcecSDan Gohman MBB = Next; 241442bfcecSDan Gohman } 242442bfcecSDan Gohman assert(Loops.empty() && "Active loop list not finished"); 243950a13cfSDan Gohman MF.RenumberBlocks(); 244950a13cfSDan Gohman 245950a13cfSDan Gohman #ifndef NDEBUG 2468fe7e86bSDan Gohman SmallSetVector<MachineLoop *, 8> OnStack; 2478fe7e86bSDan Gohman 2488fe7e86bSDan Gohman // Insert a sentinel representing the degenerate loop that starts at the 2498fe7e86bSDan Gohman // function entry block and includes the entire function as a "loop" that 2508fe7e86bSDan Gohman // executes once. 2518fe7e86bSDan Gohman OnStack.insert(nullptr); 2528fe7e86bSDan Gohman 2538fe7e86bSDan Gohman for (auto &MBB : MF) { 2548fe7e86bSDan Gohman assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative."); 2558fe7e86bSDan Gohman 2568fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 2578fe7e86bSDan Gohman if (Loop && &MBB == Loop->getHeader()) { 2588fe7e86bSDan Gohman // Loop header. The loop predecessor should be sorted above, and the other 2598fe7e86bSDan Gohman // predecessors should be backedges below. 2608fe7e86bSDan Gohman for (auto Pred : MBB.predecessors()) 2618fe7e86bSDan Gohman assert( 2628fe7e86bSDan Gohman (Pred->getNumber() < MBB.getNumber() || Loop->contains(Pred)) && 2638fe7e86bSDan Gohman "Loop header predecessors must be loop predecessors or backedges"); 2648fe7e86bSDan Gohman assert(OnStack.insert(Loop) && "Loops should be declared at most once."); 26532807932SDan Gohman } else { 2668fe7e86bSDan Gohman // Not a loop header. All predecessors should be sorted above. 267950a13cfSDan Gohman for (auto Pred : MBB.predecessors()) 268950a13cfSDan Gohman assert(Pred->getNumber() < MBB.getNumber() && 2698fe7e86bSDan Gohman "Non-loop-header predecessors should be topologically sorted"); 2708fe7e86bSDan Gohman assert(OnStack.count(MLI.getLoopFor(&MBB)) && 2718fe7e86bSDan Gohman "Blocks must be nested in their loops"); 272950a13cfSDan Gohman } 2738fe7e86bSDan Gohman while (OnStack.size() > 1 && &MBB == LoopBottom(OnStack.back())) 2748fe7e86bSDan Gohman OnStack.pop_back(); 2758fe7e86bSDan Gohman } 2768fe7e86bSDan Gohman assert(OnStack.pop_back_val() == nullptr && 2778fe7e86bSDan Gohman "The function entry block shouldn't actually be a loop header"); 2788fe7e86bSDan Gohman assert(OnStack.empty() && 2798fe7e86bSDan Gohman "Control flow stack pushes and pops should be balanced."); 280950a13cfSDan Gohman #endif 281950a13cfSDan Gohman } 282950a13cfSDan Gohman 283b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 284b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 285b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 286b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 287b3aa1ecaSDan Gohman /// explicit mentions. 28835e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 28935e4a289SDan Gohman MachineBasicBlock *MBB) { 290b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 291b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 292b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 293b3aa1ecaSDan Gohman return true; 294b3aa1ecaSDan Gohman return false; 295b3aa1ecaSDan Gohman } 296b3aa1ecaSDan Gohman 297ed0f1138SDan Gohman /// Test whether MI is a child of some other node in an expression tree. 298500d0469SDuncan P. N. Exon Smith static bool IsChild(const MachineInstr &MI, 299ed0f1138SDan Gohman const WebAssemblyFunctionInfo &MFI) { 300500d0469SDuncan P. N. Exon Smith if (MI.getNumOperands() == 0) 301ed0f1138SDan Gohman return false; 302500d0469SDuncan P. N. Exon Smith const MachineOperand &MO = MI.getOperand(0); 303ed0f1138SDan Gohman if (!MO.isReg() || MO.isImplicit() || !MO.isDef()) 304ed0f1138SDan Gohman return false; 305ed0f1138SDan Gohman unsigned Reg = MO.getReg(); 306ed0f1138SDan Gohman return TargetRegisterInfo::isVirtualRegister(Reg) && 307ed0f1138SDan Gohman MFI.isVRegStackified(Reg); 308ed0f1138SDan Gohman } 309ed0f1138SDan Gohman 31032807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 3118fe7e86bSDan Gohman static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF, 3128fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 31332807932SDan Gohman const WebAssemblyInstrInfo &TII, 3148fe7e86bSDan Gohman const MachineLoopInfo &MLI, 315ed0f1138SDan Gohman MachineDominatorTree &MDT, 316ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI) { 3178fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 3188fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 3198fe7e86bSDan Gohman // which reduces overall stack height. 32032807932SDan Gohman MachineBasicBlock *Header = nullptr; 32132807932SDan Gohman bool IsBranchedTo = false; 32232807932SDan Gohman int MBBNumber = MBB.getNumber(); 32332807932SDan Gohman for (MachineBasicBlock *Pred : MBB.predecessors()) 32432807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 32532807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 326b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 32732807932SDan Gohman IsBranchedTo = true; 32832807932SDan Gohman } 32932807932SDan Gohman if (!Header) 33032807932SDan Gohman return; 33132807932SDan Gohman if (!IsBranchedTo) 33232807932SDan Gohman return; 33332807932SDan Gohman 3348fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 335*ef0a45aaSBenjamin Kramer MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB)); 3368fe7e86bSDan Gohman 3378fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 3388fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 3398fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 3408fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 3418fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 3428fe7e86bSDan Gohman // Skip over an intervening scope. 343*ef0a45aaSBenjamin Kramer I = std::next(MachineFunction::iterator(ScopeTop)); 3448fe7e86bSDan Gohman } else { 3458fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 3468fe7e86bSDan Gohman Header = ScopeTop; 3478fe7e86bSDan Gohman break; 3488fe7e86bSDan Gohman } 3498fe7e86bSDan Gohman } 3508fe7e86bSDan Gohman } 3518fe7e86bSDan Gohman 3528fe7e86bSDan Gohman // If there's a loop which ends just before MBB which contains Header, we can 3538fe7e86bSDan Gohman // reuse its label instead of inserting a new BLOCK. 3548fe7e86bSDan Gohman for (MachineLoop *Loop = MLI.getLoopFor(LayoutPred); 3558fe7e86bSDan Gohman Loop && Loop->contains(LayoutPred); Loop = Loop->getParentLoop()) 3568fe7e86bSDan Gohman if (Loop && LoopBottom(Loop) == LayoutPred && Loop->contains(Header)) 3578fe7e86bSDan Gohman return; 3588fe7e86bSDan Gohman 3598fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 36032807932SDan Gohman MachineBasicBlock::iterator InsertPos; 36132807932SDan Gohman MachineLoop *HeaderLoop = MLI.getLoopFor(Header); 3628fe7e86bSDan Gohman if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) { 3638fe7e86bSDan Gohman // Header is the header of a loop that does not lexically contain MBB, so 364a187ab2aSDan Gohman // the BLOCK needs to be above the LOOP, after any END constructs. 36532807932SDan Gohman InsertPos = Header->begin(); 366a187ab2aSDan Gohman while (InsertPos->getOpcode() != WebAssembly::LOOP) 367a187ab2aSDan Gohman ++InsertPos; 36832807932SDan Gohman } else { 3698887d1faSDan Gohman // Otherwise, insert the BLOCK as late in Header as we can, but before the 3708887d1faSDan Gohman // beginning of the local expression tree and any nested BLOCKs. 37132807932SDan Gohman InsertPos = Header->getFirstTerminator(); 372*ef0a45aaSBenjamin Kramer while (InsertPos != Header->begin() && 373*ef0a45aaSBenjamin Kramer IsChild(*std::prev(InsertPos), MFI) && 374*ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP && 375*ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK && 376*ef0a45aaSBenjamin Kramer std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP) 37732807932SDan Gohman --InsertPos; 37832807932SDan Gohman } 37932807932SDan Gohman 3808fe7e86bSDan Gohman // Add the BLOCK. 3811d68e80fSDan Gohman BuildMI(*Header, InsertPos, DebugLoc(), TII.get(WebAssembly::BLOCK)); 3821d68e80fSDan Gohman 3831d68e80fSDan Gohman // Mark the end of the block. 3841d68e80fSDan Gohman InsertPos = MBB.begin(); 3851d68e80fSDan Gohman while (InsertPos != MBB.end() && 3861d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 3871d68e80fSDan Gohman ++InsertPos; 3881d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::END_BLOCK)); 3898fe7e86bSDan Gohman 3908fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3918fe7e86bSDan Gohman int Number = MBB.getNumber(); 3928fe7e86bSDan Gohman if (!ScopeTops[Number] || 3938fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3948fe7e86bSDan Gohman ScopeTops[Number] = Header; 395950a13cfSDan Gohman } 396950a13cfSDan Gohman 3978fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 3981d68e80fSDan Gohman static void PlaceLoopMarker( 3991d68e80fSDan Gohman MachineBasicBlock &MBB, MachineFunction &MF, 4008fe7e86bSDan Gohman SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 4011d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> &LoopTops, 4021d68e80fSDan Gohman const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) { 4038fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 4048fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 4058fe7e86bSDan Gohman return; 4068fe7e86bSDan Gohman 4078fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 4088fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 4098fe7e86bSDan Gohman MachineBasicBlock *Bottom = LoopBottom(Loop); 410*ef0a45aaSBenjamin Kramer auto Iter = std::next(MachineFunction::iterator(Bottom)); 411e3e4a5ffSDan Gohman if (Iter == MF.end()) { 412f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 413f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 414f6857223SDan Gohman Label->addSuccessor(Label); 415f6857223SDan Gohman MF.push_back(Label); 416*ef0a45aaSBenjamin Kramer Iter = std::next(MachineFunction::iterator(Bottom)); 417e3e4a5ffSDan Gohman } 4188fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 419f6857223SDan Gohman 4201d68e80fSDan Gohman // Mark the beginning of the loop (after the end of any existing loop that 4211d68e80fSDan Gohman // ends here). 4221d68e80fSDan Gohman auto InsertPos = MBB.begin(); 4231d68e80fSDan Gohman while (InsertPos != MBB.end() && 4241d68e80fSDan Gohman InsertPos->getOpcode() == WebAssembly::END_LOOP) 4251d68e80fSDan Gohman ++InsertPos; 4261d68e80fSDan Gohman BuildMI(MBB, InsertPos, DebugLoc(), TII.get(WebAssembly::LOOP)); 4271d68e80fSDan Gohman 4281d68e80fSDan Gohman // Mark the end of the loop. 4291d68e80fSDan Gohman MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(), 4301d68e80fSDan Gohman TII.get(WebAssembly::END_LOOP)); 4311d68e80fSDan Gohman LoopTops[End] = &MBB; 4328fe7e86bSDan Gohman 4338fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4348fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 435442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4368fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4378fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 438e3e4a5ffSDan Gohman } 439950a13cfSDan Gohman 4401d68e80fSDan Gohman static unsigned 4411d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 4421d68e80fSDan Gohman const MachineBasicBlock *MBB) { 4431d68e80fSDan Gohman unsigned Depth = 0; 4441d68e80fSDan Gohman for (auto X : reverse(Stack)) { 4451d68e80fSDan Gohman if (X == MBB) 4461d68e80fSDan Gohman break; 4471d68e80fSDan Gohman ++Depth; 4481d68e80fSDan Gohman } 4491d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 4501d68e80fSDan Gohman return Depth; 4511d68e80fSDan Gohman } 4521d68e80fSDan Gohman 4538fe7e86bSDan Gohman /// Insert LOOP and BLOCK markers at appropriate places. 4548fe7e86bSDan Gohman static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 4558fe7e86bSDan Gohman const WebAssemblyInstrInfo &TII, 456ed0f1138SDan Gohman MachineDominatorTree &MDT, 457ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI) { 4588fe7e86bSDan Gohman // For each block whose label represents the end of a scope, record the block 4598fe7e86bSDan Gohman // which holds the beginning of the scope. This will allow us to quickly skip 4608fe7e86bSDan Gohman // over scoped regions when walking blocks. We allocate one more than the 4618fe7e86bSDan Gohman // number of blocks in the function to accommodate for the possible fake block 4628fe7e86bSDan Gohman // we may insert at the end. 4638fe7e86bSDan Gohman SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 4648fe7e86bSDan Gohman 4651d68e80fSDan Gohman // For eacn LOOP_END, the corresponding LOOP. 4661d68e80fSDan Gohman DenseMap<const MachineInstr *, const MachineBasicBlock *> LoopTops; 4671d68e80fSDan Gohman 4688fe7e86bSDan Gohman for (auto &MBB : MF) { 4698fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 4701d68e80fSDan Gohman PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 4718fe7e86bSDan Gohman 47232807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 473ed0f1138SDan Gohman PlaceBlockMarker(MBB, MF, ScopeTops, TII, MLI, MDT, MFI); 474950a13cfSDan Gohman } 475950a13cfSDan Gohman 4761d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 4771d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 4781d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 4791d68e80fSDan Gohman for (auto &MI : reverse(MBB)) { 4801d68e80fSDan Gohman switch (MI.getOpcode()) { 4811d68e80fSDan Gohman case WebAssembly::BLOCK: 4821d68e80fSDan Gohman assert(ScopeTops[Stack.back()->getNumber()] == &MBB && 4831d68e80fSDan Gohman "Block should be balanced"); 4841d68e80fSDan Gohman Stack.pop_back(); 4851d68e80fSDan Gohman break; 4861d68e80fSDan Gohman case WebAssembly::LOOP: 4871d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 4881d68e80fSDan Gohman Stack.pop_back(); 4891d68e80fSDan Gohman Stack.pop_back(); 4901d68e80fSDan Gohman break; 4911d68e80fSDan Gohman case WebAssembly::END_BLOCK: 4921d68e80fSDan Gohman Stack.push_back(&MBB); 4931d68e80fSDan Gohman break; 4941d68e80fSDan Gohman case WebAssembly::END_LOOP: 4951d68e80fSDan Gohman Stack.push_back(&MBB); 4961d68e80fSDan Gohman Stack.push_back(LoopTops[&MI]); 4971d68e80fSDan Gohman break; 4981d68e80fSDan Gohman default: 4991d68e80fSDan Gohman if (MI.isTerminator()) { 5001d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 5011d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 5021d68e80fSDan Gohman while (MI.getNumOperands() > 0) 5031d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 5041d68e80fSDan Gohman for (auto MO : Ops) { 5051d68e80fSDan Gohman if (MO.isMBB()) 5061d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 5071d68e80fSDan Gohman MI.addOperand(MF, MO); 50832807932SDan Gohman } 5091d68e80fSDan Gohman } 5101d68e80fSDan Gohman break; 5111d68e80fSDan Gohman } 5121d68e80fSDan Gohman } 5131d68e80fSDan Gohman } 5141d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 5151d68e80fSDan Gohman } 51632807932SDan Gohman 517950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 518950a13cfSDan Gohman DEBUG(dbgs() << "********** CFG Stackifying **********\n" 519950a13cfSDan Gohman "********** Function: " 520950a13cfSDan Gohman << MF.getName() << '\n'); 521950a13cfSDan Gohman 522950a13cfSDan Gohman const auto &MLI = getAnalysis<MachineLoopInfo>(); 52332807932SDan Gohman auto &MDT = getAnalysis<MachineDominatorTree>(); 5249c3bf318SDerek Schuff // Liveness is not tracked for EXPR_STACK physreg. 525950a13cfSDan Gohman const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 526ed0f1138SDan Gohman WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 5279c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 528950a13cfSDan Gohman 529442bfcecSDan Gohman // Sort the blocks, with contiguous loops. 530442bfcecSDan Gohman SortBlocks(MF, MLI, MDT); 531950a13cfSDan Gohman 532950a13cfSDan Gohman // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 533ed0f1138SDan Gohman PlaceMarkers(MF, MLI, TII, MDT, MFI); 53432807932SDan Gohman 535950a13cfSDan Gohman return true; 536950a13cfSDan Gohman } 537