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, 100f208f631SHeejin Ahn "Insert BLOCK and LOOP markers for WebAssembly scopes", false, 101f208f631SHeejin 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) { 312409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 313409b4391SYury Delendik continue; 314e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 315e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 316e76fa9ecSHeejin Ahn else 317e76fa9ecSHeejin Ahn break; 31832807932SDan Gohman } 31932807932SDan Gohman 3208fe7e86bSDan Gohman // Add the BLOCK. 321e76fa9ecSHeejin Ahn auto InsertPos = GetLatestInsertPos(Header, BeforeSet, AfterSet); 32292401cc1SHeejin Ahn MachineInstr *Begin = 32392401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3242726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 3254fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 3261d68e80fSDan Gohman 327e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 328e76fa9ecSHeejin Ahn BeforeSet.clear(); 329e76fa9ecSHeejin Ahn AfterSet.clear(); 330e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 331e76fa9ecSHeejin Ahn #ifndef NDEBUG 332e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 333e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 334e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 335e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 336e76fa9ecSHeejin Ahn #endif 337e76fa9ecSHeejin Ahn 338e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 339e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 340e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 341e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 342e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 343e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 344e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 345e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 346e76fa9ecSHeejin Ahn #ifndef NDEBUG 347e76fa9ecSHeejin Ahn else 348e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 349e76fa9ecSHeejin Ahn #endif 350e76fa9ecSHeejin Ahn } 351e76fa9ecSHeejin Ahn } 352e76fa9ecSHeejin Ahn 3531d68e80fSDan Gohman // Mark the end of the block. 354e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(&MBB, BeforeSet, AfterSet); 35510b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3562726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 357e76fa9ecSHeejin Ahn registerScope(Begin, End); 3588fe7e86bSDan Gohman 3598fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3608fe7e86bSDan Gohman int Number = MBB.getNumber(); 3618fe7e86bSDan Gohman if (!ScopeTops[Number] || 3628fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3638fe7e86bSDan Gohman ScopeTops[Number] = Header; 364950a13cfSDan Gohman } 365950a13cfSDan Gohman 3668fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 367e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 368e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 369e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 370e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 371e76fa9ecSHeejin Ahn 3728fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3738fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3748fe7e86bSDan Gohman return; 3758fe7e86bSDan Gohman 3768fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3778fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 378817811caSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 379ef0a45aaSBenjamin Kramer auto Iter = std::next(MachineFunction::iterator(Bottom)); 380e3e4a5ffSDan Gohman if (Iter == MF.end()) { 381f6857223SDan Gohman MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 382f6857223SDan Gohman // Give it a fake predecessor so that AsmPrinter prints its label. 383f6857223SDan Gohman Label->addSuccessor(Label); 384f6857223SDan Gohman MF.push_back(Label); 385ef0a45aaSBenjamin Kramer Iter = std::next(MachineFunction::iterator(Bottom)); 386e3e4a5ffSDan Gohman } 3878fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 388f6857223SDan Gohman 389e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 390e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 391e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 392e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 393e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 394e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 395e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 396e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 397e76fa9ecSHeejin Ahn #ifndef NDEBUG 398e76fa9ecSHeejin Ahn else 399e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 400e76fa9ecSHeejin Ahn #endif 401e76fa9ecSHeejin Ahn } 402e76fa9ecSHeejin Ahn 403e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 404e76fa9ecSHeejin Ahn auto InsertPos = GetEarliestInsertPos(&MBB, BeforeSet, AfterSet); 40510b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4062726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4074fc4e42dSDan Gohman .addImm(int64_t(WebAssembly::ExprType::Void)); 4081d68e80fSDan Gohman 409e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 410e76fa9ecSHeejin Ahn BeforeSet.clear(); 411e76fa9ecSHeejin Ahn AfterSet.clear(); 412e76fa9ecSHeejin Ahn #ifndef NDEBUG 413e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 414e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 415e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 416e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 417e76fa9ecSHeejin Ahn #endif 418e76fa9ecSHeejin Ahn 419e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 420e76fa9ecSHeejin Ahn // the loop end as its location). 421e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 42210b31358SDerek Schuff DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 423e76fa9ecSHeejin Ahn MachineInstr *End = 424e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 425e76fa9ecSHeejin Ahn registerScope(Begin, End); 4268fe7e86bSDan Gohman 4278fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4288fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 429442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4308fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4318fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 432e3e4a5ffSDan Gohman } 433950a13cfSDan Gohman 434e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 435e76fa9ecSHeejin Ahn if (!MBB.isEHPad()) 436e76fa9ecSHeejin Ahn return; 437e76fa9ecSHeejin Ahn 438e76fa9ecSHeejin Ahn // catch_all terminate pad is grouped together with catch terminate pad and 439e76fa9ecSHeejin Ahn // does not need a separate TRY and END_TRY marker. 440e76fa9ecSHeejin Ahn if (WebAssembly::isCatchAllTerminatePad(MBB)) 441e76fa9ecSHeejin Ahn return; 442e76fa9ecSHeejin Ahn 443e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 444e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 445e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 446e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 447e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 448e76fa9ecSHeejin Ahn 449e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 450e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 451e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 452e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 453e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 454e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 455e76fa9ecSHeejin Ahn assert(!ExplicitlyBranchesTo(Pred, &MBB) && 456e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 457e76fa9ecSHeejin Ahn } 458e76fa9ecSHeejin Ahn } 459e76fa9ecSHeejin Ahn if (!Header) 460e76fa9ecSHeejin Ahn return; 461e76fa9ecSHeejin Ahn 462e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 463e76fa9ecSHeejin Ahn // end. 464e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 465e76fa9ecSHeejin Ahn assert(WE); 466e76fa9ecSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 467e76fa9ecSHeejin Ahn 468e76fa9ecSHeejin Ahn auto Iter = std::next(MachineFunction::iterator(Bottom)); 469e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 470e76fa9ecSHeejin Ahn MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 471e76fa9ecSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 472e76fa9ecSHeejin Ahn Label->addSuccessor(Label); 473e76fa9ecSHeejin Ahn MF.push_back(Label); 474e76fa9ecSHeejin Ahn Iter = std::next(MachineFunction::iterator(Bottom)); 475e76fa9ecSHeejin Ahn } 476e76fa9ecSHeejin Ahn MachineBasicBlock *AfterTry = &*Iter; 477e76fa9ecSHeejin Ahn 478e76fa9ecSHeejin Ahn assert(AfterTry != &MF.front()); 479e76fa9ecSHeejin Ahn MachineBasicBlock *LayoutPred = 480e76fa9ecSHeejin Ahn &*std::prev(MachineFunction::iterator(AfterTry)); 481e76fa9ecSHeejin Ahn 482e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 483e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 484e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 485e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 486e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 487e76fa9ecSHeejin Ahn // Skip over an intervening scope. 488e76fa9ecSHeejin Ahn I = std::next(MachineFunction::iterator(ScopeTop)); 489e76fa9ecSHeejin Ahn } else { 490e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 491e76fa9ecSHeejin Ahn Header = ScopeTop; 492e76fa9ecSHeejin Ahn break; 493e76fa9ecSHeejin Ahn } 494e76fa9ecSHeejin Ahn } 495e76fa9ecSHeejin Ahn } 496e76fa9ecSHeejin Ahn 497e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 498e76fa9ecSHeejin Ahn 499e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 500e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 501e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 502e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 503e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 504e76fa9ecSHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of 505e76fa9ecSHeejin Ahn // the loop is above MBB, the LOOP should be after the TRY, because the 506e76fa9ecSHeejin Ahn // loop is nested in this try. Otherwise it should be before the TRY. 507e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 508e76fa9ecSHeejin Ahn if (MBB.getNumber() > Bottom->getNumber()) 509e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 510e76fa9ecSHeejin Ahn #ifndef NDEBUG 511e76fa9ecSHeejin Ahn else 512e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 513e76fa9ecSHeejin Ahn #endif 514e76fa9ecSHeejin Ahn } 515e76fa9ecSHeejin Ahn 516e76fa9ecSHeejin Ahn // All previously inserted TRY markers should be after the TRY because they 517e76fa9ecSHeejin Ahn // are all nested trys. 518e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 519e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 520e76fa9ecSHeejin Ahn 521e76fa9ecSHeejin Ahn #ifndef NDEBUG 522e76fa9ecSHeejin Ahn // All END_(LOOP/TRY) markers should be before the TRY. 523e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 524e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 525e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 526e76fa9ecSHeejin Ahn #endif 527e76fa9ecSHeejin Ahn 528e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 529e76fa9ecSHeejin Ahn if (MI.isTerminator()) 530e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 531e76fa9ecSHeejin Ahn } 532e76fa9ecSHeejin Ahn 533e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 534e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 535e76fa9ecSHeejin Ahn --I) { 536409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 537409b4391SYury Delendik continue; 538e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 539e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 540e76fa9ecSHeejin Ahn else 541e76fa9ecSHeejin Ahn break; 542e76fa9ecSHeejin Ahn } 543e76fa9ecSHeejin Ahn 544e76fa9ecSHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 545e76fa9ecSHeejin Ahn // contain the call within it. So the call should go after the TRY. The 546e76fa9ecSHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 547e76fa9ecSHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 548e76fa9ecSHeejin Ahn // throw. 549e76fa9ecSHeejin Ahn if (MBB.isPredecessor(Header)) { 550e76fa9ecSHeejin Ahn auto TermPos = Header->getFirstTerminator(); 551e76fa9ecSHeejin Ahn if (TermPos == Header->end() || !WebAssembly::isRethrow(*TermPos)) { 552e76fa9ecSHeejin Ahn for (const auto &MI : reverse(*Header)) { 553e76fa9ecSHeejin Ahn if (MI.isCall()) { 554e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 555e76fa9ecSHeejin Ahn break; 556e76fa9ecSHeejin Ahn } 557e76fa9ecSHeejin Ahn } 558e76fa9ecSHeejin Ahn } 559e76fa9ecSHeejin Ahn } 560e76fa9ecSHeejin Ahn 561e76fa9ecSHeejin Ahn // Add the TRY. 562e76fa9ecSHeejin Ahn auto InsertPos = GetLatestInsertPos(Header, BeforeSet, AfterSet); 563e76fa9ecSHeejin Ahn MachineInstr *Begin = 564e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 565e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 566e76fa9ecSHeejin Ahn .addImm(int64_t(WebAssembly::ExprType::Void)); 567e76fa9ecSHeejin Ahn 568e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 569e76fa9ecSHeejin Ahn BeforeSet.clear(); 570e76fa9ecSHeejin Ahn AfterSet.clear(); 571e76fa9ecSHeejin Ahn for (const auto &MI : *AfterTry) { 572e76fa9ecSHeejin Ahn #ifndef NDEBUG 573e76fa9ecSHeejin Ahn // END_TRY should precede existing LOOP markers. 574e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) 575e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 576e76fa9ecSHeejin Ahn 577e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 578e76fa9ecSHeejin Ahn // this one. 579e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 580e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 581e76fa9ecSHeejin Ahn #endif 582e76fa9ecSHeejin Ahn 583e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 584e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 585e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 586e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 587e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 588e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 589e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 590e76fa9ecSHeejin Ahn #ifndef NDEBUG 591e76fa9ecSHeejin Ahn else 592e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 593e76fa9ecSHeejin Ahn #endif 594e76fa9ecSHeejin Ahn } 595e76fa9ecSHeejin Ahn } 596e76fa9ecSHeejin Ahn 597e76fa9ecSHeejin Ahn // Mark the end of the TRY. 598e76fa9ecSHeejin Ahn InsertPos = GetEarliestInsertPos(AfterTry, BeforeSet, AfterSet); 599e76fa9ecSHeejin Ahn MachineInstr *End = 600e76fa9ecSHeejin Ahn BuildMI(*AfterTry, InsertPos, Bottom->findBranchDebugLoc(), 601e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 602e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 603e76fa9ecSHeejin Ahn 604e76fa9ecSHeejin Ahn // Track the farthest-spanning scope that ends at this point. 605e76fa9ecSHeejin Ahn int Number = AfterTry->getNumber(); 606e76fa9ecSHeejin Ahn if (!ScopeTops[Number] || 607e76fa9ecSHeejin Ahn ScopeTops[Number]->getNumber() > Header->getNumber()) 608e76fa9ecSHeejin Ahn ScopeTops[Number] = Header; 609e76fa9ecSHeejin Ahn } 610e76fa9ecSHeejin Ahn 6111d68e80fSDan Gohman static unsigned 6121d68e80fSDan Gohman GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 6131d68e80fSDan Gohman const MachineBasicBlock *MBB) { 6141d68e80fSDan Gohman unsigned Depth = 0; 6151d68e80fSDan Gohman for (auto X : reverse(Stack)) { 6161d68e80fSDan Gohman if (X == MBB) 6171d68e80fSDan Gohman break; 6181d68e80fSDan Gohman ++Depth; 6191d68e80fSDan Gohman } 6201d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 6211d68e80fSDan Gohman return Depth; 6221d68e80fSDan Gohman } 6231d68e80fSDan Gohman 6242726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 6252726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 6262726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 6272726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 6282726b88cSDan Gohman /// that end at the function end need to have a return type signature that 6292726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 6302726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 631e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 632e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 6332726b88cSDan Gohman assert(MFI.getResults().size() <= 1); 6342726b88cSDan Gohman 6352726b88cSDan Gohman if (MFI.getResults().empty()) 6362726b88cSDan Gohman return; 6372726b88cSDan Gohman 6382726b88cSDan Gohman WebAssembly::ExprType retType; 6392726b88cSDan Gohman switch (MFI.getResults().front().SimpleTy) { 640f208f631SHeejin Ahn case MVT::i32: 641f208f631SHeejin Ahn retType = WebAssembly::ExprType::I32; 642f208f631SHeejin Ahn break; 643f208f631SHeejin Ahn case MVT::i64: 644f208f631SHeejin Ahn retType = WebAssembly::ExprType::I64; 645f208f631SHeejin Ahn break; 646f208f631SHeejin Ahn case MVT::f32: 647f208f631SHeejin Ahn retType = WebAssembly::ExprType::F32; 648f208f631SHeejin Ahn break; 649f208f631SHeejin Ahn case MVT::f64: 650f208f631SHeejin Ahn retType = WebAssembly::ExprType::F64; 651f208f631SHeejin Ahn break; 6522c783859SDerek Schuff case MVT::v16i8: 6532c783859SDerek Schuff case MVT::v8i16: 6542c783859SDerek Schuff case MVT::v4i32: 65551ed131eSDerek Schuff case MVT::v2i64: 6562c783859SDerek Schuff case MVT::v4f32: 65751ed131eSDerek Schuff case MVT::v2f64: 6582c783859SDerek Schuff retType = WebAssembly::ExprType::V128; 6592c783859SDerek Schuff break; 660f208f631SHeejin Ahn case MVT::ExceptRef: 661f208f631SHeejin Ahn retType = WebAssembly::ExprType::ExceptRef; 662f208f631SHeejin Ahn break; 663f208f631SHeejin Ahn default: 664f208f631SHeejin Ahn llvm_unreachable("unexpected return type"); 6652726b88cSDan Gohman } 6662726b88cSDan Gohman 6672726b88cSDan Gohman for (MachineBasicBlock &MBB : reverse(MF)) { 6682726b88cSDan Gohman for (MachineInstr &MI : reverse(MBB)) { 669801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 6702726b88cSDan Gohman continue; 6712726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_BLOCK) { 672e76fa9ecSHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(retType)); 6732726b88cSDan Gohman continue; 6742726b88cSDan Gohman } 6752726b88cSDan Gohman if (MI.getOpcode() == WebAssembly::END_LOOP) { 676e76fa9ecSHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(retType)); 6772726b88cSDan Gohman continue; 6782726b88cSDan Gohman } 6792726b88cSDan Gohman // Something other than an `end`. We're done. 6802726b88cSDan Gohman return; 6812726b88cSDan Gohman } 6822726b88cSDan Gohman } 6832726b88cSDan Gohman } 6842726b88cSDan Gohman 685d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 686d934cb88SDan Gohman // were a block. 687f208f631SHeejin Ahn static void AppendEndToFunction(MachineFunction &MF, 688d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 68910b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 69010b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 691d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 692d934cb88SDan Gohman } 693d934cb88SDan Gohman 694e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 695e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 696e76fa9ecSHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 697e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 698e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 699e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 7008fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 701e76fa9ecSHeejin Ahn for (auto &MBB : MF) 702e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 703e76fa9ecSHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 704e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 705e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 706e76fa9ecSHeejin Ahn for (auto &MBB : MF) 707e76fa9ecSHeejin Ahn placeTryMarker(MBB); 70832807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 709e76fa9ecSHeejin Ahn for (auto &MBB : MF) 710e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 711950a13cfSDan Gohman } 712950a13cfSDan Gohman 713e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 714e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 7151d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 716e76fa9ecSHeejin Ahn // We need two stacks: one for normal scopes and the other for EH pad scopes. 717e76fa9ecSHeejin Ahn // EH pad stack is used to rewrite depths in rethrow instructions. 7181d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 719e76fa9ecSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 7201d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 721e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 722e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 7231d68e80fSDan Gohman switch (MI.getOpcode()) { 7241d68e80fSDan Gohman case WebAssembly::BLOCK: 725e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 726e76fa9ecSHeejin Ahn MBB.getNumber() && 727e76fa9ecSHeejin Ahn "Block/try should be balanced"); 7281d68e80fSDan Gohman Stack.pop_back(); 7291d68e80fSDan Gohman break; 730e76fa9ecSHeejin Ahn 731e76fa9ecSHeejin Ahn case WebAssembly::TRY: 732e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 733e76fa9ecSHeejin Ahn MBB.getNumber() && 734e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 735e76fa9ecSHeejin Ahn Stack.pop_back(); 736e76fa9ecSHeejin Ahn EHPadStack.pop_back(); 737e76fa9ecSHeejin Ahn break; 738e76fa9ecSHeejin Ahn 739e76fa9ecSHeejin Ahn case WebAssembly::CATCH_I32: 740e76fa9ecSHeejin Ahn case WebAssembly::CATCH_I64: 741e76fa9ecSHeejin Ahn case WebAssembly::CATCH_ALL: 742*5b023e07SHeejin Ahn // Currently the only case there are more than one catch for a try is 743*5b023e07SHeejin Ahn // for catch terminate pad, in the form of 744*5b023e07SHeejin Ahn // try 745*5b023e07SHeejin Ahn // catch 746*5b023e07SHeejin Ahn // call @__clang_call_terminate 747*5b023e07SHeejin Ahn // unreachable 748*5b023e07SHeejin Ahn // catch_all 749*5b023e07SHeejin Ahn // call @std::terminate 750*5b023e07SHeejin Ahn // unreachable 751*5b023e07SHeejin Ahn // end 752*5b023e07SHeejin Ahn // So we shouldn't push the current BB for the second catch_all block 753*5b023e07SHeejin Ahn // here. 754*5b023e07SHeejin Ahn if (!WebAssembly::isCatchAllTerminatePad(MBB)) 755e76fa9ecSHeejin Ahn EHPadStack.push_back(&MBB); 756e76fa9ecSHeejin Ahn break; 757e76fa9ecSHeejin Ahn 7581d68e80fSDan Gohman case WebAssembly::LOOP: 7591d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 7601d68e80fSDan Gohman Stack.pop_back(); 7611d68e80fSDan Gohman break; 762e76fa9ecSHeejin Ahn 7631d68e80fSDan Gohman case WebAssembly::END_BLOCK: 764e76fa9ecSHeejin Ahn case WebAssembly::END_TRY: 7651d68e80fSDan Gohman Stack.push_back(&MBB); 7661d68e80fSDan Gohman break; 767e76fa9ecSHeejin Ahn 7681d68e80fSDan Gohman case WebAssembly::END_LOOP: 769e76fa9ecSHeejin Ahn Stack.push_back(EndToBegin[&MI]->getParent()); 7701d68e80fSDan Gohman break; 771e76fa9ecSHeejin Ahn 772e76fa9ecSHeejin Ahn case WebAssembly::RETHROW: { 773e76fa9ecSHeejin Ahn // Rewrite MBB operands to be depth immediates. 774e76fa9ecSHeejin Ahn unsigned EHPadDepth = GetDepth(EHPadStack, MI.getOperand(0).getMBB()); 775e76fa9ecSHeejin Ahn MI.RemoveOperand(0); 776e76fa9ecSHeejin Ahn MI.addOperand(MF, MachineOperand::CreateImm(EHPadDepth)); 777e76fa9ecSHeejin Ahn break; 778e76fa9ecSHeejin Ahn } 779e76fa9ecSHeejin Ahn 780e76fa9ecSHeejin Ahn case WebAssembly::RETHROW_TO_CALLER: { 781e76fa9ecSHeejin Ahn MachineInstr *Rethrow = 782e76fa9ecSHeejin Ahn BuildMI(MBB, MI, MI.getDebugLoc(), TII.get(WebAssembly::RETHROW)) 783ac764aa8SHeejin Ahn .addImm(EHPadStack.size()); 784e76fa9ecSHeejin Ahn MI.eraseFromParent(); 785e76fa9ecSHeejin Ahn I = MachineBasicBlock::reverse_iterator(Rethrow); 786e76fa9ecSHeejin Ahn break; 787e76fa9ecSHeejin Ahn } 788e76fa9ecSHeejin Ahn 7891d68e80fSDan Gohman default: 7901d68e80fSDan Gohman if (MI.isTerminator()) { 7911d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 7921d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 7931d68e80fSDan Gohman while (MI.getNumOperands() > 0) 7941d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 7951d68e80fSDan Gohman for (auto MO : Ops) { 7961d68e80fSDan Gohman if (MO.isMBB()) 7971d68e80fSDan Gohman MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 7981d68e80fSDan Gohman MI.addOperand(MF, MO); 79932807932SDan Gohman } 8001d68e80fSDan Gohman } 8011d68e80fSDan Gohman break; 8021d68e80fSDan Gohman } 8031d68e80fSDan Gohman } 8041d68e80fSDan Gohman } 8051d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 806e76fa9ecSHeejin Ahn } 8072726b88cSDan Gohman 808e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 809e76fa9ecSHeejin Ahn ScopeTops.clear(); 810e76fa9ecSHeejin Ahn BeginToEnd.clear(); 811e76fa9ecSHeejin Ahn EndToBegin.clear(); 812e76fa9ecSHeejin Ahn TryToEHPad.clear(); 813e76fa9ecSHeejin Ahn EHPadToTry.clear(); 814e76fa9ecSHeejin Ahn BeginToBottom.clear(); 8151d68e80fSDan Gohman } 81632807932SDan Gohman 817950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 818d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 819950a13cfSDan Gohman "********** Function: " 820950a13cfSDan Gohman << MF.getName() << '\n'); 821950a13cfSDan Gohman 822e76fa9ecSHeejin Ahn releaseMemory(); 823e76fa9ecSHeejin Ahn 824e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 8259c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 826950a13cfSDan Gohman 827e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 828e76fa9ecSHeejin Ahn placeMarkers(MF); 829e76fa9ecSHeejin Ahn 830e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 831e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 832e76fa9ecSHeejin Ahn 833e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 834e76fa9ecSHeejin Ahn // WebAssembly's rules. 835e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 836e76fa9ecSHeejin Ahn 837e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 838e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 839e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 840e76fa9ecSHeejin Ahn .getTargetTriple() 841e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 842e76fa9ecSHeejin Ahn AppendEndToFunction(MF, TII); 84332807932SDan Gohman 844950a13cfSDan Gohman return true; 845950a13cfSDan Gohman } 846