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 115f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass. 12950a13cfSDan Gohman /// 13e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes, 14e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control 15e76fa9ecSHeejin Ahn /// transfers. 16950a13cfSDan Gohman /// 17950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on 18950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry. 19950a13cfSDan Gohman /// 20e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind 21e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format. 22e76fa9ecSHeejin Ahn /// 23950a13cfSDan Gohman //===----------------------------------------------------------------------===// 24950a13cfSDan Gohman 25950a13cfSDan Gohman #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 266bda14b3SChandler Carruth #include "WebAssembly.h" 27e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h" 28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 29950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 304fc4e42dSDan Gohman #include "WebAssemblyUtilities.h" 3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 32950a13cfSDan Gohman #include "llvm/CodeGen/MachineFunction.h" 33950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 34950a13cfSDan Gohman #include "llvm/CodeGen/MachineLoopInfo.h" 359c3bf318SDerek Schuff #include "llvm/CodeGen/MachineRegisterInfo.h" 36950a13cfSDan Gohman #include "llvm/CodeGen/Passes.h" 37e76fa9ecSHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h" 38e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h" 39950a13cfSDan Gohman #include "llvm/Support/Debug.h" 40950a13cfSDan Gohman #include "llvm/Support/raw_ostream.h" 41950a13cfSDan Gohman using namespace llvm; 42950a13cfSDan Gohman 43950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 44950a13cfSDan Gohman 45950a13cfSDan Gohman namespace { 46950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 47117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 48950a13cfSDan Gohman 49950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 5032807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 51950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 52e76fa9ecSHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>(); 53950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 54950a13cfSDan Gohman } 55950a13cfSDan Gohman 56950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 57950a13cfSDan Gohman 58e76fa9ecSHeejin Ahn // For each block whose label represents the end of a scope, record the block 59e76fa9ecSHeejin Ahn // which holds the beginning of the scope. This will allow us to quickly skip 60e76fa9ecSHeejin Ahn // over scoped regions when walking blocks. 61e76fa9ecSHeejin Ahn SmallVector<MachineBasicBlock *, 8> ScopeTops; 62e76fa9ecSHeejin Ahn 63e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF); 64e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB); 65e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB); 66e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB); 67e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF); 68e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF); 69e76fa9ecSHeejin Ahn 70e76fa9ecSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 71e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 72e76fa9ecSHeejin Ahn // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 73e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 74e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map 75e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 76e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map 77e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 78e76fa9ecSHeejin Ahn // <LOOP|TRY marker, Loop/exception bottom BB> map 79e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> BeginToBottom; 80e76fa9ecSHeejin Ahn 81e76fa9ecSHeejin Ahn // Helper functions to register / unregister scope information created by 82e76fa9ecSHeejin Ahn // marker instructions. 83e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End); 84e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End, 85e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad); 86e76fa9ecSHeejin Ahn void unregisterScope(MachineInstr *Begin); 87e76fa9ecSHeejin Ahn 88e76fa9ecSHeejin Ahn MachineBasicBlock *getBottom(const MachineInstr *Begin); 89e76fa9ecSHeejin Ahn 90950a13cfSDan Gohman public: 91950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 92950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 93e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); } 94e76fa9ecSHeejin Ahn void releaseMemory() override; 95950a13cfSDan Gohman }; 96950a13cfSDan Gohman } // end anonymous namespace 97950a13cfSDan Gohman 98950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 9940926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 100*f208f631SHeejin Ahn "Insert BLOCK and LOOP markers for WebAssembly scopes", false, 101*f208f631SHeejin Ahn false) 10240926451SJacob Gravelle 103950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 104950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 105950a13cfSDan Gohman } 106950a13cfSDan Gohman 107b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 108b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 109b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 110b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 111b3aa1ecaSDan Gohman /// explicit mentions. 11235e4a289SDan Gohman static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 11335e4a289SDan Gohman MachineBasicBlock *MBB) { 114b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 115e76fa9ecSHeejin Ahn // Even if a rethrow takes a BB argument, it is not a branch 116e76fa9ecSHeejin Ahn if (!WebAssembly::isRethrow(MI)) 117b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 118b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 119b3aa1ecaSDan Gohman return true; 120b3aa1ecaSDan Gohman return false; 121b3aa1ecaSDan Gohman } 122b3aa1ecaSDan Gohman 123e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB, 124e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 125e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 126e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only 127e76fa9ecSHeejin Ahn // used for sanity checking. 128e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 129e76fa9ecSHeejin Ahn GetEarliestInsertPos(MachineBasicBlock *MBB, 130e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 131e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 132e76fa9ecSHeejin Ahn auto InsertPos = MBB->end(); 133e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) { 134e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) { 135e76fa9ecSHeejin Ahn #ifndef NDEBUG 136e76fa9ecSHeejin Ahn // Sanity check 137e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 138e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos))); 139e76fa9ecSHeejin Ahn #endif 140e76fa9ecSHeejin Ahn break; 141e76fa9ecSHeejin Ahn } 142e76fa9ecSHeejin Ahn --InsertPos; 143e76fa9ecSHeejin Ahn } 144e76fa9ecSHeejin Ahn return InsertPos; 145e76fa9ecSHeejin Ahn } 146e76fa9ecSHeejin Ahn 147e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB, 148e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 149e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 150e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only 151e76fa9ecSHeejin Ahn // used for sanity checking. 152e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 153e76fa9ecSHeejin Ahn GetLatestInsertPos(MachineBasicBlock *MBB, 154e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 155e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 156e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin(); 157e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) { 158e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) { 159e76fa9ecSHeejin Ahn #ifndef NDEBUG 160e76fa9ecSHeejin Ahn // Sanity check 161e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 162e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos)); 163e76fa9ecSHeejin Ahn #endif 164e76fa9ecSHeejin Ahn break; 165e76fa9ecSHeejin Ahn } 166e76fa9ecSHeejin Ahn ++InsertPos; 167e76fa9ecSHeejin Ahn } 168e76fa9ecSHeejin Ahn return InsertPos; 169e76fa9ecSHeejin Ahn } 170e76fa9ecSHeejin Ahn 171e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 172e76fa9ecSHeejin Ahn MachineInstr *End) { 173e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End; 174e76fa9ecSHeejin Ahn EndToBegin[End] = Begin; 175e76fa9ecSHeejin Ahn } 176e76fa9ecSHeejin Ahn 177e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 178e76fa9ecSHeejin Ahn MachineInstr *End, 179e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) { 180e76fa9ecSHeejin Ahn registerScope(Begin, End); 181e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad; 182e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin; 183e76fa9ecSHeejin Ahn } 184e76fa9ecSHeejin Ahn 185e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 186e76fa9ecSHeejin Ahn assert(BeginToEnd.count(Begin)); 187e76fa9ecSHeejin Ahn MachineInstr *End = BeginToEnd[Begin]; 188e76fa9ecSHeejin Ahn assert(EndToBegin.count(End)); 189e76fa9ecSHeejin Ahn BeginToEnd.erase(Begin); 190e76fa9ecSHeejin Ahn EndToBegin.erase(End); 191e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 192e76fa9ecSHeejin Ahn if (EHPad) { 193e76fa9ecSHeejin Ahn assert(EHPadToTry.count(EHPad)); 194e76fa9ecSHeejin Ahn TryToEHPad.erase(Begin); 195e76fa9ecSHeejin Ahn EHPadToTry.erase(EHPad); 196e76fa9ecSHeejin Ahn } 197e76fa9ecSHeejin Ahn MachineBasicBlock *Bottom = BeginToBottom.lookup(Begin); 198e76fa9ecSHeejin Ahn if (Bottom) 199e76fa9ecSHeejin Ahn BeginToBottom.erase(Begin); 200e76fa9ecSHeejin Ahn } 201e76fa9ecSHeejin Ahn 202e76fa9ecSHeejin Ahn // Given a LOOP/TRY marker, returns its bottom BB. Use cached information if any 203e76fa9ecSHeejin Ahn // to prevent recomputation. 204e76fa9ecSHeejin Ahn MachineBasicBlock * 205e76fa9ecSHeejin Ahn WebAssemblyCFGStackify::getBottom(const MachineInstr *Begin) { 206e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 207e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 208e76fa9ecSHeejin Ahn if (BeginToBottom.count(Begin)) 209e76fa9ecSHeejin Ahn return BeginToBottom[Begin]; 210e76fa9ecSHeejin Ahn if (Begin->getOpcode() == WebAssembly::LOOP) { 211e76fa9ecSHeejin Ahn MachineLoop *L = MLI.getLoopFor(Begin->getParent()); 212e76fa9ecSHeejin Ahn assert(L); 213e76fa9ecSHeejin Ahn BeginToBottom[Begin] = WebAssembly::getBottom(L); 214e76fa9ecSHeejin Ahn } else if (Begin->getOpcode() == WebAssembly::TRY) { 215e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(TryToEHPad[Begin]); 216e76fa9ecSHeejin Ahn assert(WE); 217e76fa9ecSHeejin Ahn BeginToBottom[Begin] = WebAssembly::getBottom(WE); 218e76fa9ecSHeejin Ahn } else 219e76fa9ecSHeejin Ahn assert(false); 220e76fa9ecSHeejin Ahn return BeginToBottom[Begin]; 221e76fa9ecSHeejin Ahn } 222e76fa9ecSHeejin Ahn 22332807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 224e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 225e76fa9ecSHeejin Ahn // This should have been handled in placeTryMarker. 226e76fa9ecSHeejin Ahn if (MBB.isEHPad()) 227e76fa9ecSHeejin Ahn return; 228e76fa9ecSHeejin Ahn 229e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 230e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 231e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 232e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 233e76fa9ecSHeejin Ahn 2348fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2358fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2368fe7e86bSDan Gohman // which reduces overall stack height. 23732807932SDan Gohman MachineBasicBlock *Header = nullptr; 23832807932SDan Gohman bool IsBranchedTo = false; 23932807932SDan Gohman int MBBNumber = MBB.getNumber(); 240e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) { 24132807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 24232807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 243b3aa1ecaSDan Gohman if (ExplicitlyBranchesTo(Pred, &MBB)) 24432807932SDan Gohman IsBranchedTo = true; 24532807932SDan Gohman } 246e76fa9ecSHeejin Ahn } 24732807932SDan Gohman if (!Header) 24832807932SDan Gohman return; 24932807932SDan Gohman if (!IsBranchedTo) 25032807932SDan Gohman return; 25132807932SDan Gohman 2528fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 253ef0a45aaSBenjamin Kramer MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB)); 2548fe7e86bSDan Gohman 2558fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2568fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2578fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2588fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2598fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2608fe7e86bSDan Gohman // Skip over an intervening scope. 261ef0a45aaSBenjamin Kramer I = std::next(MachineFunction::iterator(ScopeTop)); 2628fe7e86bSDan Gohman } else { 2638fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 2648fe7e86bSDan Gohman Header = ScopeTop; 2658fe7e86bSDan Gohman break; 2668fe7e86bSDan Gohman } 2678fe7e86bSDan Gohman } 2688fe7e86bSDan Gohman } 2698fe7e86bSDan Gohman 2708fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 271e76fa9ecSHeejin Ahn 272e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 273e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 274e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 275e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 276e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 277e76fa9ecSHeejin Ahn // If there is a previously placed LOOP/TRY marker and the bottom block of 278e76fa9ecSHeejin Ahn // the loop/exception is above MBB, it should be after the BLOCK, because 279e76fa9ecSHeejin Ahn // the loop/exception is nested in this block. Otherwise it should be before 280e76fa9ecSHeejin Ahn // the BLOCK. 281e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 282e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) { 283e76fa9ecSHeejin Ahn if (MBB.getNumber() > getBottom(&MI)->getNumber()) 284e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 285e76fa9ecSHeejin Ahn #ifndef NDEBUG 286e76fa9ecSHeejin Ahn else 287e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 288e76fa9ecSHeejin Ahn #endif 289e76fa9ecSHeejin Ahn } 290e76fa9ecSHeejin Ahn 291e76fa9ecSHeejin Ahn // All previously inserted BLOCK markers should be after the BLOCK because 292e76fa9ecSHeejin Ahn // they are all nested blocks. 293e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK) 294e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 295e76fa9ecSHeejin Ahn 296e76fa9ecSHeejin Ahn #ifndef NDEBUG 297e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 298e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 299e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 300e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 301e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 302e76fa9ecSHeejin Ahn #endif 303e76fa9ecSHeejin Ahn 304e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK. 305e76fa9ecSHeejin Ahn if (MI.isTerminator()) 306e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 307e76fa9ecSHeejin Ahn } 308e76fa9ecSHeejin Ahn 309e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK. 310e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 311e76fa9ecSHeejin Ahn --I) { 312e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 313e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 314e76fa9ecSHeejin Ahn else 315e76fa9ecSHeejin Ahn break; 31632807932SDan Gohman } 31732807932SDan Gohman 3188fe7e86bSDan Gohman // Add the BLOCK. 319e76fa9ecSHeejin Ahn auto InsertPos = GetLatestInsertPos(Header, BeforeSet, AfterSet); 32092401cc1SHeejin Ahn MachineInstr *Begin = 32192401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3222726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 3234fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 3241d68e80fSDan Gohman 325e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 326e76fa9ecSHeejin Ahn BeforeSet.clear(); 327e76fa9ecSHeejin Ahn AfterSet.clear(); 328e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 329e76fa9ecSHeejin Ahn #ifndef NDEBUG 330e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 331e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 332e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 333e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 334e76fa9ecSHeejin Ahn #endif 335e76fa9ecSHeejin Ahn 336e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 337e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 338e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 339e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 340e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 341e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 342e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 343e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 344e76fa9ecSHeejin Ahn #ifndef NDEBUG 345e76fa9ecSHeejin Ahn else 346e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 347e76fa9ecSHeejin Ahn #endif 348e76fa9ecSHeejin Ahn } 349e76fa9ecSHeejin Ahn } 350e76fa9ecSHeejin Ahn 3511d68e80fSDan Gohman // Mark the end of the block. 352e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(&MBB, BeforeSet, AfterSet); 35310b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3542726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 355e76fa9ecSHeejin Ahn registerScope(Begin, End); 3568fe7e86bSDan Gohman 3578fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3588fe7e86bSDan Gohman int Number = MBB.getNumber(); 3598fe7e86bSDan Gohman if (!ScopeTops[Number] || 3608fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3618fe7e86bSDan Gohman ScopeTops[Number] = Header; 362950a13cfSDan Gohman } 363950a13cfSDan Gohman 3648fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 365e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 366e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 367e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 368e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 369e76fa9ecSHeejin Ahn 3708fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3718fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3728fe7e86bSDan Gohman return; 3738fe7e86bSDan Gohman 3748fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3758fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 376817811caSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 377ef0a45aaSBenjamin Kramer auto Iter = std::next(MachineFunction::iterator(Bottom)); 378e3e4a5ffSDan Gohman if (Iter == MF.end()) { 379f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 380f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 381f6857223SDan Gohman Label->addSuccessor(Label); 382f6857223SDan Gohman MF.push_back(Label); 383ef0a45aaSBenjamin Kramer Iter = std::next(MachineFunction::iterator(Bottom)); 384e3e4a5ffSDan Gohman } 3858fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 386f6857223SDan Gohman 387e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 388e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 389e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 390e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 391e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 392e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 393e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 394e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 395e76fa9ecSHeejin Ahn #ifndef NDEBUG 396e76fa9ecSHeejin Ahn else 397e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 398e76fa9ecSHeejin Ahn #endif 399e76fa9ecSHeejin Ahn } 400e76fa9ecSHeejin Ahn 401e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 402e76fa9ecSHeejin Ahn auto InsertPos = GetEarliestInsertPos(&MBB, BeforeSet, AfterSet); 40310b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4042726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4054fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 4061d68e80fSDan Gohman 407e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 408e76fa9ecSHeejin Ahn BeforeSet.clear(); 409e76fa9ecSHeejin Ahn AfterSet.clear(); 410e76fa9ecSHeejin Ahn #ifndef NDEBUG 411e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 412e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 413e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 414e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 415e76fa9ecSHeejin Ahn #endif 416e76fa9ecSHeejin Ahn 417e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 418e76fa9ecSHeejin Ahn // the loop end as its location). 419e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 42010b31358SDerek Schuff DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 421e76fa9ecSHeejin Ahn MachineInstr *End = 422e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 423e76fa9ecSHeejin Ahn registerScope(Begin, End); 4248fe7e86bSDan Gohman 4258fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4268fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 427442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4288fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4298fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 430e3e4a5ffSDan Gohman } 431950a13cfSDan Gohman 432e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 433e76fa9ecSHeejin Ahn if (!MBB.isEHPad()) 434e76fa9ecSHeejin Ahn return; 435e76fa9ecSHeejin Ahn 436e76fa9ecSHeejin Ahn // catch_all terminate pad is grouped together with catch terminate pad and 437e76fa9ecSHeejin Ahn // does not need a separate TRY and END_TRY marker. 438e76fa9ecSHeejin Ahn if (WebAssembly::isCatchAllTerminatePad(MBB)) 439e76fa9ecSHeejin Ahn return; 440e76fa9ecSHeejin Ahn 441e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 442e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 443e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 444e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 445e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 446e76fa9ecSHeejin Ahn 447e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 448e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 449e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 450e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 451e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 452e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 453e76fa9ecSHeejin Ahn assert(!ExplicitlyBranchesTo(Pred, &MBB) && 454e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 455e76fa9ecSHeejin Ahn } 456e76fa9ecSHeejin Ahn } 457e76fa9ecSHeejin Ahn if (!Header) 458e76fa9ecSHeejin Ahn return; 459e76fa9ecSHeejin Ahn 460e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 461e76fa9ecSHeejin Ahn // end. 462e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 463e76fa9ecSHeejin Ahn assert(WE); 464e76fa9ecSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 465e76fa9ecSHeejin Ahn 466e76fa9ecSHeejin Ahn auto Iter = std::next(MachineFunction::iterator(Bottom)); 467e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 468e76fa9ecSHeejin Ahn MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 469e76fa9ecSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 470e76fa9ecSHeejin Ahn Label->addSuccessor(Label); 471e76fa9ecSHeejin Ahn MF.push_back(Label); 472e76fa9ecSHeejin Ahn Iter = std::next(MachineFunction::iterator(Bottom)); 473e76fa9ecSHeejin Ahn } 474e76fa9ecSHeejin Ahn MachineBasicBlock *AfterTry = &*Iter; 475e76fa9ecSHeejin Ahn 476e76fa9ecSHeejin Ahn assert(AfterTry != &MF.front()); 477e76fa9ecSHeejin Ahn MachineBasicBlock *LayoutPred = 478e76fa9ecSHeejin Ahn &*std::prev(MachineFunction::iterator(AfterTry)); 479e76fa9ecSHeejin Ahn 480e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 481e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 482e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 483e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 484e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 485e76fa9ecSHeejin Ahn // Skip over an intervening scope. 486e76fa9ecSHeejin Ahn I = std::next(MachineFunction::iterator(ScopeTop)); 487e76fa9ecSHeejin Ahn } else { 488e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 489e76fa9ecSHeejin Ahn Header = ScopeTop; 490e76fa9ecSHeejin Ahn break; 491e76fa9ecSHeejin Ahn } 492e76fa9ecSHeejin Ahn } 493e76fa9ecSHeejin Ahn } 494e76fa9ecSHeejin Ahn 495e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 496e76fa9ecSHeejin Ahn 497e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 498e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 499e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 500e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 501e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 502e76fa9ecSHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of 503e76fa9ecSHeejin Ahn // the loop is above MBB, the LOOP should be after the TRY, because the 504e76fa9ecSHeejin Ahn // loop is nested in this try. Otherwise it should be before the TRY. 505e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 506e76fa9ecSHeejin Ahn if (MBB.getNumber() > Bottom->getNumber()) 507e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 508e76fa9ecSHeejin Ahn #ifndef NDEBUG 509e76fa9ecSHeejin Ahn else 510e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 511e76fa9ecSHeejin Ahn #endif 512e76fa9ecSHeejin Ahn } 513e76fa9ecSHeejin Ahn 514e76fa9ecSHeejin Ahn // All previously inserted TRY markers should be after the TRY because they 515e76fa9ecSHeejin Ahn // are all nested trys. 516e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 517e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 518e76fa9ecSHeejin Ahn 519e76fa9ecSHeejin Ahn #ifndef NDEBUG 520e76fa9ecSHeejin Ahn // All END_(LOOP/TRY) markers should be before the TRY. 521e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 522e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 523e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 524e76fa9ecSHeejin Ahn #endif 525e76fa9ecSHeejin Ahn 526e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 527e76fa9ecSHeejin Ahn if (MI.isTerminator()) 528e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 529e76fa9ecSHeejin Ahn } 530e76fa9ecSHeejin Ahn 531e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 532e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 533e76fa9ecSHeejin Ahn --I) { 534e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 535e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 536e76fa9ecSHeejin Ahn else 537e76fa9ecSHeejin Ahn break; 538e76fa9ecSHeejin Ahn } 539e76fa9ecSHeejin Ahn 540e76fa9ecSHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 541e76fa9ecSHeejin Ahn // contain the call within it. So the call should go after the TRY. The 542e76fa9ecSHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 543e76fa9ecSHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 544e76fa9ecSHeejin Ahn // throw. 545e76fa9ecSHeejin Ahn if (MBB.isPredecessor(Header)) { 546e76fa9ecSHeejin Ahn auto TermPos = Header->getFirstTerminator(); 547e76fa9ecSHeejin Ahn if (TermPos == Header->end() || !WebAssembly::isRethrow(*TermPos)) { 548e76fa9ecSHeejin Ahn for (const auto &MI : reverse(*Header)) { 549e76fa9ecSHeejin Ahn if (MI.isCall()) { 550e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 551e76fa9ecSHeejin Ahn break; 552e76fa9ecSHeejin Ahn } 553e76fa9ecSHeejin Ahn } 554e76fa9ecSHeejin Ahn } 555e76fa9ecSHeejin Ahn } 556e76fa9ecSHeejin Ahn 557e76fa9ecSHeejin Ahn // Add the TRY. 558e76fa9ecSHeejin Ahn auto InsertPos = GetLatestInsertPos(Header, BeforeSet, AfterSet); 559e76fa9ecSHeejin Ahn MachineInstr *Begin = 560e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 561e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 562e76fa9ecSHeejin Ahn .addImm(int64_t(WebAssembly::ExprType::Void)); 563e76fa9ecSHeejin Ahn 564e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 565e76fa9ecSHeejin Ahn BeforeSet.clear(); 566e76fa9ecSHeejin Ahn AfterSet.clear(); 567e76fa9ecSHeejin Ahn for (const auto &MI : *AfterTry) { 568e76fa9ecSHeejin Ahn #ifndef NDEBUG 569e76fa9ecSHeejin Ahn // END_TRY should precede existing LOOP markers. 570e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) 571e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 572e76fa9ecSHeejin Ahn 573e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 574e76fa9ecSHeejin Ahn // this one. 575e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 576e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 577e76fa9ecSHeejin Ahn #endif 578e76fa9ecSHeejin Ahn 579e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 580e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 581e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 582e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 583e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 584e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 585e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 586e76fa9ecSHeejin Ahn #ifndef NDEBUG 587e76fa9ecSHeejin Ahn else 588e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 589e76fa9ecSHeejin Ahn #endif 590e76fa9ecSHeejin Ahn } 591e76fa9ecSHeejin Ahn } 592e76fa9ecSHeejin Ahn 593e76fa9ecSHeejin Ahn // Mark the end of the TRY. 594e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(AfterTry, BeforeSet, AfterSet); 595e76fa9ecSHeejin Ahn MachineInstr *End = 596e76fa9ecSHeejin Ahn BuildMI(*AfterTry, InsertPos, Bottom->findBranchDebugLoc(), 597e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 598e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 599e76fa9ecSHeejin Ahn 600e76fa9ecSHeejin Ahn // Track the farthest-spanning scope that ends at this point. 601e76fa9ecSHeejin Ahn int Number = AfterTry->getNumber(); 602e76fa9ecSHeejin Ahn if (!ScopeTops[Number] || 603e76fa9ecSHeejin Ahn ScopeTops[Number]->getNumber() > Header->getNumber()) 604e76fa9ecSHeejin Ahn ScopeTops[Number] = Header; 605e76fa9ecSHeejin Ahn } 606e76fa9ecSHeejin Ahn 6071d68e80fSDan Gohman static unsigned 6081d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 6091d68e80fSDan Gohman const MachineBasicBlock *MBB) { 6101d68e80fSDan Gohman unsigned Depth = 0; 6111d68e80fSDan Gohman for (auto X : reverse(Stack)) { 6121d68e80fSDan Gohman if (X == MBB) 6131d68e80fSDan Gohman break; 6141d68e80fSDan Gohman ++Depth; 6151d68e80fSDan Gohman } 6161d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 6171d68e80fSDan Gohman return Depth; 6181d68e80fSDan Gohman } 6191d68e80fSDan Gohman 6202726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 6212726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 6222726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 6232726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 6242726b88cSDan Gohman /// that end at the function end need to have a return type signature that 6252726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 6262726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 627e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 628e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 6292726b88cSDan Gohman assert(MFI.getResults().size() <= 1); 6302726b88cSDan Gohman 6312726b88cSDan Gohman if (MFI.getResults().empty()) 6322726b88cSDan Gohman return; 6332726b88cSDan Gohman 6342726b88cSDan Gohman WebAssembly::ExprType retType; 6352726b88cSDan Gohman switch (MFI.getResults().front().SimpleTy) { 636*f208f631SHeejin Ahn case MVT::i32: 637*f208f631SHeejin Ahn retType = WebAssembly::ExprType::I32; 638*f208f631SHeejin Ahn break; 639*f208f631SHeejin Ahn case MVT::i64: 640*f208f631SHeejin Ahn retType = WebAssembly::ExprType::I64; 641*f208f631SHeejin Ahn break; 642*f208f631SHeejin Ahn case MVT::f32: 643*f208f631SHeejin Ahn retType = WebAssembly::ExprType::F32; 644*f208f631SHeejin Ahn break; 645*f208f631SHeejin Ahn case MVT::f64: 646*f208f631SHeejin Ahn retType = WebAssembly::ExprType::F64; 647*f208f631SHeejin Ahn break; 6482c783859SDerek Schuff case MVT::v16i8: 6492c783859SDerek Schuff case MVT::v8i16: 6502c783859SDerek Schuff case MVT::v4i32: 65151ed131eSDerek Schuff case MVT::v2i64: 6522c783859SDerek Schuff case MVT::v4f32: 65351ed131eSDerek Schuff case MVT::v2f64: 6542c783859SDerek Schuff retType = WebAssembly::ExprType::V128; 6552c783859SDerek Schuff break; 656*f208f631SHeejin Ahn case MVT::ExceptRef: 657*f208f631SHeejin Ahn retType = WebAssembly::ExprType::ExceptRef; 658*f208f631SHeejin Ahn break; 659*f208f631SHeejin Ahn default: 660*f208f631SHeejin Ahn llvm_unreachable("unexpected return type"); 6612726b88cSDan Gohman } 6622726b88cSDan Gohman 6632726b88cSDan Gohman for (MachineBasicBlock &MBB : reverse(MF)) { 6642726b88cSDan Gohman for (MachineInstr &MI : reverse(MBB)) { 665801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 6662726b88cSDan Gohman continue; 6672726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_BLOCK) { 668e76fa9ecSHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(retType)); 6692726b88cSDan Gohman continue; 6702726b88cSDan Gohman } 6712726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_LOOP) { 672e76fa9ecSHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(retType)); 6732726b88cSDan Gohman continue; 6742726b88cSDan Gohman } 6752726b88cSDan Gohman // Something other than an `end`. We're done. 6762726b88cSDan Gohman return; 6772726b88cSDan Gohman } 6782726b88cSDan Gohman } 6792726b88cSDan Gohman } 6802726b88cSDan Gohman 681d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 682d934cb88SDan Gohman // were a block. 683*f208f631SHeejin Ahn static void AppendEndToFunction(MachineFunction &MF, 684d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 68510b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 68610b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 687d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 688d934cb88SDan Gohman } 689d934cb88SDan Gohman 690e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 691e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 692e76fa9ecSHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 693e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 694e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 695e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 6968fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 697e76fa9ecSHeejin Ahn for (auto &MBB : MF) 698e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 699e76fa9ecSHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 700e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 701e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 702e76fa9ecSHeejin Ahn for (auto &MBB : MF) 703e76fa9ecSHeejin Ahn placeTryMarker(MBB); 70432807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 705e76fa9ecSHeejin Ahn for (auto &MBB : MF) 706e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 707950a13cfSDan Gohman } 708950a13cfSDan Gohman 709e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 710e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 7111d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 712e76fa9ecSHeejin Ahn // We need two stacks: one for normal scopes and the other for EH pad scopes. 713e76fa9ecSHeejin Ahn // EH pad stack is used to rewrite depths in rethrow instructions. 7141d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 715e76fa9ecSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 7161d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 717e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 718e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 7191d68e80fSDan Gohman switch (MI.getOpcode()) { 7201d68e80fSDan Gohman case WebAssembly::BLOCK: 721e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 722e76fa9ecSHeejin Ahn MBB.getNumber() && 723e76fa9ecSHeejin Ahn "Block/try should be balanced"); 7241d68e80fSDan Gohman Stack.pop_back(); 7251d68e80fSDan Gohman break; 726e76fa9ecSHeejin Ahn 727e76fa9ecSHeejin Ahn case WebAssembly::TRY: 728e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 729e76fa9ecSHeejin Ahn MBB.getNumber() && 730e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 731e76fa9ecSHeejin Ahn Stack.pop_back(); 732e76fa9ecSHeejin Ahn EHPadStack.pop_back(); 733e76fa9ecSHeejin Ahn break; 734e76fa9ecSHeejin Ahn 735e76fa9ecSHeejin Ahn case WebAssembly::CATCH_I32: 736e76fa9ecSHeejin Ahn case WebAssembly::CATCH_I64: 737e76fa9ecSHeejin Ahn case WebAssembly::CATCH_ALL: 738e76fa9ecSHeejin Ahn EHPadStack.push_back(&MBB); 739e76fa9ecSHeejin Ahn break; 740e76fa9ecSHeejin Ahn 7411d68e80fSDan Gohman case WebAssembly::LOOP: 7421d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 7431d68e80fSDan Gohman Stack.pop_back(); 7441d68e80fSDan Gohman break; 745e76fa9ecSHeejin Ahn 7461d68e80fSDan Gohman case WebAssembly::END_BLOCK: 747e76fa9ecSHeejin Ahn case WebAssembly::END_TRY: 7481d68e80fSDan Gohman Stack.push_back(&MBB); 7491d68e80fSDan Gohman break; 750e76fa9ecSHeejin Ahn 7511d68e80fSDan Gohman case WebAssembly::END_LOOP: 752e76fa9ecSHeejin Ahn Stack.push_back(EndToBegin[&MI]->getParent()); 7531d68e80fSDan Gohman break; 754e76fa9ecSHeejin Ahn 755e76fa9ecSHeejin Ahn case WebAssembly::RETHROW: { 756e76fa9ecSHeejin Ahn // Rewrite MBB operands to be depth immediates. 757e76fa9ecSHeejin Ahn unsigned EHPadDepth = GetDepth(EHPadStack, MI.getOperand(0).getMBB()); 758e76fa9ecSHeejin Ahn MI.RemoveOperand(0); 759e76fa9ecSHeejin Ahn MI.addOperand(MF, MachineOperand::CreateImm(EHPadDepth)); 760e76fa9ecSHeejin Ahn break; 761e76fa9ecSHeejin Ahn } 762e76fa9ecSHeejin Ahn 763e76fa9ecSHeejin Ahn case WebAssembly::RETHROW_TO_CALLER: { 764e76fa9ecSHeejin Ahn MachineInstr *Rethrow = 765e76fa9ecSHeejin Ahn BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(WebAssembly::RETHROW)) 766e76fa9ecSHeejin Ahn .addImm(Stack.size()); 767e76fa9ecSHeejin Ahn MI.eraseFromParent(); 768e76fa9ecSHeejin Ahn I = MachineBasicBlock::reverse_iterator(Rethrow); 769e76fa9ecSHeejin Ahn break; 770e76fa9ecSHeejin Ahn } 771e76fa9ecSHeejin Ahn 7721d68e80fSDan Gohman default: 7731d68e80fSDan Gohman if (MI.isTerminator()) { 7741d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 7751d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 7761d68e80fSDan Gohman while (MI.getNumOperands() > 0) 7771d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 7781d68e80fSDan Gohman for (auto MO : Ops) { 7791d68e80fSDan Gohman if (MO.isMBB()) 7801d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 7811d68e80fSDan Gohman MI.addOperand(MF, MO); 78232807932SDan Gohman } 7831d68e80fSDan Gohman } 7841d68e80fSDan Gohman break; 7851d68e80fSDan Gohman } 7861d68e80fSDan Gohman } 7871d68e80fSDan Gohman } 7881d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 789e76fa9ecSHeejin Ahn } 7902726b88cSDan Gohman 791e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 792e76fa9ecSHeejin Ahn ScopeTops.clear(); 793e76fa9ecSHeejin Ahn BeginToEnd.clear(); 794e76fa9ecSHeejin Ahn EndToBegin.clear(); 795e76fa9ecSHeejin Ahn TryToEHPad.clear(); 796e76fa9ecSHeejin Ahn EHPadToTry.clear(); 797e76fa9ecSHeejin Ahn BeginToBottom.clear(); 7981d68e80fSDan Gohman } 79932807932SDan Gohman 800950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 801d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 802950a13cfSDan Gohman "********** Function: " 803950a13cfSDan Gohman << MF.getName() << '\n'); 804950a13cfSDan Gohman 805e76fa9ecSHeejin Ahn releaseMemory(); 806e76fa9ecSHeejin Ahn 807e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 8089c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 809950a13cfSDan Gohman 810e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 811e76fa9ecSHeejin Ahn placeMarkers(MF); 812e76fa9ecSHeejin Ahn 813e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 814e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 815e76fa9ecSHeejin Ahn 816e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 817e76fa9ecSHeejin Ahn // WebAssembly's rules. 818e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 819e76fa9ecSHeejin Ahn 820e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 821e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 822e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 823e76fa9ecSHeejin Ahn .getTargetTriple() 824e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 825e76fa9ecSHeejin Ahn AppendEndToFunction(MF, TII); 82632807932SDan Gohman 827950a13cfSDan Gohman return true; 828950a13cfSDan Gohman } 829