1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===// 2950a13cfSDan Gohman // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6950a13cfSDan Gohman // 7950a13cfSDan Gohman //===----------------------------------------------------------------------===// 8950a13cfSDan Gohman /// 9950a13cfSDan Gohman /// \file 105f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass. 11950a13cfSDan Gohman /// 12e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes, 13e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control 14e76fa9ecSHeejin Ahn /// transfers. 15950a13cfSDan Gohman /// 16950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on 17950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry. 18950a13cfSDan Gohman /// 19e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind 20e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format. 21e76fa9ecSHeejin Ahn /// 22950a13cfSDan Gohman //===----------------------------------------------------------------------===// 23950a13cfSDan Gohman 246bda14b3SChandler Carruth #include "WebAssembly.h" 25e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h" 26ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 27276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h" 28950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 294fc4e42dSDan Gohman #include "WebAssemblyUtilities.h" 30c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h" 3132807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 32950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 33904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h" 349f770b36SHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h" 35e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h" 36fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h" 37950a13cfSDan Gohman using namespace llvm; 38276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo; 39950a13cfSDan Gohman 40950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 41950a13cfSDan Gohman 42ed41945fSHeejin Ahn STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found"); 439f770b36SHeejin Ahn STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found"); 44c4ac74fbSHeejin Ahn 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; 621cc52357SHeejin Ahn void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) { 631cc52357SHeejin Ahn int EndNo = End->getNumber(); 641cc52357SHeejin Ahn if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber()) 651cc52357SHeejin Ahn ScopeTops[EndNo] = Begin; 661cc52357SHeejin Ahn } 67e76fa9ecSHeejin Ahn 68c4ac74fbSHeejin Ahn // Placing markers. 69e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF); 70e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB); 71e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB); 72e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB); 73ed41945fSHeejin Ahn 74ed41945fSHeejin Ahn // Exception handling related functions 75ed41945fSHeejin Ahn bool fixCallUnwindMismatches(MachineFunction &MF); 76ed41945fSHeejin Ahn bool fixCatchUnwindMismatches(MachineFunction &MF); 77ed41945fSHeejin Ahn void addTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd, 78ed41945fSHeejin Ahn MachineBasicBlock *DelegateDest); 79ed41945fSHeejin Ahn void recalculateScopeTops(MachineFunction &MF); 80cf699b45SHeejin Ahn void removeUnnecessaryInstrs(MachineFunction &MF); 81ed41945fSHeejin Ahn 82ed41945fSHeejin Ahn // Wrap-up 83*2968611fSHeejin Ahn using EndMarkerInfo = 84*2968611fSHeejin Ahn std::pair<const MachineBasicBlock *, const MachineInstr *>; 85*2968611fSHeejin Ahn unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack, 86*2968611fSHeejin Ahn const MachineBasicBlock *MBB); 87*2968611fSHeejin Ahn unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack, 88ed41945fSHeejin Ahn const MachineBasicBlock *MBB); 89e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF); 90e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF); 91ed41945fSHeejin Ahn void cleanupFunctionData(MachineFunction &MF); 92e76fa9ecSHeejin Ahn 93ed41945fSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE 94ed41945fSHeejin Ahn // (in case of TRY). 95e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 96ed41945fSHeejin Ahn // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding 97ed41945fSHeejin Ahn // BLOCK|LOOP|TRY. 98e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 99e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map 100e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 101e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map 102e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 103e76fa9ecSHeejin Ahn 104ed41945fSHeejin Ahn // We need an appendix block to place 'end_loop' or 'end_try' marker when the 105ed41945fSHeejin Ahn // loop / exception bottom block is the last block in a function 106c4ac74fbSHeejin Ahn MachineBasicBlock *AppendixBB = nullptr; 107c4ac74fbSHeejin Ahn MachineBasicBlock *getAppendixBlock(MachineFunction &MF) { 108c4ac74fbSHeejin Ahn if (!AppendixBB) { 109c4ac74fbSHeejin Ahn AppendixBB = MF.CreateMachineBasicBlock(); 110c4ac74fbSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 111c4ac74fbSHeejin Ahn AppendixBB->addSuccessor(AppendixBB); 112c4ac74fbSHeejin Ahn MF.push_back(AppendixBB); 113c4ac74fbSHeejin Ahn } 114c4ac74fbSHeejin Ahn return AppendixBB; 115c4ac74fbSHeejin Ahn } 116c4ac74fbSHeejin Ahn 117ed41945fSHeejin Ahn // Before running rewriteDepthImmediates function, 'delegate' has a BB as its 118ed41945fSHeejin Ahn // destination operand. getFakeCallerBlock() returns a fake BB that will be 119ed41945fSHeejin Ahn // used for the operand when 'delegate' needs to rethrow to the caller. This 120ed41945fSHeejin Ahn // will be rewritten as an immediate value that is the number of block depths 121ed41945fSHeejin Ahn // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end 122ed41945fSHeejin Ahn // of the pass. 123ed41945fSHeejin Ahn MachineBasicBlock *FakeCallerBB = nullptr; 124ed41945fSHeejin Ahn MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) { 125ed41945fSHeejin Ahn if (!FakeCallerBB) 126ed41945fSHeejin Ahn FakeCallerBB = MF.CreateMachineBasicBlock(); 127ed41945fSHeejin Ahn return FakeCallerBB; 128ed41945fSHeejin Ahn } 129ed41945fSHeejin Ahn 130cf699b45SHeejin Ahn // Helper functions to register / unregister scope information created by 131cf699b45SHeejin Ahn // marker instructions. 132e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End); 133e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End, 134e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad); 135cf699b45SHeejin Ahn void unregisterScope(MachineInstr *Begin); 136e76fa9ecSHeejin Ahn 137950a13cfSDan Gohman public: 138950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 139950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 140e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); } 141e76fa9ecSHeejin Ahn void releaseMemory() override; 142950a13cfSDan Gohman }; 143950a13cfSDan Gohman } // end anonymous namespace 144950a13cfSDan Gohman 145950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 14640926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 147c4ac74fbSHeejin Ahn "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false, 148f208f631SHeejin Ahn false) 14940926451SJacob Gravelle 150950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 151950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 152950a13cfSDan Gohman } 153950a13cfSDan Gohman 154b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 155b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 156b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 157b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 158b3aa1ecaSDan Gohman /// explicit mentions. 15918c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 16035e4a289SDan Gohman MachineBasicBlock *MBB) { 161b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 162b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 163b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 164b3aa1ecaSDan Gohman return true; 165b3aa1ecaSDan Gohman return false; 166b3aa1ecaSDan Gohman } 167b3aa1ecaSDan Gohman 168e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB, 169e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 170e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 171e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only 172e76fa9ecSHeejin Ahn // used for sanity checking. 1731cc52357SHeejin Ahn template <typename Container> 174e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 1751cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet, 1761cc52357SHeejin Ahn const Container &AfterSet) { 177e76fa9ecSHeejin Ahn auto InsertPos = MBB->end(); 178e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) { 179e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) { 180e76fa9ecSHeejin Ahn #ifndef NDEBUG 181e76fa9ecSHeejin Ahn // Sanity check 182e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 183e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos))); 184e76fa9ecSHeejin Ahn #endif 185e76fa9ecSHeejin Ahn break; 186e76fa9ecSHeejin Ahn } 187e76fa9ecSHeejin Ahn --InsertPos; 188e76fa9ecSHeejin Ahn } 189e76fa9ecSHeejin Ahn return InsertPos; 190e76fa9ecSHeejin Ahn } 191e76fa9ecSHeejin Ahn 192e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB, 193e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 194e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 195e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only 196e76fa9ecSHeejin Ahn // used for sanity checking. 1971cc52357SHeejin Ahn template <typename Container> 198e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 1991cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet, 2001cc52357SHeejin Ahn const Container &AfterSet) { 201e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin(); 202e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) { 203e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) { 204e76fa9ecSHeejin Ahn #ifndef NDEBUG 205e76fa9ecSHeejin Ahn // Sanity check 206e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 207e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos)); 208e76fa9ecSHeejin Ahn #endif 209e76fa9ecSHeejin Ahn break; 210e76fa9ecSHeejin Ahn } 211e76fa9ecSHeejin Ahn ++InsertPos; 212e76fa9ecSHeejin Ahn } 213e76fa9ecSHeejin Ahn return InsertPos; 214e76fa9ecSHeejin Ahn } 215e76fa9ecSHeejin Ahn 216e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 217e76fa9ecSHeejin Ahn MachineInstr *End) { 218e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End; 219e76fa9ecSHeejin Ahn EndToBegin[End] = Begin; 220e76fa9ecSHeejin Ahn } 221e76fa9ecSHeejin Ahn 222ed41945fSHeejin Ahn // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr. 223e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 224e76fa9ecSHeejin Ahn MachineInstr *End, 225e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) { 226e76fa9ecSHeejin Ahn registerScope(Begin, End); 227e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad; 228e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin; 229e76fa9ecSHeejin Ahn } 230e76fa9ecSHeejin Ahn 231cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 232cf699b45SHeejin Ahn assert(BeginToEnd.count(Begin)); 233cf699b45SHeejin Ahn MachineInstr *End = BeginToEnd[Begin]; 234cf699b45SHeejin Ahn assert(EndToBegin.count(End)); 235cf699b45SHeejin Ahn BeginToEnd.erase(Begin); 236cf699b45SHeejin Ahn EndToBegin.erase(End); 237cf699b45SHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 238cf699b45SHeejin Ahn if (EHPad) { 239cf699b45SHeejin Ahn assert(EHPadToTry.count(EHPad)); 240cf699b45SHeejin Ahn TryToEHPad.erase(Begin); 241cf699b45SHeejin Ahn EHPadToTry.erase(EHPad); 242cf699b45SHeejin Ahn } 243cf699b45SHeejin Ahn } 244cf699b45SHeejin Ahn 24532807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 246c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and 247c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later. 248e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 24944a5a4b1SHeejin Ahn assert(!MBB.isEHPad()); 250e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 251e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 252e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 253e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 254e76fa9ecSHeejin Ahn 2558fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2568fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2578fe7e86bSDan Gohman // which reduces overall stack height. 25832807932SDan Gohman MachineBasicBlock *Header = nullptr; 25932807932SDan Gohman bool IsBranchedTo = false; 26032807932SDan Gohman int MBBNumber = MBB.getNumber(); 261e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) { 26232807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 26332807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 26452e240a0SHeejin Ahn if (explicitlyBranchesTo(Pred, &MBB)) 26532807932SDan Gohman IsBranchedTo = true; 26632807932SDan Gohman } 267e76fa9ecSHeejin Ahn } 26832807932SDan Gohman if (!Header) 26932807932SDan Gohman return; 27032807932SDan Gohman if (!IsBranchedTo) 27132807932SDan Gohman return; 27232807932SDan Gohman 2738fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2745c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 2758fe7e86bSDan Gohman 2768fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2778fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2788fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2798fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2808fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2818fe7e86bSDan Gohman // Skip over an intervening scope. 2825c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 2838fe7e86bSDan Gohman } else { 2848fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 2858fe7e86bSDan Gohman Header = ScopeTop; 2868fe7e86bSDan Gohman break; 2878fe7e86bSDan Gohman } 2888fe7e86bSDan Gohman } 2898fe7e86bSDan Gohman } 2908fe7e86bSDan Gohman 2918fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 292e76fa9ecSHeejin Ahn 293e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 294e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 295e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 296e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 297e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 29844a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 29944a5a4b1SHeejin Ahn // loop is above MBB, it should be after the BLOCK, because the loop is 30044a5a4b1SHeejin Ahn // nested in this BLOCK. Otherwise it should be before the BLOCK. 30144a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 30244a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 30344a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 304e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 305e76fa9ecSHeejin Ahn #ifndef NDEBUG 306e76fa9ecSHeejin Ahn else 307e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 308e76fa9ecSHeejin Ahn #endif 309e76fa9ecSHeejin Ahn } 310e76fa9ecSHeejin Ahn 311834debffSHeejin Ahn // If there is a previously placed BLOCK/TRY marker and its corresponding 312834debffSHeejin Ahn // END marker is before the current BLOCK's END marker, that should be 313834debffSHeejin Ahn // placed after this BLOCK. Otherwise it should be placed before this BLOCK 314834debffSHeejin Ahn // marker. 31544a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 316834debffSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) { 317834debffSHeejin Ahn if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber()) 318e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 319834debffSHeejin Ahn #ifndef NDEBUG 320834debffSHeejin Ahn else 321834debffSHeejin Ahn BeforeSet.insert(&MI); 322834debffSHeejin Ahn #endif 323834debffSHeejin Ahn } 324e76fa9ecSHeejin Ahn 325e76fa9ecSHeejin Ahn #ifndef NDEBUG 326e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 327e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 328e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 329e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 330e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 331e76fa9ecSHeejin Ahn #endif 332e76fa9ecSHeejin Ahn 333e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK. 334e76fa9ecSHeejin Ahn if (MI.isTerminator()) 335e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 336e76fa9ecSHeejin Ahn } 337e76fa9ecSHeejin Ahn 338e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK. 339e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 340e76fa9ecSHeejin Ahn --I) { 341409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 342409b4391SYury Delendik continue; 343e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 344e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 345e76fa9ecSHeejin Ahn else 346e76fa9ecSHeejin Ahn break; 34732807932SDan Gohman } 34832807932SDan Gohman 3498fe7e86bSDan Gohman // Add the BLOCK. 3502cb27072SThomas Lively WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void; 35118c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 35292401cc1SHeejin Ahn MachineInstr *Begin = 35392401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3542726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 355d6f48786SHeejin Ahn .addImm(int64_t(ReturnType)); 3561d68e80fSDan Gohman 357e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 358e76fa9ecSHeejin Ahn BeforeSet.clear(); 359e76fa9ecSHeejin Ahn AfterSet.clear(); 360e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 361e76fa9ecSHeejin Ahn #ifndef NDEBUG 362e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 363e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 364e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 365e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 366e76fa9ecSHeejin Ahn #endif 367e76fa9ecSHeejin Ahn 368e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 369e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 370e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 371e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 372e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 373e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 374e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 375e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 376e76fa9ecSHeejin Ahn #ifndef NDEBUG 377e76fa9ecSHeejin Ahn else 378e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 379e76fa9ecSHeejin Ahn #endif 380e76fa9ecSHeejin Ahn } 381e76fa9ecSHeejin Ahn } 382e76fa9ecSHeejin Ahn 3831d68e80fSDan Gohman // Mark the end of the block. 38418c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 38510b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3862726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 387e76fa9ecSHeejin Ahn registerScope(Begin, End); 3888fe7e86bSDan Gohman 3898fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3901cc52357SHeejin Ahn updateScopeTops(Header, &MBB); 391950a13cfSDan Gohman } 392950a13cfSDan Gohman 3938fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 394e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 395e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 396e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 397276f9e8cSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 398276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI); 399e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 400e76fa9ecSHeejin Ahn 4018fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 4028fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 4038fe7e86bSDan Gohman return; 4048fe7e86bSDan Gohman 4058fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 4068fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 407276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(Loop); 4085c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 409e3e4a5ffSDan Gohman if (Iter == MF.end()) { 410c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4115c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 412e3e4a5ffSDan Gohman } 4138fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 414f6857223SDan Gohman 415e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 416e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 417e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 418e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 419e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 420e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 421e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 422e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 423e76fa9ecSHeejin Ahn #ifndef NDEBUG 424e76fa9ecSHeejin Ahn else 425e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 426e76fa9ecSHeejin Ahn #endif 427e76fa9ecSHeejin Ahn } 428e76fa9ecSHeejin Ahn 429e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 43018c56a07SHeejin Ahn auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 43110b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4322726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4332cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 4341d68e80fSDan Gohman 435e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 436e76fa9ecSHeejin Ahn BeforeSet.clear(); 437e76fa9ecSHeejin Ahn AfterSet.clear(); 438e76fa9ecSHeejin Ahn #ifndef NDEBUG 439e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 440e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 441e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 442e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 443e76fa9ecSHeejin Ahn #endif 444e76fa9ecSHeejin Ahn 445e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 446e76fa9ecSHeejin Ahn // the loop end as its location). 44718c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 44867f74aceSHeejin Ahn DebugLoc EndDL = AfterLoop->pred_empty() 44967f74aceSHeejin Ahn ? DebugLoc() 45067f74aceSHeejin Ahn : (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 451e76fa9ecSHeejin Ahn MachineInstr *End = 452e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 453e76fa9ecSHeejin Ahn registerScope(Begin, End); 4548fe7e86bSDan Gohman 4558fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4568fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 457442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4581cc52357SHeejin Ahn updateScopeTops(&MBB, AfterLoop); 459e3e4a5ffSDan Gohman } 460950a13cfSDan Gohman 461e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 46244a5a4b1SHeejin Ahn assert(MBB.isEHPad()); 463e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 464e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 465e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 466276f9e8cSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 467e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 468276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI); 469e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 470e76fa9ecSHeejin Ahn 471e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 472e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 473e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 474e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 475e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 476e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 47718c56a07SHeejin Ahn assert(!explicitlyBranchesTo(Pred, &MBB) && 478e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 479e76fa9ecSHeejin Ahn } 480e76fa9ecSHeejin Ahn } 481e76fa9ecSHeejin Ahn if (!Header) 482e76fa9ecSHeejin Ahn return; 483e76fa9ecSHeejin Ahn 484e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 485e76fa9ecSHeejin Ahn // end. 486e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 487e76fa9ecSHeejin Ahn assert(WE); 488276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(WE); 489e76fa9ecSHeejin Ahn 4905c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 491e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 492c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4935c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 494e76fa9ecSHeejin Ahn } 49520cf0749SHeejin Ahn MachineBasicBlock *Cont = &*Iter; 496e76fa9ecSHeejin Ahn 49720cf0749SHeejin Ahn assert(Cont != &MF.front()); 4985c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 499e76fa9ecSHeejin Ahn 500e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 501e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 502e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 503e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 504e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 505e76fa9ecSHeejin Ahn // Skip over an intervening scope. 5065c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 507e76fa9ecSHeejin Ahn } else { 508e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 509e76fa9ecSHeejin Ahn Header = ScopeTop; 510e76fa9ecSHeejin Ahn break; 511e76fa9ecSHeejin Ahn } 512e76fa9ecSHeejin Ahn } 513e76fa9ecSHeejin Ahn } 514e76fa9ecSHeejin Ahn 515e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 516e76fa9ecSHeejin Ahn 51744a5a4b1SHeejin Ahn // Instructions that should go before the TRY. 518e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 51944a5a4b1SHeejin Ahn // Instructions that should go after the TRY. 520e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 521e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 52244a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 52344a5a4b1SHeejin Ahn // loop is above MBB, it should be after the TRY, because the loop is nested 52444a5a4b1SHeejin Ahn // in this TRY. Otherwise it should be before the TRY. 525e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 52644a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 52744a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 528e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 529e76fa9ecSHeejin Ahn #ifndef NDEBUG 530e76fa9ecSHeejin Ahn else 531e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 532e76fa9ecSHeejin Ahn #endif 533e76fa9ecSHeejin Ahn } 534e76fa9ecSHeejin Ahn 53544a5a4b1SHeejin Ahn // All previously inserted BLOCK/TRY markers should be after the TRY because 53644a5a4b1SHeejin Ahn // they are all nested trys. 53744a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 53844a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 539e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 540e76fa9ecSHeejin Ahn 541e76fa9ecSHeejin Ahn #ifndef NDEBUG 54244a5a4b1SHeejin Ahn // All END_(BLOCK/LOOP/TRY) markers should be before the TRY. 54344a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 54444a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 545e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 546e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 547e76fa9ecSHeejin Ahn #endif 548e76fa9ecSHeejin Ahn 549e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 550e76fa9ecSHeejin Ahn if (MI.isTerminator()) 551e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 552e76fa9ecSHeejin Ahn } 553e76fa9ecSHeejin Ahn 5546a37c5d6SHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 5556a37c5d6SHeejin Ahn // contain the call within it. So the call should go after the TRY. The 5566a37c5d6SHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 5576a37c5d6SHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 5586a37c5d6SHeejin Ahn // throw. 5596a37c5d6SHeejin Ahn MachineInstr *ThrowingCall = nullptr; 5606a37c5d6SHeejin Ahn if (MBB.isPredecessor(Header)) { 5616a37c5d6SHeejin Ahn auto TermPos = Header->getFirstTerminator(); 5626a37c5d6SHeejin Ahn if (TermPos == Header->end() || 5636a37c5d6SHeejin Ahn TermPos->getOpcode() != WebAssembly::RETHROW) { 5646a37c5d6SHeejin Ahn for (auto &MI : reverse(*Header)) { 5656a37c5d6SHeejin Ahn if (MI.isCall()) { 5666a37c5d6SHeejin Ahn AfterSet.insert(&MI); 5676a37c5d6SHeejin Ahn ThrowingCall = &MI; 5686a37c5d6SHeejin Ahn // Possibly throwing calls are usually wrapped by EH_LABEL 5696a37c5d6SHeejin Ahn // instructions. We don't want to split them and the call. 5706a37c5d6SHeejin Ahn if (MI.getIterator() != Header->begin() && 5716a37c5d6SHeejin Ahn std::prev(MI.getIterator())->isEHLabel()) { 5726a37c5d6SHeejin Ahn AfterSet.insert(&*std::prev(MI.getIterator())); 5736a37c5d6SHeejin Ahn ThrowingCall = &*std::prev(MI.getIterator()); 5746a37c5d6SHeejin Ahn } 5756a37c5d6SHeejin Ahn break; 5766a37c5d6SHeejin Ahn } 5776a37c5d6SHeejin Ahn } 5786a37c5d6SHeejin Ahn } 5796a37c5d6SHeejin Ahn } 5806a37c5d6SHeejin Ahn 581e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 5826a37c5d6SHeejin Ahn // For BLOCK placement, we start the search from the previous instruction of a 5836a37c5d6SHeejin Ahn // BB's terminator, but in TRY's case, we should start from the previous 5846a37c5d6SHeejin Ahn // instruction of a call that can throw, or a EH_LABEL that precedes the call, 5856a37c5d6SHeejin Ahn // because the return values of the call's previous instructions can be 5866a37c5d6SHeejin Ahn // stackified and consumed by the throwing call. 5876a37c5d6SHeejin Ahn auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall) 5886a37c5d6SHeejin Ahn : Header->getFirstTerminator(); 5896a37c5d6SHeejin Ahn for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) { 590409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 591409b4391SYury Delendik continue; 592e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 593e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 594e76fa9ecSHeejin Ahn else 595e76fa9ecSHeejin Ahn break; 596e76fa9ecSHeejin Ahn } 597e76fa9ecSHeejin Ahn 598e76fa9ecSHeejin Ahn // Add the TRY. 59918c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 600e76fa9ecSHeejin Ahn MachineInstr *Begin = 601e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 602e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 6032cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 604e76fa9ecSHeejin Ahn 605e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 606e76fa9ecSHeejin Ahn BeforeSet.clear(); 607e76fa9ecSHeejin Ahn AfterSet.clear(); 60820cf0749SHeejin Ahn for (const auto &MI : *Cont) { 609e76fa9ecSHeejin Ahn #ifndef NDEBUG 61044a5a4b1SHeejin Ahn // END_TRY should precede existing LOOP and BLOCK markers. 61144a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 61244a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::BLOCK) 613e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 614e76fa9ecSHeejin Ahn 615e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 616e76fa9ecSHeejin Ahn // this one. 617e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 618e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 619e76fa9ecSHeejin Ahn #endif 620e76fa9ecSHeejin Ahn 621e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 622e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 623e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 624e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 625e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 626222718fdSHeejin Ahn // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they 627222718fdSHeejin Ahn // are in the same BB, LOOP is always before TRY. 628222718fdSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber()) 629e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 630e76fa9ecSHeejin Ahn #ifndef NDEBUG 631e76fa9ecSHeejin Ahn else 632e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 633e76fa9ecSHeejin Ahn #endif 634e76fa9ecSHeejin Ahn } 63544a5a4b1SHeejin Ahn 63644a5a4b1SHeejin Ahn // It is not possible for an END_BLOCK to be already in this block. 637e76fa9ecSHeejin Ahn } 638e76fa9ecSHeejin Ahn 639e76fa9ecSHeejin Ahn // Mark the end of the TRY. 64020cf0749SHeejin Ahn InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 641e76fa9ecSHeejin Ahn MachineInstr *End = 64220cf0749SHeejin Ahn BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 643e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 644e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 645e76fa9ecSHeejin Ahn 64682da1ffcSHeejin Ahn // Track the farthest-spanning scope that ends at this point. We create two 64782da1ffcSHeejin Ahn // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 64882da1ffcSHeejin Ahn // with 'try'). We need to create 'catch' -> 'try' mapping here too because 64982da1ffcSHeejin Ahn // markers should not span across 'catch'. For example, this should not 65082da1ffcSHeejin Ahn // happen: 65182da1ffcSHeejin Ahn // 65282da1ffcSHeejin Ahn // try 65382da1ffcSHeejin Ahn // block --| (X) 65482da1ffcSHeejin Ahn // catch | 65582da1ffcSHeejin Ahn // end_block --| 65682da1ffcSHeejin Ahn // end_try 6571cc52357SHeejin Ahn for (auto *End : {&MBB, Cont}) 6581cc52357SHeejin Ahn updateScopeTops(Header, End); 65982da1ffcSHeejin Ahn } 660e76fa9ecSHeejin Ahn 661cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 662cf699b45SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 663cf699b45SHeejin Ahn 664cf699b45SHeejin Ahn // When there is an unconditional branch right before a catch instruction and 665cf699b45SHeejin Ahn // it branches to the end of end_try marker, we don't need the branch, because 666cf699b45SHeejin Ahn // it there is no exception, the control flow transfers to that point anyway. 667cf699b45SHeejin Ahn // bb0: 668cf699b45SHeejin Ahn // try 669cf699b45SHeejin Ahn // ... 670cf699b45SHeejin Ahn // br bb2 <- Not necessary 671c93b9559SHeejin Ahn // bb1 (ehpad): 672cf699b45SHeejin Ahn // catch 673cf699b45SHeejin Ahn // ... 674c93b9559SHeejin Ahn // bb2: <- Continuation BB 675cf699b45SHeejin Ahn // end 676c93b9559SHeejin Ahn // 677c93b9559SHeejin Ahn // A more involved case: When the BB where 'end' is located is an another EH 678c93b9559SHeejin Ahn // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example, 679c93b9559SHeejin Ahn // bb0: 680c93b9559SHeejin Ahn // try 681c93b9559SHeejin Ahn // try 682c93b9559SHeejin Ahn // ... 683c93b9559SHeejin Ahn // br bb3 <- Not necessary 684c93b9559SHeejin Ahn // bb1 (ehpad): 685c93b9559SHeejin Ahn // catch 686c93b9559SHeejin Ahn // bb2 (ehpad): 687c93b9559SHeejin Ahn // end 688c93b9559SHeejin Ahn // catch 689c93b9559SHeejin Ahn // ... 690c93b9559SHeejin Ahn // bb3: <- Continuation BB 691c93b9559SHeejin Ahn // end 692c93b9559SHeejin Ahn // 693c93b9559SHeejin Ahn // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is 694c93b9559SHeejin Ahn // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the 695c93b9559SHeejin Ahn // code can be deleted. This is why we run 'while' until 'Cont' is not an EH 696c93b9559SHeejin Ahn // pad. 697cf699b45SHeejin Ahn for (auto &MBB : MF) { 698cf699b45SHeejin Ahn if (!MBB.isEHPad()) 699cf699b45SHeejin Ahn continue; 700cf699b45SHeejin Ahn 701cf699b45SHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 702cf699b45SHeejin Ahn SmallVector<MachineOperand, 4> Cond; 7035c644c9bSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 704c93b9559SHeejin Ahn 705c93b9559SHeejin Ahn MachineBasicBlock *Cont = &MBB; 706c93b9559SHeejin Ahn while (Cont->isEHPad()) { 707c93b9559SHeejin Ahn MachineInstr *Try = EHPadToTry[Cont]; 708c93b9559SHeejin Ahn MachineInstr *EndTry = BeginToEnd[Try]; 709ed41945fSHeejin Ahn // We started from an EH pad, so the end marker cannot be a delegate 710ed41945fSHeejin Ahn assert(EndTry->getOpcode() != WebAssembly::DELEGATE); 711c93b9559SHeejin Ahn Cont = EndTry->getParent(); 712c93b9559SHeejin Ahn } 713c93b9559SHeejin Ahn 714cf699b45SHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 7153fe6ea46SHeejin Ahn // This condition means either 7163fe6ea46SHeejin Ahn // 1. This BB ends with a single unconditional branch whose destinaion is 7173fe6ea46SHeejin Ahn // Cont. 7183fe6ea46SHeejin Ahn // 2. This BB ends with a conditional branch followed by an unconditional 7193fe6ea46SHeejin Ahn // branch, and the unconditional branch's destination is Cont. 7203fe6ea46SHeejin Ahn // In both cases, we want to remove the last (= unconditional) branch. 721cf699b45SHeejin Ahn if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 7223fe6ea46SHeejin Ahn (!Cond.empty() && FBB && FBB == Cont))) { 7233fe6ea46SHeejin Ahn bool ErasedUncondBr = false; 724a5099ad9SHeejin Ahn (void)ErasedUncondBr; 7253fe6ea46SHeejin Ahn for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin(); 7263fe6ea46SHeejin Ahn I != E; --I) { 7273fe6ea46SHeejin Ahn auto PrevI = std::prev(I); 7283fe6ea46SHeejin Ahn if (PrevI->isTerminator()) { 7293fe6ea46SHeejin Ahn assert(PrevI->getOpcode() == WebAssembly::BR); 7303fe6ea46SHeejin Ahn PrevI->eraseFromParent(); 7313fe6ea46SHeejin Ahn ErasedUncondBr = true; 7323fe6ea46SHeejin Ahn break; 7333fe6ea46SHeejin Ahn } 7343fe6ea46SHeejin Ahn } 7353fe6ea46SHeejin Ahn assert(ErasedUncondBr && "Unconditional branch not erased!"); 7363fe6ea46SHeejin Ahn } 737cf699b45SHeejin Ahn } 738cf699b45SHeejin Ahn 739cf699b45SHeejin Ahn // When there are block / end_block markers that overlap with try / end_try 740cf699b45SHeejin Ahn // markers, and the block and try markers' return types are the same, the 741cf699b45SHeejin Ahn // block /end_block markers are not necessary, because try / end_try markers 742cf699b45SHeejin Ahn // also can serve as boundaries for branches. 743cf699b45SHeejin Ahn // block <- Not necessary 744cf699b45SHeejin Ahn // try 745cf699b45SHeejin Ahn // ... 746cf699b45SHeejin Ahn // catch 747cf699b45SHeejin Ahn // ... 748cf699b45SHeejin Ahn // end 749cf699b45SHeejin Ahn // end <- Not necessary 750cf699b45SHeejin Ahn SmallVector<MachineInstr *, 32> ToDelete; 751cf699b45SHeejin Ahn for (auto &MBB : MF) { 752cf699b45SHeejin Ahn for (auto &MI : MBB) { 753cf699b45SHeejin Ahn if (MI.getOpcode() != WebAssembly::TRY) 754cf699b45SHeejin Ahn continue; 755cf699b45SHeejin Ahn MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 756ed41945fSHeejin Ahn if (EndTry->getOpcode() == WebAssembly::DELEGATE) 757ed41945fSHeejin Ahn continue; 758ed41945fSHeejin Ahn 759cf699b45SHeejin Ahn MachineBasicBlock *TryBB = Try->getParent(); 760cf699b45SHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent(); 761cf699b45SHeejin Ahn int64_t RetType = Try->getOperand(0).getImm(); 7625c644c9bSHeejin Ahn for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 763cf699b45SHeejin Ahn B != TryBB->begin() && E != Cont->end() && 764cf699b45SHeejin Ahn std::prev(B)->getOpcode() == WebAssembly::BLOCK && 765cf699b45SHeejin Ahn E->getOpcode() == WebAssembly::END_BLOCK && 766cf699b45SHeejin Ahn std::prev(B)->getOperand(0).getImm() == RetType; 767cf699b45SHeejin Ahn --B, ++E) { 768cf699b45SHeejin Ahn ToDelete.push_back(&*std::prev(B)); 769cf699b45SHeejin Ahn ToDelete.push_back(&*E); 770cf699b45SHeejin Ahn } 771cf699b45SHeejin Ahn } 772cf699b45SHeejin Ahn } 773cf699b45SHeejin Ahn for (auto *MI : ToDelete) { 774cf699b45SHeejin Ahn if (MI->getOpcode() == WebAssembly::BLOCK) 775cf699b45SHeejin Ahn unregisterScope(MI); 776cf699b45SHeejin Ahn MI->eraseFromParent(); 777cf699b45SHeejin Ahn } 778cf699b45SHeejin Ahn } 779cf699b45SHeejin Ahn 78083c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class. 78183c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) { 78283c26eaeSHeejin Ahn if (RC == &WebAssembly::I32RegClass) 78383c26eaeSHeejin Ahn return WebAssembly::COPY_I32; 78483c26eaeSHeejin Ahn if (RC == &WebAssembly::I64RegClass) 78583c26eaeSHeejin Ahn return WebAssembly::COPY_I64; 78683c26eaeSHeejin Ahn if (RC == &WebAssembly::F32RegClass) 78783c26eaeSHeejin Ahn return WebAssembly::COPY_F32; 78883c26eaeSHeejin Ahn if (RC == &WebAssembly::F64RegClass) 78983c26eaeSHeejin Ahn return WebAssembly::COPY_F64; 79083c26eaeSHeejin Ahn if (RC == &WebAssembly::V128RegClass) 79183c26eaeSHeejin Ahn return WebAssembly::COPY_V128; 79260653e24SHeejin Ahn if (RC == &WebAssembly::FUNCREFRegClass) 79360653e24SHeejin Ahn return WebAssembly::COPY_FUNCREF; 79460653e24SHeejin Ahn if (RC == &WebAssembly::EXTERNREFRegClass) 79560653e24SHeejin Ahn return WebAssembly::COPY_EXTERNREF; 79683c26eaeSHeejin Ahn llvm_unreachable("Unexpected register class"); 79783c26eaeSHeejin Ahn } 79883c26eaeSHeejin Ahn 79961d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that 80061d5c76aSHeejin Ahn // have their uses in Split. 801ed41945fSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, 802ed41945fSHeejin Ahn MachineBasicBlock &Split) { 8031cc52357SHeejin Ahn MachineFunction &MF = *MBB.getParent(); 8041cc52357SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 8051cc52357SHeejin Ahn auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 8061cc52357SHeejin Ahn auto &MRI = MF.getRegInfo(); 8071cc52357SHeejin Ahn 80861d5c76aSHeejin Ahn for (auto &MI : Split) { 80961d5c76aSHeejin Ahn for (auto &MO : MI.explicit_uses()) { 81061d5c76aSHeejin Ahn if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg())) 81161d5c76aSHeejin Ahn continue; 81261d5c76aSHeejin Ahn if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg())) 81361d5c76aSHeejin Ahn if (Def->getParent() == &MBB) 81461d5c76aSHeejin Ahn MFI.unstackifyVReg(MO.getReg()); 81561d5c76aSHeejin Ahn } 81661d5c76aSHeejin Ahn } 81783c26eaeSHeejin Ahn 81883c26eaeSHeejin Ahn // In RegStackify, when a register definition is used multiple times, 81983c26eaeSHeejin Ahn // Reg = INST ... 82083c26eaeSHeejin Ahn // INST ..., Reg, ... 82183c26eaeSHeejin Ahn // INST ..., Reg, ... 82283c26eaeSHeejin Ahn // INST ..., Reg, ... 82383c26eaeSHeejin Ahn // 82483c26eaeSHeejin Ahn // we introduce a TEE, which has the following form: 82583c26eaeSHeejin Ahn // DefReg = INST ... 82683c26eaeSHeejin Ahn // TeeReg, Reg = TEE_... DefReg 82783c26eaeSHeejin Ahn // INST ..., TeeReg, ... 82883c26eaeSHeejin Ahn // INST ..., Reg, ... 82983c26eaeSHeejin Ahn // INST ..., Reg, ... 83083c26eaeSHeejin Ahn // with DefReg and TeeReg stackified but Reg not stackified. 83183c26eaeSHeejin Ahn // 83283c26eaeSHeejin Ahn // But the invariant that TeeReg should be stackified can be violated while we 83383c26eaeSHeejin Ahn // unstackify registers in the split BB above. In this case, we convert TEEs 83483c26eaeSHeejin Ahn // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals. 83583c26eaeSHeejin Ahn // DefReg = INST ... 83683c26eaeSHeejin Ahn // TeeReg = COPY DefReg 83783c26eaeSHeejin Ahn // Reg = COPY DefReg 83883c26eaeSHeejin Ahn // INST ..., TeeReg, ... 83983c26eaeSHeejin Ahn // INST ..., Reg, ... 84083c26eaeSHeejin Ahn // INST ..., Reg, ... 84183c26eaeSHeejin Ahn for (auto I = MBB.begin(), E = MBB.end(); I != E;) { 84283c26eaeSHeejin Ahn MachineInstr &MI = *I++; 84383c26eaeSHeejin Ahn if (!WebAssembly::isTee(MI.getOpcode())) 84483c26eaeSHeejin Ahn continue; 84583c26eaeSHeejin Ahn Register TeeReg = MI.getOperand(0).getReg(); 84683c26eaeSHeejin Ahn Register Reg = MI.getOperand(1).getReg(); 84783c26eaeSHeejin Ahn Register DefReg = MI.getOperand(2).getReg(); 84883c26eaeSHeejin Ahn if (!MFI.isVRegStackified(TeeReg)) { 84983c26eaeSHeejin Ahn // Now we are not using TEE anymore, so unstackify DefReg too 85083c26eaeSHeejin Ahn MFI.unstackifyVReg(DefReg); 85183c26eaeSHeejin Ahn unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg)); 85283c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg) 85383c26eaeSHeejin Ahn .addReg(DefReg); 85483c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg); 85583c26eaeSHeejin Ahn MI.eraseFromParent(); 85683c26eaeSHeejin Ahn } 85783c26eaeSHeejin Ahn } 85861d5c76aSHeejin Ahn } 85961d5c76aSHeejin Ahn 860ed41945fSHeejin Ahn // Wrap the given range of instruction with try-delegate. RangeBegin and 861ed41945fSHeejin Ahn // RangeEnd are inclusive. 862ed41945fSHeejin Ahn void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin, 863ed41945fSHeejin Ahn MachineInstr *RangeEnd, 864ed41945fSHeejin Ahn MachineBasicBlock *DelegateDest) { 865ed41945fSHeejin Ahn auto *BeginBB = RangeBegin->getParent(); 866ed41945fSHeejin Ahn auto *EndBB = RangeEnd->getParent(); 867ed41945fSHeejin Ahn MachineFunction &MF = *BeginBB->getParent(); 868ed41945fSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 869ed41945fSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 870ed41945fSHeejin Ahn 871ed41945fSHeejin Ahn // Local expression tree before the first call of this range should go 872ed41945fSHeejin Ahn // after the nested TRY. 873ed41945fSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 874ed41945fSHeejin Ahn AfterSet.insert(RangeBegin); 875ed41945fSHeejin Ahn for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin(); 876ed41945fSHeejin Ahn I != E; --I) { 877ed41945fSHeejin Ahn if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 878ed41945fSHeejin Ahn continue; 879ed41945fSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 880ed41945fSHeejin Ahn AfterSet.insert(&*std::prev(I)); 881ed41945fSHeejin Ahn else 882ed41945fSHeejin Ahn break; 883ed41945fSHeejin Ahn } 884ed41945fSHeejin Ahn 885ed41945fSHeejin Ahn // Create the nested try instruction. 886ed41945fSHeejin Ahn auto TryPos = getLatestInsertPos( 887ed41945fSHeejin Ahn BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet); 888ed41945fSHeejin Ahn MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(), 889ed41945fSHeejin Ahn TII.get(WebAssembly::TRY)) 890ed41945fSHeejin Ahn .addImm(int64_t(WebAssembly::BlockType::Void)); 891ed41945fSHeejin Ahn 892ed41945fSHeejin Ahn // Create a BB to insert the 'delegate' instruction. 893ed41945fSHeejin Ahn MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock(); 894ed41945fSHeejin Ahn // If the destination of 'delegate' is not the caller, adds the destination to 895ed41945fSHeejin Ahn // the BB's successors. 896ed41945fSHeejin Ahn if (DelegateDest != FakeCallerBB) 897ed41945fSHeejin Ahn DelegateBB->addSuccessor(DelegateDest); 898ed41945fSHeejin Ahn 899ed41945fSHeejin Ahn auto SplitPos = std::next(RangeEnd->getIterator()); 900ed41945fSHeejin Ahn if (SplitPos == EndBB->end()) { 901ed41945fSHeejin Ahn // If the range's end instruction is at the end of the BB, insert the new 902ed41945fSHeejin Ahn // delegate BB after the current BB. 903ed41945fSHeejin Ahn MF.insert(std::next(EndBB->getIterator()), DelegateBB); 904ed41945fSHeejin Ahn EndBB->addSuccessor(DelegateBB); 905ed41945fSHeejin Ahn 906ed41945fSHeejin Ahn } else { 9079f770b36SHeejin Ahn // When the split pos is in the middle of a BB, we split the BB into two and 9089f770b36SHeejin Ahn // put the 'delegate' BB in between. We normally create a split BB and make 9099f770b36SHeejin Ahn // it a successor of the original BB (PostSplit == true), but in case the BB 9109f770b36SHeejin Ahn // is an EH pad and the split pos is before 'catch', we should preserve the 9119f770b36SHeejin Ahn // BB's property, including that it is an EH pad, in the later part of the 9129f770b36SHeejin Ahn // BB, where 'catch' is. In this case we set PostSplit to false. 9139f770b36SHeejin Ahn bool PostSplit = true; 9149f770b36SHeejin Ahn if (EndBB->isEHPad()) { 9159f770b36SHeejin Ahn for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end(); 9169f770b36SHeejin Ahn I != E; ++I) { 9179f770b36SHeejin Ahn if (WebAssembly::isCatch(I->getOpcode())) { 9189f770b36SHeejin Ahn PostSplit = false; 9199f770b36SHeejin Ahn break; 9209f770b36SHeejin Ahn } 9219f770b36SHeejin Ahn } 9229f770b36SHeejin Ahn } 9239f770b36SHeejin Ahn 9249f770b36SHeejin Ahn MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr; 9259f770b36SHeejin Ahn if (PostSplit) { 926ed41945fSHeejin Ahn // If the range's end instruction is in the middle of the BB, we split the 927ed41945fSHeejin Ahn // BB into two and insert the delegate BB in between. 928ed41945fSHeejin Ahn // - Before: 929ed41945fSHeejin Ahn // bb: 930ed41945fSHeejin Ahn // range_end 931ed41945fSHeejin Ahn // other_insts 932ed41945fSHeejin Ahn // 933ed41945fSHeejin Ahn // - After: 934ed41945fSHeejin Ahn // pre_bb: (previous 'bb') 935ed41945fSHeejin Ahn // range_end 936ed41945fSHeejin Ahn // delegate_bb: (new) 937ed41945fSHeejin Ahn // delegate 938ed41945fSHeejin Ahn // post_bb: (new) 939ed41945fSHeejin Ahn // other_insts 9409f770b36SHeejin Ahn PreBB = EndBB; 9419f770b36SHeejin Ahn PostBB = MF.CreateMachineBasicBlock(); 942ed41945fSHeejin Ahn MF.insert(std::next(PreBB->getIterator()), PostBB); 943ed41945fSHeejin Ahn MF.insert(std::next(PreBB->getIterator()), DelegateBB); 944ed41945fSHeejin Ahn PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end()); 945ed41945fSHeejin Ahn PostBB->transferSuccessors(PreBB); 9469f770b36SHeejin Ahn } else { 9479f770b36SHeejin Ahn // - Before: 9489f770b36SHeejin Ahn // ehpad: 9499f770b36SHeejin Ahn // range_end 9509f770b36SHeejin Ahn // catch 9519f770b36SHeejin Ahn // ... 9529f770b36SHeejin Ahn // 9539f770b36SHeejin Ahn // - After: 9549f770b36SHeejin Ahn // pre_bb: (new) 9559f770b36SHeejin Ahn // range_end 9569f770b36SHeejin Ahn // delegate_bb: (new) 9579f770b36SHeejin Ahn // delegate 9589f770b36SHeejin Ahn // post_bb: (previous 'ehpad') 9599f770b36SHeejin Ahn // catch 9609f770b36SHeejin Ahn // ... 9619f770b36SHeejin Ahn assert(EndBB->isEHPad()); 9629f770b36SHeejin Ahn PreBB = MF.CreateMachineBasicBlock(); 9639f770b36SHeejin Ahn PostBB = EndBB; 9649f770b36SHeejin Ahn MF.insert(PostBB->getIterator(), PreBB); 9659f770b36SHeejin Ahn MF.insert(PostBB->getIterator(), DelegateBB); 9669f770b36SHeejin Ahn PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos); 9679f770b36SHeejin Ahn // We don't need to transfer predecessors of the EH pad to 'PreBB', 9689f770b36SHeejin Ahn // because an EH pad's predecessors are all through unwind edges and they 9699f770b36SHeejin Ahn // should still unwind to the EH pad, not PreBB. 9709f770b36SHeejin Ahn } 971ed41945fSHeejin Ahn unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB); 972ed41945fSHeejin Ahn PreBB->addSuccessor(DelegateBB); 973ed41945fSHeejin Ahn PreBB->addSuccessor(PostBB); 974ed41945fSHeejin Ahn } 975ed41945fSHeejin Ahn 976ed41945fSHeejin Ahn // Add 'delegate' instruction in the delegate BB created above. 977ed41945fSHeejin Ahn MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(), 978ed41945fSHeejin Ahn TII.get(WebAssembly::DELEGATE)) 979ed41945fSHeejin Ahn .addMBB(DelegateDest); 980ed41945fSHeejin Ahn registerTryScope(Try, Delegate, nullptr); 981ed41945fSHeejin Ahn } 982ed41945fSHeejin Ahn 983ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) { 984ed41945fSHeejin Ahn // Linearizing the control flow by placing TRY / END_TRY markers can create 985ed41945fSHeejin Ahn // mismatches in unwind destinations for throwing instructions, such as calls. 986ed41945fSHeejin Ahn // 987ed41945fSHeejin Ahn // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate' 988ed41945fSHeejin Ahn // instruction delegates an exception to an outer 'catch'. It can target not 989ed41945fSHeejin Ahn // only 'catch' but all block-like structures including another 'delegate', 990ed41945fSHeejin Ahn // but with slightly different semantics than branches. When it targets a 991ed41945fSHeejin Ahn // 'catch', it will delegate the exception to that catch. It is being 992ed41945fSHeejin Ahn // discussed how to define the semantics when 'delegate''s target is a non-try 993ed41945fSHeejin Ahn // block: it will either be a validation failure or it will target the next 994ed41945fSHeejin Ahn // outer try-catch. But anyway our LLVM backend currently does not generate 995ed41945fSHeejin Ahn // such code. The example below illustrates where the 'delegate' instruction 996ed41945fSHeejin Ahn // in the middle will delegate the exception to, depending on the value of N. 997ed41945fSHeejin Ahn // try 998ed41945fSHeejin Ahn // try 999ed41945fSHeejin Ahn // block 1000ed41945fSHeejin Ahn // try 1001ed41945fSHeejin Ahn // try 1002ed41945fSHeejin Ahn // call @foo 1003ed41945fSHeejin Ahn // delegate N ;; Where will this delegate to? 1004ed41945fSHeejin Ahn // catch ;; N == 0 1005ed41945fSHeejin Ahn // end 1006ed41945fSHeejin Ahn // end ;; N == 1 (invalid; will not be generated) 1007ed41945fSHeejin Ahn // delegate ;; N == 2 1008ed41945fSHeejin Ahn // catch ;; N == 3 1009ed41945fSHeejin Ahn // end 1010ed41945fSHeejin Ahn // ;; N == 4 (to caller) 1011ed41945fSHeejin Ahn 1012ed41945fSHeejin Ahn // 1. When an instruction may throw, but the EH pad it will unwind to can be 1013ed41945fSHeejin Ahn // different from the original CFG. 1014ed41945fSHeejin Ahn // 1015ed41945fSHeejin Ahn // Example: we have the following CFG: 1016ed41945fSHeejin Ahn // bb0: 1017ed41945fSHeejin Ahn // call @foo ; if it throws, unwind to bb2 1018ed41945fSHeejin Ahn // bb1: 1019ed41945fSHeejin Ahn // call @bar ; if it throws, unwind to bb3 1020ed41945fSHeejin Ahn // bb2 (ehpad): 1021ed41945fSHeejin Ahn // catch 1022ed41945fSHeejin Ahn // ... 1023ed41945fSHeejin Ahn // bb3 (ehpad) 1024ed41945fSHeejin Ahn // catch 1025ed41945fSHeejin Ahn // ... 1026ed41945fSHeejin Ahn // 1027ed41945fSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 1028ed41945fSHeejin Ahn // will look like: (BB markers are omitted) 1029ed41945fSHeejin Ahn // try 1030ed41945fSHeejin Ahn // try 1031ed41945fSHeejin Ahn // call @foo 1032ed41945fSHeejin Ahn // call @bar ;; if it throws, unwind to bb3 1033ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1034ed41945fSHeejin Ahn // ... 1035ed41945fSHeejin Ahn // end_try 1036ed41945fSHeejin Ahn // catch ;; ehpad (bb3) 1037ed41945fSHeejin Ahn // ... 1038ed41945fSHeejin Ahn // end_try 1039ed41945fSHeejin Ahn // 1040ed41945fSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it 1041ed41945fSHeejin Ahn // is supposed to end up. We solve this problem by wrapping the mismatching 1042ed41945fSHeejin Ahn // call with an inner try-delegate that rethrows the exception to the right 1043ed41945fSHeejin Ahn // 'catch'. 1044ed41945fSHeejin Ahn // 1045ed41945fSHeejin Ahn // try 1046ed41945fSHeejin Ahn // try 1047ed41945fSHeejin Ahn // call @foo 1048ed41945fSHeejin Ahn // try ;; (new) 1049ed41945fSHeejin Ahn // call @bar 1050ed41945fSHeejin Ahn // delegate 1 (bb3) ;; (new) 1051ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1052ed41945fSHeejin Ahn // ... 1053ed41945fSHeejin Ahn // end_try 1054ed41945fSHeejin Ahn // catch ;; ehpad (bb3) 1055ed41945fSHeejin Ahn // ... 1056ed41945fSHeejin Ahn // end_try 1057ed41945fSHeejin Ahn // 1058ed41945fSHeejin Ahn // --- 1059ed41945fSHeejin Ahn // 2. The same as 1, but in this case an instruction unwinds to a caller 1060ed41945fSHeejin Ahn // function and not another EH pad. 1061ed41945fSHeejin Ahn // 1062ed41945fSHeejin Ahn // Example: we have the following CFG: 1063ed41945fSHeejin Ahn // bb0: 1064ed41945fSHeejin Ahn // call @foo ; if it throws, unwind to bb2 1065ed41945fSHeejin Ahn // bb1: 1066ed41945fSHeejin Ahn // call @bar ; if it throws, unwind to caller 1067ed41945fSHeejin Ahn // bb2 (ehpad): 1068ed41945fSHeejin Ahn // catch 1069ed41945fSHeejin Ahn // ... 1070ed41945fSHeejin Ahn // 1071ed41945fSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 1072ed41945fSHeejin Ahn // will look like: 1073ed41945fSHeejin Ahn // try 1074ed41945fSHeejin Ahn // call @foo 1075ed41945fSHeejin Ahn // call @bar ;; if it throws, unwind to caller 1076ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1077ed41945fSHeejin Ahn // ... 1078ed41945fSHeejin Ahn // end_try 1079ed41945fSHeejin Ahn // 1080ed41945fSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, when it is supposed 1081ed41945fSHeejin Ahn // throw up to the caller. We solve this problem in the same way, but in this 1082ed41945fSHeejin Ahn // case 'delegate's immediate argument is the number of block depths + 1, 1083ed41945fSHeejin Ahn // which means it rethrows to the caller. 1084ed41945fSHeejin Ahn // try 1085ed41945fSHeejin Ahn // call @foo 1086ed41945fSHeejin Ahn // try ;; (new) 1087ed41945fSHeejin Ahn // call @bar 1088ed41945fSHeejin Ahn // delegate 1 (caller) ;; (new) 1089ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1090ed41945fSHeejin Ahn // ... 1091ed41945fSHeejin Ahn // end_try 1092ed41945fSHeejin Ahn // 1093ed41945fSHeejin Ahn // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the 1094ed41945fSHeejin Ahn // caller, it will take a fake BB generated by getFakeCallerBlock(), which 1095ed41945fSHeejin Ahn // will be converted to a correct immediate argument later. 1096ed41945fSHeejin Ahn // 1097ed41945fSHeejin Ahn // In case there are multiple calls in a BB that may throw to the caller, they 1098ed41945fSHeejin Ahn // can be wrapped together in one nested try-delegate scope. (In 1, this 1099ed41945fSHeejin Ahn // couldn't happen, because may-throwing instruction there had an unwind 1100ed41945fSHeejin Ahn // destination, i.e., it was an invoke before, and there could be only one 1101ed41945fSHeejin Ahn // invoke within a BB.) 1102ed41945fSHeejin Ahn 1103ed41945fSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 1104ed41945fSHeejin Ahn // Range of intructions to be wrapped in a new nested try/catch. A range 1105ed41945fSHeejin Ahn // exists in a single BB and does not span multiple BBs. 1106ed41945fSHeejin Ahn using TryRange = std::pair<MachineInstr *, MachineInstr *>; 1107ed41945fSHeejin Ahn // In original CFG, <unwind destination BB, a vector of try ranges> 1108ed41945fSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges; 1109ed41945fSHeejin Ahn 1110ed41945fSHeejin Ahn // Gather possibly throwing calls (i.e., previously invokes) whose current 1111ed41945fSHeejin Ahn // unwind destination is not the same as the original CFG. (Case 1) 1112ed41945fSHeejin Ahn 1113ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) { 1114ed41945fSHeejin Ahn bool SeenThrowableInstInBB = false; 1115ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) { 1116ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 1117ed41945fSHeejin Ahn EHPadStack.pop_back(); 1118ed41945fSHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) 1119ed41945fSHeejin Ahn EHPadStack.push_back(MI.getParent()); 1120ed41945fSHeejin Ahn 1121ed41945fSHeejin Ahn // In this loop we only gather calls that have an EH pad to unwind. So 1122ed41945fSHeejin Ahn // there will be at most 1 such call (= invoke) in a BB, so after we've 1123ed41945fSHeejin Ahn // seen one, we can skip the rest of BB. Also if MBB has no EH pad 1124ed41945fSHeejin Ahn // successor or MI does not throw, this is not an invoke. 1125ed41945fSHeejin Ahn if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() || 1126ed41945fSHeejin Ahn !WebAssembly::mayThrow(MI)) 1127ed41945fSHeejin Ahn continue; 1128ed41945fSHeejin Ahn SeenThrowableInstInBB = true; 1129ed41945fSHeejin Ahn 1130ed41945fSHeejin Ahn // If the EH pad on the stack top is where this instruction should unwind 1131ed41945fSHeejin Ahn // next, we're good. 1132ed41945fSHeejin Ahn MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF); 1133ed41945fSHeejin Ahn for (auto *Succ : MBB.successors()) { 1134ed41945fSHeejin Ahn // Even though semantically a BB can have multiple successors in case an 1135ed41945fSHeejin Ahn // exception is not caught by a catchpad, in our backend implementation 1136ed41945fSHeejin Ahn // it is guaranteed that a BB can have at most one EH pad successor. For 1137ed41945fSHeejin Ahn // details, refer to comments in findWasmUnwindDestinations function in 1138ed41945fSHeejin Ahn // SelectionDAGBuilder.cpp. 1139ed41945fSHeejin Ahn if (Succ->isEHPad()) { 1140ed41945fSHeejin Ahn UnwindDest = Succ; 1141ed41945fSHeejin Ahn break; 1142ed41945fSHeejin Ahn } 1143ed41945fSHeejin Ahn } 1144ed41945fSHeejin Ahn if (EHPadStack.back() == UnwindDest) 1145ed41945fSHeejin Ahn continue; 1146ed41945fSHeejin Ahn 1147ed41945fSHeejin Ahn // Include EH_LABELs in the range before and afer the invoke 1148ed41945fSHeejin Ahn MachineInstr *RangeBegin = &MI, *RangeEnd = &MI; 1149ed41945fSHeejin Ahn if (RangeBegin->getIterator() != MBB.begin() && 1150ed41945fSHeejin Ahn std::prev(RangeBegin->getIterator())->isEHLabel()) 1151ed41945fSHeejin Ahn RangeBegin = &*std::prev(RangeBegin->getIterator()); 1152ed41945fSHeejin Ahn if (std::next(RangeEnd->getIterator()) != MBB.end() && 1153ed41945fSHeejin Ahn std::next(RangeEnd->getIterator())->isEHLabel()) 1154ed41945fSHeejin Ahn RangeEnd = &*std::next(RangeEnd->getIterator()); 1155ed41945fSHeejin Ahn 1156ed41945fSHeejin Ahn // If not, record the range. 1157ed41945fSHeejin Ahn UnwindDestToTryRanges[UnwindDest].push_back( 1158ed41945fSHeejin Ahn TryRange(RangeBegin, RangeEnd)); 1159ed41945fSHeejin Ahn LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName() 1160ed41945fSHeejin Ahn << "\nCall = " << MI 1161ed41945fSHeejin Ahn << "\nOriginal dest = " << UnwindDest->getName() 1162ed41945fSHeejin Ahn << " Current dest = " << EHPadStack.back()->getName() 1163ed41945fSHeejin Ahn << "\n\n"); 1164ed41945fSHeejin Ahn } 1165ed41945fSHeejin Ahn } 1166ed41945fSHeejin Ahn 1167ed41945fSHeejin Ahn assert(EHPadStack.empty()); 1168ed41945fSHeejin Ahn 1169ed41945fSHeejin Ahn // Gather possibly throwing calls that are supposed to unwind up to the caller 1170ed41945fSHeejin Ahn // if they throw, but currently unwind to an incorrect destination. Unlike the 1171ed41945fSHeejin Ahn // loop above, there can be multiple calls within a BB that unwind to the 1172ed41945fSHeejin Ahn // caller, which we should group together in a range. (Case 2) 1173ed41945fSHeejin Ahn 1174ed41945fSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive 1175ed41945fSHeejin Ahn 1176ed41945fSHeejin Ahn // Record the range. 1177ed41945fSHeejin Ahn auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) { 1178ed41945fSHeejin Ahn UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back( 1179ed41945fSHeejin Ahn TryRange(RangeBegin, RangeEnd)); 1180ed41945fSHeejin Ahn LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " 1181ed41945fSHeejin Ahn << RangeBegin->getParent()->getName() 1182ed41945fSHeejin Ahn << "\nRange begin = " << *RangeBegin 1183ed41945fSHeejin Ahn << "Range end = " << *RangeEnd 1184ed41945fSHeejin Ahn << "\nOriginal dest = caller Current dest = " 1185ed41945fSHeejin Ahn << CurrentDest->getName() << "\n\n"); 1186ed41945fSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers 1187ed41945fSHeejin Ahn }; 1188ed41945fSHeejin Ahn 1189ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) { 1190ed41945fSHeejin Ahn bool SeenThrowableInstInBB = false; 1191ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) { 1192ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 1193ed41945fSHeejin Ahn EHPadStack.pop_back(); 1194ed41945fSHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) 1195ed41945fSHeejin Ahn EHPadStack.push_back(MI.getParent()); 1196ed41945fSHeejin Ahn bool MayThrow = WebAssembly::mayThrow(MI); 1197ed41945fSHeejin Ahn 1198ed41945fSHeejin Ahn // If MBB has an EH pad successor and this is the last instruction that 1199ed41945fSHeejin Ahn // may throw, this instruction unwinds to the EH pad and not to the 1200ed41945fSHeejin Ahn // caller. 1201ed41945fSHeejin Ahn if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB) { 1202ed41945fSHeejin Ahn SeenThrowableInstInBB = true; 1203ed41945fSHeejin Ahn continue; 1204ed41945fSHeejin Ahn } 1205ed41945fSHeejin Ahn 1206ed41945fSHeejin Ahn // We wrap up the current range when we see a marker even if we haven't 1207ed41945fSHeejin Ahn // finished a BB. 1208ed41945fSHeejin Ahn if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) { 1209ed41945fSHeejin Ahn RecordCallerMismatchRange(EHPadStack.back()); 1210ed41945fSHeejin Ahn continue; 1211ed41945fSHeejin Ahn } 1212ed41945fSHeejin Ahn 1213ed41945fSHeejin Ahn // If EHPadStack is empty, that means it correctly unwinds to the caller 1214ed41945fSHeejin Ahn // if it throws, so we're good. If MI does not throw, we're good too. 1215ed41945fSHeejin Ahn if (EHPadStack.empty() || !MayThrow) 1216ed41945fSHeejin Ahn continue; 1217ed41945fSHeejin Ahn 1218ed41945fSHeejin Ahn // We found an instruction that unwinds to the caller but currently has an 1219ed41945fSHeejin Ahn // incorrect unwind destination. Create a new range or increment the 1220ed41945fSHeejin Ahn // currently existing range. 1221ed41945fSHeejin Ahn if (!RangeEnd) 1222ed41945fSHeejin Ahn RangeBegin = RangeEnd = &MI; 1223ed41945fSHeejin Ahn else 1224ed41945fSHeejin Ahn RangeBegin = &MI; 1225ed41945fSHeejin Ahn } 1226ed41945fSHeejin Ahn 1227ed41945fSHeejin Ahn if (RangeEnd) 1228ed41945fSHeejin Ahn RecordCallerMismatchRange(EHPadStack.back()); 1229ed41945fSHeejin Ahn } 1230ed41945fSHeejin Ahn 1231ed41945fSHeejin Ahn assert(EHPadStack.empty()); 1232ed41945fSHeejin Ahn 1233ed41945fSHeejin Ahn // We don't have any unwind destination mismatches to resolve. 1234ed41945fSHeejin Ahn if (UnwindDestToTryRanges.empty()) 1235ed41945fSHeejin Ahn return false; 1236ed41945fSHeejin Ahn 1237ed41945fSHeejin Ahn // Now we fix the mismatches by wrapping calls with inner try-delegates. 1238ed41945fSHeejin Ahn for (auto &P : UnwindDestToTryRanges) { 1239ed41945fSHeejin Ahn NumCallUnwindMismatches += P.second.size(); 1240ed41945fSHeejin Ahn MachineBasicBlock *UnwindDest = P.first; 1241ed41945fSHeejin Ahn auto &TryRanges = P.second; 1242ed41945fSHeejin Ahn 1243ed41945fSHeejin Ahn for (auto Range : TryRanges) { 1244ed41945fSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; 1245ed41945fSHeejin Ahn std::tie(RangeBegin, RangeEnd) = Range; 1246ed41945fSHeejin Ahn auto *MBB = RangeBegin->getParent(); 1247ed41945fSHeejin Ahn 1248ed41945fSHeejin Ahn // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we 1249ed41945fSHeejin Ahn // are going to wrap the invoke with try-delegate, making the 'delegate' 1250ed41945fSHeejin Ahn // BB the new successor instead, so remove the EH pad succesor here. The 1251ed41945fSHeejin Ahn // BB may not have an EH pad successor if calls in this BB throw to the 1252ed41945fSHeejin Ahn // caller. 1253ed41945fSHeejin Ahn MachineBasicBlock *EHPad = nullptr; 1254ed41945fSHeejin Ahn for (auto *Succ : MBB->successors()) { 1255ed41945fSHeejin Ahn if (Succ->isEHPad()) { 1256ed41945fSHeejin Ahn EHPad = Succ; 1257ed41945fSHeejin Ahn break; 1258ed41945fSHeejin Ahn } 1259ed41945fSHeejin Ahn } 1260ed41945fSHeejin Ahn if (EHPad) 1261ed41945fSHeejin Ahn MBB->removeSuccessor(EHPad); 1262ed41945fSHeejin Ahn 1263ed41945fSHeejin Ahn addTryDelegate(RangeBegin, RangeEnd, UnwindDest); 1264ed41945fSHeejin Ahn } 1265ed41945fSHeejin Ahn } 1266ed41945fSHeejin Ahn 1267ed41945fSHeejin Ahn return true; 1268ed41945fSHeejin Ahn } 1269ed41945fSHeejin Ahn 1270ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) { 12719f770b36SHeejin Ahn // There is another kind of unwind destination mismatches besides call unwind 12729f770b36SHeejin Ahn // mismatches, which we will call "catch unwind mismatches". See this example 12739f770b36SHeejin Ahn // after the marker placement: 12749f770b36SHeejin Ahn // try 12759f770b36SHeejin Ahn // try 12769f770b36SHeejin Ahn // call @foo 12779f770b36SHeejin Ahn // catch __cpp_exception ;; ehpad A (next unwind dest: caller) 12789f770b36SHeejin Ahn // ... 12799f770b36SHeejin Ahn // end_try 12809f770b36SHeejin Ahn // catch_all ;; ehpad B 12819f770b36SHeejin Ahn // ... 12829f770b36SHeejin Ahn // end_try 12839f770b36SHeejin Ahn // 12849f770b36SHeejin Ahn // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo' 12859f770b36SHeejin Ahn // throws a foreign exception that is not caught by ehpad A, and its next 12869f770b36SHeejin Ahn // destination should be the caller. But after control flow linearization, 12879f770b36SHeejin Ahn // another EH pad can be placed in between (e.g. ehpad B here), making the 12889f770b36SHeejin Ahn // next unwind destination incorrect. In this case, the foreign exception 12899f770b36SHeejin Ahn // will instead go to ehpad B and will be caught there instead. In this 12909f770b36SHeejin Ahn // example the correct next unwind destination is the caller, but it can be 12919f770b36SHeejin Ahn // another outer catch in other cases. 12929f770b36SHeejin Ahn // 12939f770b36SHeejin Ahn // There is no specific 'call' or 'throw' instruction to wrap with a 12949f770b36SHeejin Ahn // try-delegate, so we wrap the whole try-catch-end with a try-delegate and 12959f770b36SHeejin Ahn // make it rethrow to the right destination, as in the example below: 12969f770b36SHeejin Ahn // try 12979f770b36SHeejin Ahn // try ;; (new) 12989f770b36SHeejin Ahn // try 12999f770b36SHeejin Ahn // call @foo 13009f770b36SHeejin Ahn // catch __cpp_exception ;; ehpad A (next unwind dest: caller) 13019f770b36SHeejin Ahn // ... 13029f770b36SHeejin Ahn // end_try 13039f770b36SHeejin Ahn // delegate 1 (caller) ;; (new) 13049f770b36SHeejin Ahn // catch_all ;; ehpad B 13059f770b36SHeejin Ahn // ... 13069f770b36SHeejin Ahn // end_try 13079f770b36SHeejin Ahn 13089f770b36SHeejin Ahn const auto *EHInfo = MF.getWasmEHFuncInfo(); 13099f770b36SHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 13109f770b36SHeejin Ahn // For EH pads that have catch unwind mismatches, a map of <EH pad, its 13119f770b36SHeejin Ahn // correct unwind destination>. 13129f770b36SHeejin Ahn DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest; 13139f770b36SHeejin Ahn 13149f770b36SHeejin Ahn for (auto &MBB : reverse(MF)) { 13159f770b36SHeejin Ahn for (auto &MI : reverse(MBB)) { 13169f770b36SHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 13179f770b36SHeejin Ahn EHPadStack.pop_back(); 13189f770b36SHeejin Ahn else if (MI.getOpcode() == WebAssembly::DELEGATE) 13199f770b36SHeejin Ahn EHPadStack.push_back(&MBB); 13209f770b36SHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) { 13219f770b36SHeejin Ahn auto *EHPad = &MBB; 13229f770b36SHeejin Ahn 13239f770b36SHeejin Ahn // catch_all always catches an exception, so we don't need to do 13249f770b36SHeejin Ahn // anything 13259f770b36SHeejin Ahn if (MI.getOpcode() == WebAssembly::CATCH_ALL) { 13269f770b36SHeejin Ahn } 13279f770b36SHeejin Ahn 13289f770b36SHeejin Ahn // This can happen when the unwind dest was removed during the 13299f770b36SHeejin Ahn // optimization, e.g. because it was unreachable. 13309f770b36SHeejin Ahn else if (EHPadStack.empty() && EHInfo->hasEHPadUnwindDest(EHPad)) { 13319f770b36SHeejin Ahn LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName() 13329f770b36SHeejin Ahn << "'s unwind destination does not exist anymore" 13339f770b36SHeejin Ahn << "\n\n"); 13349f770b36SHeejin Ahn } 13359f770b36SHeejin Ahn 13369f770b36SHeejin Ahn // The EHPad's next unwind destination is the caller, but we incorrectly 13379f770b36SHeejin Ahn // unwind to another EH pad. 13389f770b36SHeejin Ahn else if (!EHPadStack.empty() && !EHInfo->hasEHPadUnwindDest(EHPad)) { 13399f770b36SHeejin Ahn EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF); 13409f770b36SHeejin Ahn LLVM_DEBUG(dbgs() 13419f770b36SHeejin Ahn << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName() 13429f770b36SHeejin Ahn << " Original dest = caller Current dest = " 13439f770b36SHeejin Ahn << EHPadStack.back()->getName() << "\n\n"); 13449f770b36SHeejin Ahn } 13459f770b36SHeejin Ahn 13469f770b36SHeejin Ahn // The EHPad's next unwind destination is an EH pad, whereas we 13479f770b36SHeejin Ahn // incorrectly unwind to another EH pad. 13489f770b36SHeejin Ahn else if (!EHPadStack.empty() && EHInfo->hasEHPadUnwindDest(EHPad)) { 13499f770b36SHeejin Ahn auto *UnwindDest = EHInfo->getEHPadUnwindDest(EHPad); 13509f770b36SHeejin Ahn if (EHPadStack.back() != UnwindDest) { 13519f770b36SHeejin Ahn EHPadToUnwindDest[EHPad] = UnwindDest; 13529f770b36SHeejin Ahn LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = " 13539f770b36SHeejin Ahn << EHPad->getName() << " Original dest = " 13549f770b36SHeejin Ahn << UnwindDest->getName() << " Current dest = " 13559f770b36SHeejin Ahn << EHPadStack.back()->getName() << "\n\n"); 13569f770b36SHeejin Ahn } 13579f770b36SHeejin Ahn } 13589f770b36SHeejin Ahn 13599f770b36SHeejin Ahn EHPadStack.push_back(EHPad); 13609f770b36SHeejin Ahn } 13619f770b36SHeejin Ahn } 13629f770b36SHeejin Ahn } 13639f770b36SHeejin Ahn 13649f770b36SHeejin Ahn assert(EHPadStack.empty()); 13659f770b36SHeejin Ahn if (EHPadToUnwindDest.empty()) 1366c4ac74fbSHeejin Ahn return false; 13679f770b36SHeejin Ahn NumCatchUnwindMismatches += EHPadToUnwindDest.size(); 13689f770b36SHeejin Ahn 13699f770b36SHeejin Ahn for (auto &P : EHPadToUnwindDest) { 13709f770b36SHeejin Ahn MachineBasicBlock *EHPad = P.first; 13719f770b36SHeejin Ahn MachineBasicBlock *UnwindDest = P.second; 13729f770b36SHeejin Ahn MachineInstr *Try = EHPadToTry[EHPad]; 13739f770b36SHeejin Ahn MachineInstr *EndTry = BeginToEnd[Try]; 13749f770b36SHeejin Ahn addTryDelegate(Try, EndTry, UnwindDest); 13759f770b36SHeejin Ahn } 13769f770b36SHeejin Ahn 13779f770b36SHeejin Ahn return true; 1378c4ac74fbSHeejin Ahn } 1379c4ac74fbSHeejin Ahn 1380ed41945fSHeejin Ahn void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) { 1381ed41945fSHeejin Ahn // Renumber BBs and recalculate ScopeTop info because new BBs might have been 1382ed41945fSHeejin Ahn // created and inserted during fixing unwind mismatches. 1383ed41945fSHeejin Ahn MF.RenumberBlocks(); 1384ed41945fSHeejin Ahn ScopeTops.clear(); 1385ed41945fSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs()); 1386ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) { 1387ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) { 1388ed41945fSHeejin Ahn if (ScopeTops[MBB.getNumber()]) 1389ed41945fSHeejin Ahn break; 1390ed41945fSHeejin Ahn switch (MI.getOpcode()) { 1391ed41945fSHeejin Ahn case WebAssembly::END_BLOCK: 1392ed41945fSHeejin Ahn case WebAssembly::END_LOOP: 1393ed41945fSHeejin Ahn case WebAssembly::END_TRY: 1394ed41945fSHeejin Ahn case WebAssembly::DELEGATE: 1395ed41945fSHeejin Ahn updateScopeTops(EndToBegin[&MI]->getParent(), &MBB); 1396ed41945fSHeejin Ahn break; 1397ed41945fSHeejin Ahn case WebAssembly::CATCH: 1398ed41945fSHeejin Ahn case WebAssembly::CATCH_ALL: 1399ed41945fSHeejin Ahn updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB); 1400ed41945fSHeejin Ahn break; 1401ed41945fSHeejin Ahn } 1402ed41945fSHeejin Ahn } 1403ed41945fSHeejin Ahn } 1404ed41945fSHeejin Ahn } 1405ed41945fSHeejin Ahn 14062726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 14072726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 14082726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 14092726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 14102726b88cSDan Gohman /// that end at the function end need to have a return type signature that 14112726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 14122726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 1413e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 1414e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 14152726b88cSDan Gohman 14162726b88cSDan Gohman if (MFI.getResults().empty()) 14172726b88cSDan Gohman return; 14182726b88cSDan Gohman 14192cb27072SThomas Lively // MCInstLower will add the proper types to multivalue signatures based on the 14202cb27072SThomas Lively // function return type 14212cb27072SThomas Lively WebAssembly::BlockType RetType = 14222cb27072SThomas Lively MFI.getResults().size() > 1 14232cb27072SThomas Lively ? WebAssembly::BlockType::Multivalue 14242cb27072SThomas Lively : WebAssembly::BlockType( 14252cb27072SThomas Lively WebAssembly::toValType(MFI.getResults().front())); 14262726b88cSDan Gohman 1427d25c17f3SHeejin Ahn SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist; 1428d25c17f3SHeejin Ahn Worklist.push_back(MF.rbegin()->rbegin()); 1429d25c17f3SHeejin Ahn 1430d25c17f3SHeejin Ahn auto Process = [&](MachineBasicBlock::reverse_iterator It) { 1431d25c17f3SHeejin Ahn auto *MBB = It->getParent(); 1432d25c17f3SHeejin Ahn while (It != MBB->rend()) { 1433d25c17f3SHeejin Ahn MachineInstr &MI = *It++; 1434801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 14352726b88cSDan Gohman continue; 14362cb27072SThomas Lively switch (MI.getOpcode()) { 1437d25c17f3SHeejin Ahn case WebAssembly::END_TRY: { 1438d25c17f3SHeejin Ahn // If a 'try''s return type is fixed, both its try body and catch body 1439d25c17f3SHeejin Ahn // should satisfy the return type, so we need to search 'end' 1440d25c17f3SHeejin Ahn // instructions before its corresponding 'catch' too. 1441d25c17f3SHeejin Ahn auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]); 1442d25c17f3SHeejin Ahn assert(EHPad); 14439f8b2576SHeejin Ahn auto NextIt = 14449f8b2576SHeejin Ahn std::next(WebAssembly::findCatch(EHPad)->getReverseIterator()); 14459f8b2576SHeejin Ahn if (NextIt != EHPad->rend()) 14469f8b2576SHeejin Ahn Worklist.push_back(NextIt); 1447d25c17f3SHeejin Ahn LLVM_FALLTHROUGH; 1448d25c17f3SHeejin Ahn } 14492cb27072SThomas Lively case WebAssembly::END_BLOCK: 14502cb27072SThomas Lively case WebAssembly::END_LOOP: 145118c56a07SHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 14522726b88cSDan Gohman continue; 14532cb27072SThomas Lively default: 1454d25c17f3SHeejin Ahn // Something other than an `end`. We're done for this BB. 14552726b88cSDan Gohman return; 14562726b88cSDan Gohman } 14572726b88cSDan Gohman } 1458d25c17f3SHeejin Ahn // We've reached the beginning of a BB. Continue the search in the previous 1459d25c17f3SHeejin Ahn // BB. 1460d25c17f3SHeejin Ahn Worklist.push_back(MBB->getPrevNode()->rbegin()); 1461d25c17f3SHeejin Ahn }; 1462d25c17f3SHeejin Ahn 1463d25c17f3SHeejin Ahn while (!Worklist.empty()) 1464d25c17f3SHeejin Ahn Process(Worklist.pop_back_val()); 14652cb27072SThomas Lively } 14662726b88cSDan Gohman 1467d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 1468d934cb88SDan Gohman // were a block. 146918c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF, 1470d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 147110b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 147210b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 1473d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 1474d934cb88SDan Gohman } 1475d934cb88SDan Gohman 1476e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 1477e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 1478e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 1479e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 1480e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 14818fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 1482e76fa9ecSHeejin Ahn for (auto &MBB : MF) 1483e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 148444a5a4b1SHeejin Ahn 1485d6f48786SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 148644a5a4b1SHeejin Ahn for (auto &MBB : MF) { 148744a5a4b1SHeejin Ahn if (MBB.isEHPad()) { 148844a5a4b1SHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 1489e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1490e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 1491e76fa9ecSHeejin Ahn placeTryMarker(MBB); 149244a5a4b1SHeejin Ahn } else { 149332807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 1494e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 1495950a13cfSDan Gohman } 149644a5a4b1SHeejin Ahn } 1497c4ac74fbSHeejin Ahn // Fix mismatches in unwind destinations induced by linearizing the code. 1498daeead4bSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1499ed41945fSHeejin Ahn MF.getFunction().hasPersonalityFn()) { 1500ed41945fSHeejin Ahn bool Changed = fixCallUnwindMismatches(MF); 1501ed41945fSHeejin Ahn Changed |= fixCatchUnwindMismatches(MF); 1502ed41945fSHeejin Ahn if (Changed) 1503ed41945fSHeejin Ahn recalculateScopeTops(MF); 1504ed41945fSHeejin Ahn } 150544a5a4b1SHeejin Ahn } 1506950a13cfSDan Gohman 1507*2968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getBranchDepth( 1508*2968611fSHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) { 1509*2968611fSHeejin Ahn unsigned Depth = 0; 1510*2968611fSHeejin Ahn for (auto X : reverse(Stack)) { 1511*2968611fSHeejin Ahn if (X.first == MBB) 1512*2968611fSHeejin Ahn break; 1513*2968611fSHeejin Ahn ++Depth; 1514*2968611fSHeejin Ahn } 1515*2968611fSHeejin Ahn assert(Depth < Stack.size() && "Branch destination should be in scope"); 1516*2968611fSHeejin Ahn return Depth; 1517*2968611fSHeejin Ahn } 1518*2968611fSHeejin Ahn 1519*2968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getDelegateDepth( 1520*2968611fSHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) { 1521*2968611fSHeejin Ahn if (MBB == FakeCallerBB) 1522*2968611fSHeejin Ahn return Stack.size(); 1523*2968611fSHeejin Ahn // Delegate's destination is either a catch or a another delegate BB. When the 1524*2968611fSHeejin Ahn // destination is another delegate, we can compute the argument in the same 1525*2968611fSHeejin Ahn // way as branches, because the target delegate BB only contains the single 1526*2968611fSHeejin Ahn // delegate instruction. 1527*2968611fSHeejin Ahn if (!MBB->isEHPad()) // Target is a delegate BB 1528*2968611fSHeejin Ahn return getBranchDepth(Stack, MBB); 1529*2968611fSHeejin Ahn 1530*2968611fSHeejin Ahn // When the delegate's destination is a catch BB, we need to use its 1531*2968611fSHeejin Ahn // corresponding try's end_try BB because Stack contains each marker's end BB. 1532*2968611fSHeejin Ahn // Also we need to check if the end marker instruction matches, because a 1533*2968611fSHeejin Ahn // single BB can contain multiple end markers, like this: 1534*2968611fSHeejin Ahn // bb: 1535*2968611fSHeejin Ahn // END_BLOCK 1536*2968611fSHeejin Ahn // END_TRY 1537*2968611fSHeejin Ahn // END_BLOCK 1538*2968611fSHeejin Ahn // END_TRY 1539*2968611fSHeejin Ahn // ... 1540*2968611fSHeejin Ahn // 1541*2968611fSHeejin Ahn // In case of branches getting the immediate that targets any of these is 1542*2968611fSHeejin Ahn // fine, but delegate has to exactly target the correct try. 1543*2968611fSHeejin Ahn unsigned Depth = 0; 1544*2968611fSHeejin Ahn const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]]; 1545*2968611fSHeejin Ahn for (auto X : reverse(Stack)) { 1546*2968611fSHeejin Ahn if (X.first == EndTry->getParent() && X.second == EndTry) 1547*2968611fSHeejin Ahn break; 1548*2968611fSHeejin Ahn ++Depth; 1549*2968611fSHeejin Ahn } 1550*2968611fSHeejin Ahn assert(Depth < Stack.size() && "Delegate destination should be in scope"); 1551*2968611fSHeejin Ahn return Depth; 1552*2968611fSHeejin Ahn } 1553*2968611fSHeejin Ahn 1554e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 15551d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 1556*2968611fSHeejin Ahn SmallVector<EndMarkerInfo, 8> Stack; 15571d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 1558e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 1559e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 15601d68e80fSDan Gohman switch (MI.getOpcode()) { 15611d68e80fSDan Gohman case WebAssembly::BLOCK: 1562e76fa9ecSHeejin Ahn case WebAssembly::TRY: 1563*2968611fSHeejin Ahn assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <= 1564e76fa9ecSHeejin Ahn MBB.getNumber() && 1565e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 1566e76fa9ecSHeejin Ahn Stack.pop_back(); 1567e76fa9ecSHeejin Ahn break; 1568e76fa9ecSHeejin Ahn 15691d68e80fSDan Gohman case WebAssembly::LOOP: 1570*2968611fSHeejin Ahn assert(Stack.back().first == &MBB && "Loop top should be balanced"); 15711d68e80fSDan Gohman Stack.pop_back(); 15721d68e80fSDan Gohman break; 1573e76fa9ecSHeejin Ahn 15741d68e80fSDan Gohman case WebAssembly::END_BLOCK: 1575*2968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI)); 1576ed41945fSHeejin Ahn break; 1577ed41945fSHeejin Ahn 1578e76fa9ecSHeejin Ahn case WebAssembly::END_TRY: 1579ed41945fSHeejin Ahn // We handle DELEGATE in the default level, because DELEGATE has 1580*2968611fSHeejin Ahn // immediate operands to rewrite. 1581*2968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI)); 15821d68e80fSDan Gohman break; 1583e76fa9ecSHeejin Ahn 15841d68e80fSDan Gohman case WebAssembly::END_LOOP: 1585*2968611fSHeejin Ahn Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI)); 15861d68e80fSDan Gohman break; 1587e76fa9ecSHeejin Ahn 15881d68e80fSDan Gohman default: 15891d68e80fSDan Gohman if (MI.isTerminator()) { 15901d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 15911d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 15921d68e80fSDan Gohman while (MI.getNumOperands() > 0) 15931d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 15941d68e80fSDan Gohman for (auto MO : Ops) { 1595ed41945fSHeejin Ahn if (MO.isMBB()) { 1596ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::DELEGATE) 1597ed41945fSHeejin Ahn MO = MachineOperand::CreateImm( 1598*2968611fSHeejin Ahn getDelegateDepth(Stack, MO.getMBB())); 1599ed41945fSHeejin Ahn else 1600*2968611fSHeejin Ahn MO = MachineOperand::CreateImm( 1601*2968611fSHeejin Ahn getBranchDepth(Stack, MO.getMBB())); 1602ed41945fSHeejin Ahn } 16031d68e80fSDan Gohman MI.addOperand(MF, MO); 160432807932SDan Gohman } 16051d68e80fSDan Gohman } 1606ed41945fSHeejin Ahn 1607*2968611fSHeejin Ahn if (MI.getOpcode() == WebAssembly::DELEGATE) 1608*2968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI)); 16091d68e80fSDan Gohman break; 16101d68e80fSDan Gohman } 16111d68e80fSDan Gohman } 16121d68e80fSDan Gohman } 16131d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 1614e76fa9ecSHeejin Ahn } 16152726b88cSDan Gohman 1616ed41945fSHeejin Ahn void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) { 1617ed41945fSHeejin Ahn if (FakeCallerBB) 1618ed41945fSHeejin Ahn MF.DeleteMachineBasicBlock(FakeCallerBB); 1619ed41945fSHeejin Ahn AppendixBB = FakeCallerBB = nullptr; 1620ed41945fSHeejin Ahn } 1621ed41945fSHeejin Ahn 1622e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 1623e76fa9ecSHeejin Ahn ScopeTops.clear(); 1624e76fa9ecSHeejin Ahn BeginToEnd.clear(); 1625e76fa9ecSHeejin Ahn EndToBegin.clear(); 1626e76fa9ecSHeejin Ahn TryToEHPad.clear(); 1627e76fa9ecSHeejin Ahn EHPadToTry.clear(); 16281d68e80fSDan Gohman } 162932807932SDan Gohman 1630950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 1631d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 1632950a13cfSDan Gohman "********** Function: " 1633950a13cfSDan Gohman << MF.getName() << '\n'); 1634cf699b45SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 1635950a13cfSDan Gohman 1636e76fa9ecSHeejin Ahn releaseMemory(); 1637e76fa9ecSHeejin Ahn 1638e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 16399c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 1640950a13cfSDan Gohman 1641e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 1642e76fa9ecSHeejin Ahn placeMarkers(MF); 1643e76fa9ecSHeejin Ahn 1644c4ac74fbSHeejin Ahn // Remove unnecessary instructions possibly introduced by try/end_trys. 1645cf699b45SHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1646cf699b45SHeejin Ahn MF.getFunction().hasPersonalityFn()) 1647cf699b45SHeejin Ahn removeUnnecessaryInstrs(MF); 1648cf699b45SHeejin Ahn 1649e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 1650e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 1651e76fa9ecSHeejin Ahn 1652e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 1653e76fa9ecSHeejin Ahn // WebAssembly's rules. 1654e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 1655e76fa9ecSHeejin Ahn 1656e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 1657e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 1658e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 1659e76fa9ecSHeejin Ahn .getTargetTriple() 1660e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 166118c56a07SHeejin Ahn appendEndToFunction(MF, TII); 166232807932SDan Gohman 1663ed41945fSHeejin Ahn cleanupFunctionData(MF); 1664ed41945fSHeejin Ahn 16651aaa481fSHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified(); 1666950a13cfSDan Gohman return true; 1667950a13cfSDan Gohman } 1668