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 24*0b2bc69bSHeejin Ahn #include "Utils/WebAssemblyTypeUtilities.h" 25*0b2bc69bSHeejin Ahn #include "Utils/WebAssemblyUtilities.h" 266bda14b3SChandler Carruth #include "WebAssembly.h" 27e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h" 28ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 29276f9e8cSHeejin Ahn #include "WebAssemblySortRegion.h" 30950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 31c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h" 3232807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 33950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 34904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h" 359f770b36SHeejin Ahn #include "llvm/CodeGen/WasmEHFuncInfo.h" 36e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h" 37fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h" 38950a13cfSDan Gohman using namespace llvm; 39276f9e8cSHeejin Ahn using WebAssembly::SortRegionInfo; 40950a13cfSDan Gohman 41950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 42950a13cfSDan Gohman 43ed41945fSHeejin Ahn STATISTIC(NumCallUnwindMismatches, "Number of call unwind mismatches found"); 449f770b36SHeejin Ahn STATISTIC(NumCatchUnwindMismatches, "Number of catch unwind mismatches found"); 45c4ac74fbSHeejin Ahn 46950a13cfSDan Gohman namespace { 47950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 48117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 49950a13cfSDan Gohman 50950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 5132807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 52950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 53e76fa9ecSHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>(); 54950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 55950a13cfSDan Gohman } 56950a13cfSDan Gohman 57950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 58950a13cfSDan Gohman 59e76fa9ecSHeejin Ahn // For each block whose label represents the end of a scope, record the block 60e76fa9ecSHeejin Ahn // which holds the beginning of the scope. This will allow us to quickly skip 61e76fa9ecSHeejin Ahn // over scoped regions when walking blocks. 62e76fa9ecSHeejin Ahn SmallVector<MachineBasicBlock *, 8> ScopeTops; 631cc52357SHeejin Ahn void updateScopeTops(MachineBasicBlock *Begin, MachineBasicBlock *End) { 641cc52357SHeejin Ahn int EndNo = End->getNumber(); 651cc52357SHeejin Ahn if (!ScopeTops[EndNo] || ScopeTops[EndNo]->getNumber() > Begin->getNumber()) 661cc52357SHeejin Ahn ScopeTops[EndNo] = Begin; 671cc52357SHeejin Ahn } 68e76fa9ecSHeejin Ahn 69c4ac74fbSHeejin Ahn // Placing markers. 70e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF); 71e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB); 72e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB); 73e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB); 74ed41945fSHeejin Ahn 75ed41945fSHeejin Ahn // Exception handling related functions 76ed41945fSHeejin Ahn bool fixCallUnwindMismatches(MachineFunction &MF); 77ed41945fSHeejin Ahn bool fixCatchUnwindMismatches(MachineFunction &MF); 78ed41945fSHeejin Ahn void addTryDelegate(MachineInstr *RangeBegin, MachineInstr *RangeEnd, 79ed41945fSHeejin Ahn MachineBasicBlock *DelegateDest); 80ed41945fSHeejin Ahn void recalculateScopeTops(MachineFunction &MF); 81cf699b45SHeejin Ahn void removeUnnecessaryInstrs(MachineFunction &MF); 82ed41945fSHeejin Ahn 83ed41945fSHeejin Ahn // Wrap-up 842968611fSHeejin Ahn using EndMarkerInfo = 852968611fSHeejin Ahn std::pair<const MachineBasicBlock *, const MachineInstr *>; 862968611fSHeejin Ahn unsigned getBranchDepth(const SmallVectorImpl<EndMarkerInfo> &Stack, 872968611fSHeejin Ahn const MachineBasicBlock *MBB); 882968611fSHeejin Ahn unsigned getDelegateDepth(const SmallVectorImpl<EndMarkerInfo> &Stack, 89ed41945fSHeejin Ahn const MachineBasicBlock *MBB); 9035f5f797SHeejin Ahn unsigned 9135f5f797SHeejin Ahn getRethrowDepth(const SmallVectorImpl<EndMarkerInfo> &Stack, 9235f5f797SHeejin Ahn const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack); 93e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF); 94e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF); 95ed41945fSHeejin Ahn void cleanupFunctionData(MachineFunction &MF); 96e76fa9ecSHeejin Ahn 97ed41945fSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY) or DELEGATE 98ed41945fSHeejin Ahn // (in case of TRY). 99e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 100ed41945fSHeejin Ahn // For each END_(BLOCK|LOOP|TRY) or DELEGATE, the corresponding 101ed41945fSHeejin Ahn // BLOCK|LOOP|TRY. 102e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 103e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map 104e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 105e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map 106e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 107e76fa9ecSHeejin Ahn 108ed41945fSHeejin Ahn // We need an appendix block to place 'end_loop' or 'end_try' marker when the 109ed41945fSHeejin Ahn // loop / exception bottom block is the last block in a function 110c4ac74fbSHeejin Ahn MachineBasicBlock *AppendixBB = nullptr; 111c4ac74fbSHeejin Ahn MachineBasicBlock *getAppendixBlock(MachineFunction &MF) { 112c4ac74fbSHeejin Ahn if (!AppendixBB) { 113c4ac74fbSHeejin Ahn AppendixBB = MF.CreateMachineBasicBlock(); 114c4ac74fbSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 115c4ac74fbSHeejin Ahn AppendixBB->addSuccessor(AppendixBB); 116c4ac74fbSHeejin Ahn MF.push_back(AppendixBB); 117c4ac74fbSHeejin Ahn } 118c4ac74fbSHeejin Ahn return AppendixBB; 119c4ac74fbSHeejin Ahn } 120c4ac74fbSHeejin Ahn 121ed41945fSHeejin Ahn // Before running rewriteDepthImmediates function, 'delegate' has a BB as its 122ed41945fSHeejin Ahn // destination operand. getFakeCallerBlock() returns a fake BB that will be 123ed41945fSHeejin Ahn // used for the operand when 'delegate' needs to rethrow to the caller. This 124ed41945fSHeejin Ahn // will be rewritten as an immediate value that is the number of block depths 125ed41945fSHeejin Ahn // + 1 in rewriteDepthImmediates, and this fake BB will be removed at the end 126ed41945fSHeejin Ahn // of the pass. 127ed41945fSHeejin Ahn MachineBasicBlock *FakeCallerBB = nullptr; 128ed41945fSHeejin Ahn MachineBasicBlock *getFakeCallerBlock(MachineFunction &MF) { 129ed41945fSHeejin Ahn if (!FakeCallerBB) 130ed41945fSHeejin Ahn FakeCallerBB = MF.CreateMachineBasicBlock(); 131ed41945fSHeejin Ahn return FakeCallerBB; 132ed41945fSHeejin Ahn } 133ed41945fSHeejin Ahn 134cf699b45SHeejin Ahn // Helper functions to register / unregister scope information created by 135cf699b45SHeejin Ahn // marker instructions. 136e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End); 137e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End, 138e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad); 139cf699b45SHeejin Ahn void unregisterScope(MachineInstr *Begin); 140e76fa9ecSHeejin Ahn 141950a13cfSDan Gohman public: 142950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 143950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 144e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); } 145e76fa9ecSHeejin Ahn void releaseMemory() override; 146950a13cfSDan Gohman }; 147950a13cfSDan Gohman } // end anonymous namespace 148950a13cfSDan Gohman 149950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 15040926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 151c4ac74fbSHeejin Ahn "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false, 152f208f631SHeejin Ahn false) 15340926451SJacob Gravelle 154950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 155950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 156950a13cfSDan Gohman } 157950a13cfSDan Gohman 158b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 159b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 160b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 161b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 162b3aa1ecaSDan Gohman /// explicit mentions. 16318c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 16435e4a289SDan Gohman MachineBasicBlock *MBB) { 165b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 166b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 167b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 168b3aa1ecaSDan Gohman return true; 169b3aa1ecaSDan Gohman return false; 170b3aa1ecaSDan Gohman } 171b3aa1ecaSDan Gohman 172e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB, 173e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 174e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 175e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only 176e76fa9ecSHeejin Ahn // used for sanity checking. 1771cc52357SHeejin Ahn template <typename Container> 178e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 1791cc52357SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet, 1801cc52357SHeejin Ahn const Container &AfterSet) { 181e76fa9ecSHeejin Ahn auto InsertPos = MBB->end(); 182e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) { 183e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) { 184e76fa9ecSHeejin Ahn #ifndef NDEBUG 185e76fa9ecSHeejin Ahn // Sanity check 186e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 187e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos))); 188e76fa9ecSHeejin Ahn #endif 189e76fa9ecSHeejin Ahn break; 190e76fa9ecSHeejin Ahn } 191e76fa9ecSHeejin Ahn --InsertPos; 192e76fa9ecSHeejin Ahn } 193e76fa9ecSHeejin Ahn return InsertPos; 194e76fa9ecSHeejin Ahn } 195e76fa9ecSHeejin Ahn 196e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB, 197e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 198e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 199e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only 200e76fa9ecSHeejin Ahn // used for sanity checking. 2011cc52357SHeejin Ahn template <typename Container> 202e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 2031cc52357SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, const Container &BeforeSet, 2041cc52357SHeejin Ahn const Container &AfterSet) { 205e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin(); 206e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) { 207e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) { 208e76fa9ecSHeejin Ahn #ifndef NDEBUG 209e76fa9ecSHeejin Ahn // Sanity check 210e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 211e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos)); 212e76fa9ecSHeejin Ahn #endif 213e76fa9ecSHeejin Ahn break; 214e76fa9ecSHeejin Ahn } 215e76fa9ecSHeejin Ahn ++InsertPos; 216e76fa9ecSHeejin Ahn } 217e76fa9ecSHeejin Ahn return InsertPos; 218e76fa9ecSHeejin Ahn } 219e76fa9ecSHeejin Ahn 220e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 221e76fa9ecSHeejin Ahn MachineInstr *End) { 222e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End; 223e76fa9ecSHeejin Ahn EndToBegin[End] = Begin; 224e76fa9ecSHeejin Ahn } 225e76fa9ecSHeejin Ahn 226ed41945fSHeejin Ahn // When 'End' is not an 'end_try' but 'delegate, EHPad is nullptr. 227e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 228e76fa9ecSHeejin Ahn MachineInstr *End, 229e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) { 230e76fa9ecSHeejin Ahn registerScope(Begin, End); 231e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad; 232e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin; 233e76fa9ecSHeejin Ahn } 234e76fa9ecSHeejin Ahn 235cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 236cf699b45SHeejin Ahn assert(BeginToEnd.count(Begin)); 237cf699b45SHeejin Ahn MachineInstr *End = BeginToEnd[Begin]; 238cf699b45SHeejin Ahn assert(EndToBegin.count(End)); 239cf699b45SHeejin Ahn BeginToEnd.erase(Begin); 240cf699b45SHeejin Ahn EndToBegin.erase(End); 241cf699b45SHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 242cf699b45SHeejin Ahn if (EHPad) { 243cf699b45SHeejin Ahn assert(EHPadToTry.count(EHPad)); 244cf699b45SHeejin Ahn TryToEHPad.erase(Begin); 245cf699b45SHeejin Ahn EHPadToTry.erase(EHPad); 246cf699b45SHeejin Ahn } 247cf699b45SHeejin Ahn } 248cf699b45SHeejin Ahn 24932807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 250c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and 251c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later. 252e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 25344a5a4b1SHeejin Ahn assert(!MBB.isEHPad()); 254e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 255e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 256e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 257e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 258e76fa9ecSHeejin Ahn 2598fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2608fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2618fe7e86bSDan Gohman // which reduces overall stack height. 26232807932SDan Gohman MachineBasicBlock *Header = nullptr; 26332807932SDan Gohman bool IsBranchedTo = false; 26432807932SDan Gohman int MBBNumber = MBB.getNumber(); 265e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) { 26632807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 26732807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 26852e240a0SHeejin Ahn if (explicitlyBranchesTo(Pred, &MBB)) 26932807932SDan Gohman IsBranchedTo = true; 27032807932SDan Gohman } 271e76fa9ecSHeejin Ahn } 27232807932SDan Gohman if (!Header) 27332807932SDan Gohman return; 27432807932SDan Gohman if (!IsBranchedTo) 27532807932SDan Gohman return; 27632807932SDan Gohman 2778fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2785c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 2798fe7e86bSDan Gohman 2808fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2818fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2828fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2838fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2848fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2858fe7e86bSDan Gohman // Skip over an intervening scope. 2865c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 2878fe7e86bSDan Gohman } else { 2888fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 2898fe7e86bSDan Gohman Header = ScopeTop; 2908fe7e86bSDan Gohman break; 2918fe7e86bSDan Gohman } 2928fe7e86bSDan Gohman } 2938fe7e86bSDan Gohman } 2948fe7e86bSDan Gohman 2958fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 296e76fa9ecSHeejin Ahn 297e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 298e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 299e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 300e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 301e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 30244a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 30344a5a4b1SHeejin Ahn // loop is above MBB, it should be after the BLOCK, because the loop is 30444a5a4b1SHeejin Ahn // nested in this BLOCK. Otherwise it should be before the BLOCK. 30544a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 30644a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 30744a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 308e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 309e76fa9ecSHeejin Ahn #ifndef NDEBUG 310e76fa9ecSHeejin Ahn else 311e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 312e76fa9ecSHeejin Ahn #endif 313e76fa9ecSHeejin Ahn } 314e76fa9ecSHeejin Ahn 315834debffSHeejin Ahn // If there is a previously placed BLOCK/TRY marker and its corresponding 316834debffSHeejin Ahn // END marker is before the current BLOCK's END marker, that should be 317834debffSHeejin Ahn // placed after this BLOCK. Otherwise it should be placed before this BLOCK 318834debffSHeejin Ahn // marker. 31944a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 320834debffSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) { 321834debffSHeejin Ahn if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber()) 322e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 323834debffSHeejin Ahn #ifndef NDEBUG 324834debffSHeejin Ahn else 325834debffSHeejin Ahn BeforeSet.insert(&MI); 326834debffSHeejin Ahn #endif 327834debffSHeejin Ahn } 328e76fa9ecSHeejin Ahn 329e76fa9ecSHeejin Ahn #ifndef NDEBUG 330e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 331e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 332e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 333e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 334e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 335e76fa9ecSHeejin Ahn #endif 336e76fa9ecSHeejin Ahn 337e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK. 338e76fa9ecSHeejin Ahn if (MI.isTerminator()) 339e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 340e76fa9ecSHeejin Ahn } 341e76fa9ecSHeejin Ahn 342e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK. 343e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 344e76fa9ecSHeejin Ahn --I) { 345409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 346409b4391SYury Delendik continue; 347e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 348e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 349e76fa9ecSHeejin Ahn else 350e76fa9ecSHeejin Ahn break; 35132807932SDan Gohman } 35232807932SDan Gohman 3538fe7e86bSDan Gohman // Add the BLOCK. 3542cb27072SThomas Lively WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void; 35518c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 35692401cc1SHeejin Ahn MachineInstr *Begin = 35792401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3582726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 359d6f48786SHeejin Ahn .addImm(int64_t(ReturnType)); 3601d68e80fSDan Gohman 361e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 362e76fa9ecSHeejin Ahn BeforeSet.clear(); 363e76fa9ecSHeejin Ahn AfterSet.clear(); 364e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 365e76fa9ecSHeejin Ahn #ifndef NDEBUG 366e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 367e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 368e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 369e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 370e76fa9ecSHeejin Ahn #endif 371e76fa9ecSHeejin Ahn 372e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 373e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 374e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 375e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 376e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 377e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 378e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 379e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 380e76fa9ecSHeejin Ahn #ifndef NDEBUG 381e76fa9ecSHeejin Ahn else 382e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 383e76fa9ecSHeejin Ahn #endif 384e76fa9ecSHeejin Ahn } 385e76fa9ecSHeejin Ahn } 386e76fa9ecSHeejin Ahn 3871d68e80fSDan Gohman // Mark the end of the block. 38818c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 38910b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3902726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 391e76fa9ecSHeejin Ahn registerScope(Begin, End); 3928fe7e86bSDan Gohman 3938fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3941cc52357SHeejin Ahn updateScopeTops(Header, &MBB); 395950a13cfSDan Gohman } 396950a13cfSDan Gohman 3978fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 398e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 399e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 400e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 401276f9e8cSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 402276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI); 403e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 404e76fa9ecSHeejin Ahn 4058fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 4068fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 4078fe7e86bSDan Gohman return; 4088fe7e86bSDan Gohman 4098fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 4108fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 411276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(Loop); 4125c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 413e3e4a5ffSDan Gohman if (Iter == MF.end()) { 414c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4155c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 416e3e4a5ffSDan Gohman } 4178fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 418f6857223SDan Gohman 419e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 420e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 421e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 422e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 423e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 424e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 425e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 426e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 427e76fa9ecSHeejin Ahn #ifndef NDEBUG 428e76fa9ecSHeejin Ahn else 429e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 430e76fa9ecSHeejin Ahn #endif 431e76fa9ecSHeejin Ahn } 432e76fa9ecSHeejin Ahn 433e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 43418c56a07SHeejin Ahn auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 43510b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4362726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4372cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 4381d68e80fSDan Gohman 439e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 440e76fa9ecSHeejin Ahn BeforeSet.clear(); 441e76fa9ecSHeejin Ahn AfterSet.clear(); 442e76fa9ecSHeejin Ahn #ifndef NDEBUG 443e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 444e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 445e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 446e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 447e76fa9ecSHeejin Ahn #endif 448e76fa9ecSHeejin Ahn 449e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 450e76fa9ecSHeejin Ahn // the loop end as its location). 45118c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 45267f74aceSHeejin Ahn DebugLoc EndDL = AfterLoop->pred_empty() 45367f74aceSHeejin Ahn ? DebugLoc() 45467f74aceSHeejin Ahn : (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 455e76fa9ecSHeejin Ahn MachineInstr *End = 456e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 457e76fa9ecSHeejin Ahn registerScope(Begin, End); 4588fe7e86bSDan Gohman 4598fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4608fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 461442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4621cc52357SHeejin Ahn updateScopeTops(&MBB, AfterLoop); 463e3e4a5ffSDan Gohman } 464950a13cfSDan Gohman 465e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 46644a5a4b1SHeejin Ahn assert(MBB.isEHPad()); 467e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 468e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 469e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 470276f9e8cSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 471e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 472276f9e8cSHeejin Ahn SortRegionInfo SRI(MLI, WEI); 473e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 474e76fa9ecSHeejin Ahn 475e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 476e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 477e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 478e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 479e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 480e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 48118c56a07SHeejin Ahn assert(!explicitlyBranchesTo(Pred, &MBB) && 482e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 483e76fa9ecSHeejin Ahn } 484e76fa9ecSHeejin Ahn } 485e76fa9ecSHeejin Ahn if (!Header) 486e76fa9ecSHeejin Ahn return; 487e76fa9ecSHeejin Ahn 488e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 489e76fa9ecSHeejin Ahn // end. 490e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 491e76fa9ecSHeejin Ahn assert(WE); 492276f9e8cSHeejin Ahn MachineBasicBlock *Bottom = SRI.getBottom(WE); 493e76fa9ecSHeejin Ahn 4945c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 495e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 496c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4975c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 498e76fa9ecSHeejin Ahn } 49920cf0749SHeejin Ahn MachineBasicBlock *Cont = &*Iter; 500e76fa9ecSHeejin Ahn 50120cf0749SHeejin Ahn assert(Cont != &MF.front()); 5025c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 503e76fa9ecSHeejin Ahn 504e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 505e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 506e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 507e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 508e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 509e76fa9ecSHeejin Ahn // Skip over an intervening scope. 5105c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 511e76fa9ecSHeejin Ahn } else { 512e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 513e76fa9ecSHeejin Ahn Header = ScopeTop; 514e76fa9ecSHeejin Ahn break; 515e76fa9ecSHeejin Ahn } 516e76fa9ecSHeejin Ahn } 517e76fa9ecSHeejin Ahn } 518e76fa9ecSHeejin Ahn 519e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 520e76fa9ecSHeejin Ahn 52144a5a4b1SHeejin Ahn // Instructions that should go before the TRY. 522e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 52344a5a4b1SHeejin Ahn // Instructions that should go after the TRY. 524e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 525e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 52644a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 52744a5a4b1SHeejin Ahn // loop is above MBB, it should be after the TRY, because the loop is nested 52844a5a4b1SHeejin Ahn // in this TRY. Otherwise it should be before the TRY. 529e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 53044a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 53144a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 532e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 533e76fa9ecSHeejin Ahn #ifndef NDEBUG 534e76fa9ecSHeejin Ahn else 535e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 536e76fa9ecSHeejin Ahn #endif 537e76fa9ecSHeejin Ahn } 538e76fa9ecSHeejin Ahn 53944a5a4b1SHeejin Ahn // All previously inserted BLOCK/TRY markers should be after the TRY because 54044a5a4b1SHeejin Ahn // they are all nested trys. 54144a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 54244a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 543e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 544e76fa9ecSHeejin Ahn 545e76fa9ecSHeejin Ahn #ifndef NDEBUG 54644a5a4b1SHeejin Ahn // All END_(BLOCK/LOOP/TRY) markers should be before the TRY. 54744a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 54844a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 549e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 550e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 551e76fa9ecSHeejin Ahn #endif 552e76fa9ecSHeejin Ahn 553e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 554e76fa9ecSHeejin Ahn if (MI.isTerminator()) 555e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 556e76fa9ecSHeejin Ahn } 557e76fa9ecSHeejin Ahn 5586a37c5d6SHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 5596a37c5d6SHeejin Ahn // contain the call within it. So the call should go after the TRY. The 5606a37c5d6SHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 5616a37c5d6SHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 5626a37c5d6SHeejin Ahn // throw. 5636a37c5d6SHeejin Ahn MachineInstr *ThrowingCall = nullptr; 5646a37c5d6SHeejin Ahn if (MBB.isPredecessor(Header)) { 5656a37c5d6SHeejin Ahn auto TermPos = Header->getFirstTerminator(); 5666a37c5d6SHeejin Ahn if (TermPos == Header->end() || 5676a37c5d6SHeejin Ahn TermPos->getOpcode() != WebAssembly::RETHROW) { 5686a37c5d6SHeejin Ahn for (auto &MI : reverse(*Header)) { 5696a37c5d6SHeejin Ahn if (MI.isCall()) { 5706a37c5d6SHeejin Ahn AfterSet.insert(&MI); 5716a37c5d6SHeejin Ahn ThrowingCall = &MI; 5726a37c5d6SHeejin Ahn // Possibly throwing calls are usually wrapped by EH_LABEL 5736a37c5d6SHeejin Ahn // instructions. We don't want to split them and the call. 5746a37c5d6SHeejin Ahn if (MI.getIterator() != Header->begin() && 5756a37c5d6SHeejin Ahn std::prev(MI.getIterator())->isEHLabel()) { 5766a37c5d6SHeejin Ahn AfterSet.insert(&*std::prev(MI.getIterator())); 5776a37c5d6SHeejin Ahn ThrowingCall = &*std::prev(MI.getIterator()); 5786a37c5d6SHeejin Ahn } 5796a37c5d6SHeejin Ahn break; 5806a37c5d6SHeejin Ahn } 5816a37c5d6SHeejin Ahn } 5826a37c5d6SHeejin Ahn } 5836a37c5d6SHeejin Ahn } 5846a37c5d6SHeejin Ahn 585e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 5866a37c5d6SHeejin Ahn // For BLOCK placement, we start the search from the previous instruction of a 5876a37c5d6SHeejin Ahn // BB's terminator, but in TRY's case, we should start from the previous 5886a37c5d6SHeejin Ahn // instruction of a call that can throw, or a EH_LABEL that precedes the call, 5896a37c5d6SHeejin Ahn // because the return values of the call's previous instructions can be 5906a37c5d6SHeejin Ahn // stackified and consumed by the throwing call. 5916a37c5d6SHeejin Ahn auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall) 5926a37c5d6SHeejin Ahn : Header->getFirstTerminator(); 5936a37c5d6SHeejin Ahn for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) { 594409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 595409b4391SYury Delendik continue; 596e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 597e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 598e76fa9ecSHeejin Ahn else 599e76fa9ecSHeejin Ahn break; 600e76fa9ecSHeejin Ahn } 601e76fa9ecSHeejin Ahn 602e76fa9ecSHeejin Ahn // Add the TRY. 60318c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 604e76fa9ecSHeejin Ahn MachineInstr *Begin = 605e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 606e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 6072cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 608e76fa9ecSHeejin Ahn 609e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 610e76fa9ecSHeejin Ahn BeforeSet.clear(); 611e76fa9ecSHeejin Ahn AfterSet.clear(); 61220cf0749SHeejin Ahn for (const auto &MI : *Cont) { 613e76fa9ecSHeejin Ahn #ifndef NDEBUG 61444a5a4b1SHeejin Ahn // END_TRY should precede existing LOOP and BLOCK markers. 61544a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 61644a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::BLOCK) 617e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 618e76fa9ecSHeejin Ahn 619e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 620e76fa9ecSHeejin Ahn // this one. 621e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 622e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 623e76fa9ecSHeejin Ahn #endif 624e76fa9ecSHeejin Ahn 625e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 626e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 627e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 628e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 629e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 630222718fdSHeejin Ahn // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they 631222718fdSHeejin Ahn // are in the same BB, LOOP is always before TRY. 632222718fdSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber()) 633e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 634e76fa9ecSHeejin Ahn #ifndef NDEBUG 635e76fa9ecSHeejin Ahn else 636e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 637e76fa9ecSHeejin Ahn #endif 638e76fa9ecSHeejin Ahn } 63944a5a4b1SHeejin Ahn 64044a5a4b1SHeejin Ahn // It is not possible for an END_BLOCK to be already in this block. 641e76fa9ecSHeejin Ahn } 642e76fa9ecSHeejin Ahn 643e76fa9ecSHeejin Ahn // Mark the end of the TRY. 64420cf0749SHeejin Ahn InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 645e76fa9ecSHeejin Ahn MachineInstr *End = 64620cf0749SHeejin Ahn BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 647e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 648e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 649e76fa9ecSHeejin Ahn 65082da1ffcSHeejin Ahn // Track the farthest-spanning scope that ends at this point. We create two 65182da1ffcSHeejin Ahn // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 65282da1ffcSHeejin Ahn // with 'try'). We need to create 'catch' -> 'try' mapping here too because 65382da1ffcSHeejin Ahn // markers should not span across 'catch'. For example, this should not 65482da1ffcSHeejin Ahn // happen: 65582da1ffcSHeejin Ahn // 65682da1ffcSHeejin Ahn // try 65782da1ffcSHeejin Ahn // block --| (X) 65882da1ffcSHeejin Ahn // catch | 65982da1ffcSHeejin Ahn // end_block --| 66082da1ffcSHeejin Ahn // end_try 6611cc52357SHeejin Ahn for (auto *End : {&MBB, Cont}) 6621cc52357SHeejin Ahn updateScopeTops(Header, End); 66382da1ffcSHeejin Ahn } 664e76fa9ecSHeejin Ahn 665cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 666cf699b45SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 667cf699b45SHeejin Ahn 668cf699b45SHeejin Ahn // When there is an unconditional branch right before a catch instruction and 669cf699b45SHeejin Ahn // it branches to the end of end_try marker, we don't need the branch, because 670cf699b45SHeejin Ahn // it there is no exception, the control flow transfers to that point anyway. 671cf699b45SHeejin Ahn // bb0: 672cf699b45SHeejin Ahn // try 673cf699b45SHeejin Ahn // ... 674cf699b45SHeejin Ahn // br bb2 <- Not necessary 675c93b9559SHeejin Ahn // bb1 (ehpad): 676cf699b45SHeejin Ahn // catch 677cf699b45SHeejin Ahn // ... 678c93b9559SHeejin Ahn // bb2: <- Continuation BB 679cf699b45SHeejin Ahn // end 680c93b9559SHeejin Ahn // 681c93b9559SHeejin Ahn // A more involved case: When the BB where 'end' is located is an another EH 682c93b9559SHeejin Ahn // pad, the Cont (= continuation) BB is that EH pad's 'end' BB. For example, 683c93b9559SHeejin Ahn // bb0: 684c93b9559SHeejin Ahn // try 685c93b9559SHeejin Ahn // try 686c93b9559SHeejin Ahn // ... 687c93b9559SHeejin Ahn // br bb3 <- Not necessary 688c93b9559SHeejin Ahn // bb1 (ehpad): 689c93b9559SHeejin Ahn // catch 690c93b9559SHeejin Ahn // bb2 (ehpad): 691c93b9559SHeejin Ahn // end 692c93b9559SHeejin Ahn // catch 693c93b9559SHeejin Ahn // ... 694c93b9559SHeejin Ahn // bb3: <- Continuation BB 695c93b9559SHeejin Ahn // end 696c93b9559SHeejin Ahn // 697c93b9559SHeejin Ahn // When the EH pad at hand is bb1, its matching end_try is in bb2. But it is 698c93b9559SHeejin Ahn // another EH pad, so bb0's continuation BB becomes bb3. So 'br bb3' in the 699c93b9559SHeejin Ahn // code can be deleted. This is why we run 'while' until 'Cont' is not an EH 700c93b9559SHeejin Ahn // pad. 701cf699b45SHeejin Ahn for (auto &MBB : MF) { 702cf699b45SHeejin Ahn if (!MBB.isEHPad()) 703cf699b45SHeejin Ahn continue; 704cf699b45SHeejin Ahn 705cf699b45SHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 706cf699b45SHeejin Ahn SmallVector<MachineOperand, 4> Cond; 7075c644c9bSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 708c93b9559SHeejin Ahn 709c93b9559SHeejin Ahn MachineBasicBlock *Cont = &MBB; 710c93b9559SHeejin Ahn while (Cont->isEHPad()) { 711c93b9559SHeejin Ahn MachineInstr *Try = EHPadToTry[Cont]; 712c93b9559SHeejin Ahn MachineInstr *EndTry = BeginToEnd[Try]; 713ed41945fSHeejin Ahn // We started from an EH pad, so the end marker cannot be a delegate 714ed41945fSHeejin Ahn assert(EndTry->getOpcode() != WebAssembly::DELEGATE); 715c93b9559SHeejin Ahn Cont = EndTry->getParent(); 716c93b9559SHeejin Ahn } 717c93b9559SHeejin Ahn 718cf699b45SHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 7193fe6ea46SHeejin Ahn // This condition means either 7203fe6ea46SHeejin Ahn // 1. This BB ends with a single unconditional branch whose destinaion is 7213fe6ea46SHeejin Ahn // Cont. 7223fe6ea46SHeejin Ahn // 2. This BB ends with a conditional branch followed by an unconditional 7233fe6ea46SHeejin Ahn // branch, and the unconditional branch's destination is Cont. 7243fe6ea46SHeejin Ahn // In both cases, we want to remove the last (= unconditional) branch. 725cf699b45SHeejin Ahn if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 7263fe6ea46SHeejin Ahn (!Cond.empty() && FBB && FBB == Cont))) { 7273fe6ea46SHeejin Ahn bool ErasedUncondBr = false; 728a5099ad9SHeejin Ahn (void)ErasedUncondBr; 7293fe6ea46SHeejin Ahn for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin(); 7303fe6ea46SHeejin Ahn I != E; --I) { 7313fe6ea46SHeejin Ahn auto PrevI = std::prev(I); 7323fe6ea46SHeejin Ahn if (PrevI->isTerminator()) { 7333fe6ea46SHeejin Ahn assert(PrevI->getOpcode() == WebAssembly::BR); 7343fe6ea46SHeejin Ahn PrevI->eraseFromParent(); 7353fe6ea46SHeejin Ahn ErasedUncondBr = true; 7363fe6ea46SHeejin Ahn break; 7373fe6ea46SHeejin Ahn } 7383fe6ea46SHeejin Ahn } 7393fe6ea46SHeejin Ahn assert(ErasedUncondBr && "Unconditional branch not erased!"); 7403fe6ea46SHeejin Ahn } 741cf699b45SHeejin Ahn } 742cf699b45SHeejin Ahn 743cf699b45SHeejin Ahn // When there are block / end_block markers that overlap with try / end_try 744cf699b45SHeejin Ahn // markers, and the block and try markers' return types are the same, the 745cf699b45SHeejin Ahn // block /end_block markers are not necessary, because try / end_try markers 746cf699b45SHeejin Ahn // also can serve as boundaries for branches. 747cf699b45SHeejin Ahn // block <- Not necessary 748cf699b45SHeejin Ahn // try 749cf699b45SHeejin Ahn // ... 750cf699b45SHeejin Ahn // catch 751cf699b45SHeejin Ahn // ... 752cf699b45SHeejin Ahn // end 753cf699b45SHeejin Ahn // end <- Not necessary 754cf699b45SHeejin Ahn SmallVector<MachineInstr *, 32> ToDelete; 755cf699b45SHeejin Ahn for (auto &MBB : MF) { 756cf699b45SHeejin Ahn for (auto &MI : MBB) { 757cf699b45SHeejin Ahn if (MI.getOpcode() != WebAssembly::TRY) 758cf699b45SHeejin Ahn continue; 759cf699b45SHeejin Ahn MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 760ed41945fSHeejin Ahn if (EndTry->getOpcode() == WebAssembly::DELEGATE) 761ed41945fSHeejin Ahn continue; 762ed41945fSHeejin Ahn 763cf699b45SHeejin Ahn MachineBasicBlock *TryBB = Try->getParent(); 764cf699b45SHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent(); 765cf699b45SHeejin Ahn int64_t RetType = Try->getOperand(0).getImm(); 7665c644c9bSHeejin Ahn for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 767cf699b45SHeejin Ahn B != TryBB->begin() && E != Cont->end() && 768cf699b45SHeejin Ahn std::prev(B)->getOpcode() == WebAssembly::BLOCK && 769cf699b45SHeejin Ahn E->getOpcode() == WebAssembly::END_BLOCK && 770cf699b45SHeejin Ahn std::prev(B)->getOperand(0).getImm() == RetType; 771cf699b45SHeejin Ahn --B, ++E) { 772cf699b45SHeejin Ahn ToDelete.push_back(&*std::prev(B)); 773cf699b45SHeejin Ahn ToDelete.push_back(&*E); 774cf699b45SHeejin Ahn } 775cf699b45SHeejin Ahn } 776cf699b45SHeejin Ahn } 777cf699b45SHeejin Ahn for (auto *MI : ToDelete) { 778cf699b45SHeejin Ahn if (MI->getOpcode() == WebAssembly::BLOCK) 779cf699b45SHeejin Ahn unregisterScope(MI); 780cf699b45SHeejin Ahn MI->eraseFromParent(); 781cf699b45SHeejin Ahn } 782cf699b45SHeejin Ahn } 783cf699b45SHeejin Ahn 78483c26eaeSHeejin Ahn // Get the appropriate copy opcode for the given register class. 78583c26eaeSHeejin Ahn static unsigned getCopyOpcode(const TargetRegisterClass *RC) { 78683c26eaeSHeejin Ahn if (RC == &WebAssembly::I32RegClass) 78783c26eaeSHeejin Ahn return WebAssembly::COPY_I32; 78883c26eaeSHeejin Ahn if (RC == &WebAssembly::I64RegClass) 78983c26eaeSHeejin Ahn return WebAssembly::COPY_I64; 79083c26eaeSHeejin Ahn if (RC == &WebAssembly::F32RegClass) 79183c26eaeSHeejin Ahn return WebAssembly::COPY_F32; 79283c26eaeSHeejin Ahn if (RC == &WebAssembly::F64RegClass) 79383c26eaeSHeejin Ahn return WebAssembly::COPY_F64; 79483c26eaeSHeejin Ahn if (RC == &WebAssembly::V128RegClass) 79583c26eaeSHeejin Ahn return WebAssembly::COPY_V128; 79660653e24SHeejin Ahn if (RC == &WebAssembly::FUNCREFRegClass) 79760653e24SHeejin Ahn return WebAssembly::COPY_FUNCREF; 79860653e24SHeejin Ahn if (RC == &WebAssembly::EXTERNREFRegClass) 79960653e24SHeejin Ahn return WebAssembly::COPY_EXTERNREF; 80083c26eaeSHeejin Ahn llvm_unreachable("Unexpected register class"); 80183c26eaeSHeejin Ahn } 80283c26eaeSHeejin Ahn 80361d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that 80461d5c76aSHeejin Ahn // have their uses in Split. 805ed41945fSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, 806ed41945fSHeejin Ahn MachineBasicBlock &Split) { 8071cc52357SHeejin Ahn MachineFunction &MF = *MBB.getParent(); 8081cc52357SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 8091cc52357SHeejin Ahn auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 8101cc52357SHeejin Ahn auto &MRI = MF.getRegInfo(); 8111cc52357SHeejin Ahn 81261d5c76aSHeejin Ahn for (auto &MI : Split) { 81361d5c76aSHeejin Ahn for (auto &MO : MI.explicit_uses()) { 81461d5c76aSHeejin Ahn if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg())) 81561d5c76aSHeejin Ahn continue; 81661d5c76aSHeejin Ahn if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg())) 81761d5c76aSHeejin Ahn if (Def->getParent() == &MBB) 81861d5c76aSHeejin Ahn MFI.unstackifyVReg(MO.getReg()); 81961d5c76aSHeejin Ahn } 82061d5c76aSHeejin Ahn } 82183c26eaeSHeejin Ahn 82283c26eaeSHeejin Ahn // In RegStackify, when a register definition is used multiple times, 82383c26eaeSHeejin Ahn // Reg = INST ... 82483c26eaeSHeejin Ahn // INST ..., Reg, ... 82583c26eaeSHeejin Ahn // INST ..., Reg, ... 82683c26eaeSHeejin Ahn // INST ..., Reg, ... 82783c26eaeSHeejin Ahn // 82883c26eaeSHeejin Ahn // we introduce a TEE, which has the following form: 82983c26eaeSHeejin Ahn // DefReg = INST ... 83083c26eaeSHeejin Ahn // TeeReg, Reg = TEE_... DefReg 83183c26eaeSHeejin Ahn // INST ..., TeeReg, ... 83283c26eaeSHeejin Ahn // INST ..., Reg, ... 83383c26eaeSHeejin Ahn // INST ..., Reg, ... 83483c26eaeSHeejin Ahn // with DefReg and TeeReg stackified but Reg not stackified. 83583c26eaeSHeejin Ahn // 83683c26eaeSHeejin Ahn // But the invariant that TeeReg should be stackified can be violated while we 83783c26eaeSHeejin Ahn // unstackify registers in the split BB above. In this case, we convert TEEs 83883c26eaeSHeejin Ahn // into two COPYs. This COPY will be eventually eliminated in ExplicitLocals. 83983c26eaeSHeejin Ahn // DefReg = INST ... 84083c26eaeSHeejin Ahn // TeeReg = COPY DefReg 84183c26eaeSHeejin Ahn // Reg = COPY DefReg 84283c26eaeSHeejin Ahn // INST ..., TeeReg, ... 84383c26eaeSHeejin Ahn // INST ..., Reg, ... 84483c26eaeSHeejin Ahn // INST ..., Reg, ... 84583c26eaeSHeejin Ahn for (auto I = MBB.begin(), E = MBB.end(); I != E;) { 84683c26eaeSHeejin Ahn MachineInstr &MI = *I++; 84783c26eaeSHeejin Ahn if (!WebAssembly::isTee(MI.getOpcode())) 84883c26eaeSHeejin Ahn continue; 84983c26eaeSHeejin Ahn Register TeeReg = MI.getOperand(0).getReg(); 85083c26eaeSHeejin Ahn Register Reg = MI.getOperand(1).getReg(); 85183c26eaeSHeejin Ahn Register DefReg = MI.getOperand(2).getReg(); 85283c26eaeSHeejin Ahn if (!MFI.isVRegStackified(TeeReg)) { 85383c26eaeSHeejin Ahn // Now we are not using TEE anymore, so unstackify DefReg too 85483c26eaeSHeejin Ahn MFI.unstackifyVReg(DefReg); 85583c26eaeSHeejin Ahn unsigned CopyOpc = getCopyOpcode(MRI.getRegClass(DefReg)); 85683c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), TeeReg) 85783c26eaeSHeejin Ahn .addReg(DefReg); 85883c26eaeSHeejin Ahn BuildMI(MBB, &MI, MI.getDebugLoc(), TII.get(CopyOpc), Reg).addReg(DefReg); 85983c26eaeSHeejin Ahn MI.eraseFromParent(); 86083c26eaeSHeejin Ahn } 86183c26eaeSHeejin Ahn } 86261d5c76aSHeejin Ahn } 86361d5c76aSHeejin Ahn 864ed41945fSHeejin Ahn // Wrap the given range of instruction with try-delegate. RangeBegin and 865ed41945fSHeejin Ahn // RangeEnd are inclusive. 866ed41945fSHeejin Ahn void WebAssemblyCFGStackify::addTryDelegate(MachineInstr *RangeBegin, 867ed41945fSHeejin Ahn MachineInstr *RangeEnd, 868ed41945fSHeejin Ahn MachineBasicBlock *DelegateDest) { 869ed41945fSHeejin Ahn auto *BeginBB = RangeBegin->getParent(); 870ed41945fSHeejin Ahn auto *EndBB = RangeEnd->getParent(); 871ed41945fSHeejin Ahn MachineFunction &MF = *BeginBB->getParent(); 872ed41945fSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 873ed41945fSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 874ed41945fSHeejin Ahn 875ed41945fSHeejin Ahn // Local expression tree before the first call of this range should go 876ed41945fSHeejin Ahn // after the nested TRY. 877ed41945fSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 878ed41945fSHeejin Ahn AfterSet.insert(RangeBegin); 879ed41945fSHeejin Ahn for (auto I = MachineBasicBlock::iterator(RangeBegin), E = BeginBB->begin(); 880ed41945fSHeejin Ahn I != E; --I) { 881ed41945fSHeejin Ahn if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 882ed41945fSHeejin Ahn continue; 883ed41945fSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 884ed41945fSHeejin Ahn AfterSet.insert(&*std::prev(I)); 885ed41945fSHeejin Ahn else 886ed41945fSHeejin Ahn break; 887ed41945fSHeejin Ahn } 888ed41945fSHeejin Ahn 889ed41945fSHeejin Ahn // Create the nested try instruction. 890ed41945fSHeejin Ahn auto TryPos = getLatestInsertPos( 891ed41945fSHeejin Ahn BeginBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet); 892ed41945fSHeejin Ahn MachineInstr *Try = BuildMI(*BeginBB, TryPos, RangeBegin->getDebugLoc(), 893ed41945fSHeejin Ahn TII.get(WebAssembly::TRY)) 894ed41945fSHeejin Ahn .addImm(int64_t(WebAssembly::BlockType::Void)); 895ed41945fSHeejin Ahn 896ed41945fSHeejin Ahn // Create a BB to insert the 'delegate' instruction. 897ed41945fSHeejin Ahn MachineBasicBlock *DelegateBB = MF.CreateMachineBasicBlock(); 898ed41945fSHeejin Ahn // If the destination of 'delegate' is not the caller, adds the destination to 899ed41945fSHeejin Ahn // the BB's successors. 900ed41945fSHeejin Ahn if (DelegateDest != FakeCallerBB) 901ed41945fSHeejin Ahn DelegateBB->addSuccessor(DelegateDest); 902ed41945fSHeejin Ahn 903ed41945fSHeejin Ahn auto SplitPos = std::next(RangeEnd->getIterator()); 904ed41945fSHeejin Ahn if (SplitPos == EndBB->end()) { 905ed41945fSHeejin Ahn // If the range's end instruction is at the end of the BB, insert the new 906ed41945fSHeejin Ahn // delegate BB after the current BB. 907ed41945fSHeejin Ahn MF.insert(std::next(EndBB->getIterator()), DelegateBB); 908ed41945fSHeejin Ahn EndBB->addSuccessor(DelegateBB); 909ed41945fSHeejin Ahn 910ed41945fSHeejin Ahn } else { 9119f770b36SHeejin Ahn // When the split pos is in the middle of a BB, we split the BB into two and 9129f770b36SHeejin Ahn // put the 'delegate' BB in between. We normally create a split BB and make 9139f770b36SHeejin Ahn // it a successor of the original BB (PostSplit == true), but in case the BB 9149f770b36SHeejin Ahn // is an EH pad and the split pos is before 'catch', we should preserve the 9159f770b36SHeejin Ahn // BB's property, including that it is an EH pad, in the later part of the 9169f770b36SHeejin Ahn // BB, where 'catch' is. In this case we set PostSplit to false. 9179f770b36SHeejin Ahn bool PostSplit = true; 9189f770b36SHeejin Ahn if (EndBB->isEHPad()) { 9199f770b36SHeejin Ahn for (auto I = MachineBasicBlock::iterator(SplitPos), E = EndBB->end(); 9209f770b36SHeejin Ahn I != E; ++I) { 9219f770b36SHeejin Ahn if (WebAssembly::isCatch(I->getOpcode())) { 9229f770b36SHeejin Ahn PostSplit = false; 9239f770b36SHeejin Ahn break; 9249f770b36SHeejin Ahn } 9259f770b36SHeejin Ahn } 9269f770b36SHeejin Ahn } 9279f770b36SHeejin Ahn 9289f770b36SHeejin Ahn MachineBasicBlock *PreBB = nullptr, *PostBB = nullptr; 9299f770b36SHeejin Ahn if (PostSplit) { 930ed41945fSHeejin Ahn // If the range's end instruction is in the middle of the BB, we split the 931ed41945fSHeejin Ahn // BB into two and insert the delegate BB in between. 932ed41945fSHeejin Ahn // - Before: 933ed41945fSHeejin Ahn // bb: 934ed41945fSHeejin Ahn // range_end 935ed41945fSHeejin Ahn // other_insts 936ed41945fSHeejin Ahn // 937ed41945fSHeejin Ahn // - After: 938ed41945fSHeejin Ahn // pre_bb: (previous 'bb') 939ed41945fSHeejin Ahn // range_end 940ed41945fSHeejin Ahn // delegate_bb: (new) 941ed41945fSHeejin Ahn // delegate 942ed41945fSHeejin Ahn // post_bb: (new) 943ed41945fSHeejin Ahn // other_insts 9449f770b36SHeejin Ahn PreBB = EndBB; 9459f770b36SHeejin Ahn PostBB = MF.CreateMachineBasicBlock(); 946ed41945fSHeejin Ahn MF.insert(std::next(PreBB->getIterator()), PostBB); 947ed41945fSHeejin Ahn MF.insert(std::next(PreBB->getIterator()), DelegateBB); 948ed41945fSHeejin Ahn PostBB->splice(PostBB->end(), PreBB, SplitPos, PreBB->end()); 949ed41945fSHeejin Ahn PostBB->transferSuccessors(PreBB); 9509f770b36SHeejin Ahn } else { 9519f770b36SHeejin Ahn // - Before: 9529f770b36SHeejin Ahn // ehpad: 9539f770b36SHeejin Ahn // range_end 9549f770b36SHeejin Ahn // catch 9559f770b36SHeejin Ahn // ... 9569f770b36SHeejin Ahn // 9579f770b36SHeejin Ahn // - After: 9589f770b36SHeejin Ahn // pre_bb: (new) 9599f770b36SHeejin Ahn // range_end 9609f770b36SHeejin Ahn // delegate_bb: (new) 9619f770b36SHeejin Ahn // delegate 9629f770b36SHeejin Ahn // post_bb: (previous 'ehpad') 9639f770b36SHeejin Ahn // catch 9649f770b36SHeejin Ahn // ... 9659f770b36SHeejin Ahn assert(EndBB->isEHPad()); 9669f770b36SHeejin Ahn PreBB = MF.CreateMachineBasicBlock(); 9679f770b36SHeejin Ahn PostBB = EndBB; 9689f770b36SHeejin Ahn MF.insert(PostBB->getIterator(), PreBB); 9699f770b36SHeejin Ahn MF.insert(PostBB->getIterator(), DelegateBB); 9709f770b36SHeejin Ahn PreBB->splice(PreBB->end(), PostBB, PostBB->begin(), SplitPos); 9719f770b36SHeejin Ahn // We don't need to transfer predecessors of the EH pad to 'PreBB', 9729f770b36SHeejin Ahn // because an EH pad's predecessors are all through unwind edges and they 9739f770b36SHeejin Ahn // should still unwind to the EH pad, not PreBB. 9749f770b36SHeejin Ahn } 975ed41945fSHeejin Ahn unstackifyVRegsUsedInSplitBB(*PreBB, *PostBB); 976ed41945fSHeejin Ahn PreBB->addSuccessor(DelegateBB); 977ed41945fSHeejin Ahn PreBB->addSuccessor(PostBB); 978ed41945fSHeejin Ahn } 979ed41945fSHeejin Ahn 980ed41945fSHeejin Ahn // Add 'delegate' instruction in the delegate BB created above. 981ed41945fSHeejin Ahn MachineInstr *Delegate = BuildMI(DelegateBB, RangeEnd->getDebugLoc(), 982ed41945fSHeejin Ahn TII.get(WebAssembly::DELEGATE)) 983ed41945fSHeejin Ahn .addMBB(DelegateDest); 984ed41945fSHeejin Ahn registerTryScope(Try, Delegate, nullptr); 985ed41945fSHeejin Ahn } 986ed41945fSHeejin Ahn 987ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCallUnwindMismatches(MachineFunction &MF) { 988ed41945fSHeejin Ahn // Linearizing the control flow by placing TRY / END_TRY markers can create 989ed41945fSHeejin Ahn // mismatches in unwind destinations for throwing instructions, such as calls. 990ed41945fSHeejin Ahn // 991ed41945fSHeejin Ahn // We use the 'delegate' instruction to fix the unwind mismatches. 'delegate' 992ed41945fSHeejin Ahn // instruction delegates an exception to an outer 'catch'. It can target not 993ed41945fSHeejin Ahn // only 'catch' but all block-like structures including another 'delegate', 994ed41945fSHeejin Ahn // but with slightly different semantics than branches. When it targets a 995ed41945fSHeejin Ahn // 'catch', it will delegate the exception to that catch. It is being 996ed41945fSHeejin Ahn // discussed how to define the semantics when 'delegate''s target is a non-try 997ed41945fSHeejin Ahn // block: it will either be a validation failure or it will target the next 998ed41945fSHeejin Ahn // outer try-catch. But anyway our LLVM backend currently does not generate 999ed41945fSHeejin Ahn // such code. The example below illustrates where the 'delegate' instruction 1000ed41945fSHeejin Ahn // in the middle will delegate the exception to, depending on the value of N. 1001ed41945fSHeejin Ahn // try 1002ed41945fSHeejin Ahn // try 1003ed41945fSHeejin Ahn // block 1004ed41945fSHeejin Ahn // try 1005ed41945fSHeejin Ahn // try 1006ed41945fSHeejin Ahn // call @foo 1007ed41945fSHeejin Ahn // delegate N ;; Where will this delegate to? 1008ed41945fSHeejin Ahn // catch ;; N == 0 1009ed41945fSHeejin Ahn // end 1010ed41945fSHeejin Ahn // end ;; N == 1 (invalid; will not be generated) 1011ed41945fSHeejin Ahn // delegate ;; N == 2 1012ed41945fSHeejin Ahn // catch ;; N == 3 1013ed41945fSHeejin Ahn // end 1014ed41945fSHeejin Ahn // ;; N == 4 (to caller) 1015ed41945fSHeejin Ahn 1016ed41945fSHeejin Ahn // 1. When an instruction may throw, but the EH pad it will unwind to can be 1017ed41945fSHeejin Ahn // different from the original CFG. 1018ed41945fSHeejin Ahn // 1019ed41945fSHeejin Ahn // Example: we have the following CFG: 1020ed41945fSHeejin Ahn // bb0: 1021ed41945fSHeejin Ahn // call @foo ; if it throws, unwind to bb2 1022ed41945fSHeejin Ahn // bb1: 1023ed41945fSHeejin Ahn // call @bar ; if it throws, unwind to bb3 1024ed41945fSHeejin Ahn // bb2 (ehpad): 1025ed41945fSHeejin Ahn // catch 1026ed41945fSHeejin Ahn // ... 1027ed41945fSHeejin Ahn // bb3 (ehpad) 1028ed41945fSHeejin Ahn // catch 1029ed41945fSHeejin Ahn // ... 1030ed41945fSHeejin Ahn // 1031ed41945fSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 1032ed41945fSHeejin Ahn // will look like: (BB markers are omitted) 1033ed41945fSHeejin Ahn // try 1034ed41945fSHeejin Ahn // try 1035ed41945fSHeejin Ahn // call @foo 1036ed41945fSHeejin Ahn // call @bar ;; if it throws, unwind to bb3 1037ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1038ed41945fSHeejin Ahn // ... 1039ed41945fSHeejin Ahn // end_try 1040ed41945fSHeejin Ahn // catch ;; ehpad (bb3) 1041ed41945fSHeejin Ahn // ... 1042ed41945fSHeejin Ahn // end_try 1043ed41945fSHeejin Ahn // 1044ed41945fSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it 1045ed41945fSHeejin Ahn // is supposed to end up. We solve this problem by wrapping the mismatching 1046ed41945fSHeejin Ahn // call with an inner try-delegate that rethrows the exception to the right 1047ed41945fSHeejin Ahn // 'catch'. 1048ed41945fSHeejin Ahn // 1049ed41945fSHeejin Ahn // try 1050ed41945fSHeejin Ahn // try 1051ed41945fSHeejin Ahn // call @foo 1052ed41945fSHeejin Ahn // try ;; (new) 1053ed41945fSHeejin Ahn // call @bar 1054ed41945fSHeejin Ahn // delegate 1 (bb3) ;; (new) 1055ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1056ed41945fSHeejin Ahn // ... 1057ed41945fSHeejin Ahn // end_try 1058ed41945fSHeejin Ahn // catch ;; ehpad (bb3) 1059ed41945fSHeejin Ahn // ... 1060ed41945fSHeejin Ahn // end_try 1061ed41945fSHeejin Ahn // 1062ed41945fSHeejin Ahn // --- 1063ed41945fSHeejin Ahn // 2. The same as 1, but in this case an instruction unwinds to a caller 1064ed41945fSHeejin Ahn // function and not another EH pad. 1065ed41945fSHeejin Ahn // 1066ed41945fSHeejin Ahn // Example: we have the following CFG: 1067ed41945fSHeejin Ahn // bb0: 1068ed41945fSHeejin Ahn // call @foo ; if it throws, unwind to bb2 1069ed41945fSHeejin Ahn // bb1: 1070ed41945fSHeejin Ahn // call @bar ; if it throws, unwind to caller 1071ed41945fSHeejin Ahn // bb2 (ehpad): 1072ed41945fSHeejin Ahn // catch 1073ed41945fSHeejin Ahn // ... 1074ed41945fSHeejin Ahn // 1075ed41945fSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 1076ed41945fSHeejin Ahn // will look like: 1077ed41945fSHeejin Ahn // try 1078ed41945fSHeejin Ahn // call @foo 1079ed41945fSHeejin Ahn // call @bar ;; if it throws, unwind to caller 1080ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1081ed41945fSHeejin Ahn // ... 1082ed41945fSHeejin Ahn // end_try 1083ed41945fSHeejin Ahn // 1084ed41945fSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, when it is supposed 1085ed41945fSHeejin Ahn // throw up to the caller. We solve this problem in the same way, but in this 1086ed41945fSHeejin Ahn // case 'delegate's immediate argument is the number of block depths + 1, 1087ed41945fSHeejin Ahn // which means it rethrows to the caller. 1088ed41945fSHeejin Ahn // try 1089ed41945fSHeejin Ahn // call @foo 1090ed41945fSHeejin Ahn // try ;; (new) 1091ed41945fSHeejin Ahn // call @bar 1092ed41945fSHeejin Ahn // delegate 1 (caller) ;; (new) 1093ed41945fSHeejin Ahn // catch ;; ehpad (bb2) 1094ed41945fSHeejin Ahn // ... 1095ed41945fSHeejin Ahn // end_try 1096ed41945fSHeejin Ahn // 1097ed41945fSHeejin Ahn // Before rewriteDepthImmediates, delegate's argument is a BB. In case of the 1098ed41945fSHeejin Ahn // caller, it will take a fake BB generated by getFakeCallerBlock(), which 1099ed41945fSHeejin Ahn // will be converted to a correct immediate argument later. 1100ed41945fSHeejin Ahn // 1101ed41945fSHeejin Ahn // In case there are multiple calls in a BB that may throw to the caller, they 1102ed41945fSHeejin Ahn // can be wrapped together in one nested try-delegate scope. (In 1, this 1103ed41945fSHeejin Ahn // couldn't happen, because may-throwing instruction there had an unwind 1104ed41945fSHeejin Ahn // destination, i.e., it was an invoke before, and there could be only one 1105ed41945fSHeejin Ahn // invoke within a BB.) 1106ed41945fSHeejin Ahn 1107ed41945fSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 1108ed41945fSHeejin Ahn // Range of intructions to be wrapped in a new nested try/catch. A range 1109ed41945fSHeejin Ahn // exists in a single BB and does not span multiple BBs. 1110ed41945fSHeejin Ahn using TryRange = std::pair<MachineInstr *, MachineInstr *>; 1111ed41945fSHeejin Ahn // In original CFG, <unwind destination BB, a vector of try ranges> 1112ed41945fSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges; 1113ed41945fSHeejin Ahn 1114ed41945fSHeejin Ahn // Gather possibly throwing calls (i.e., previously invokes) whose current 1115ed41945fSHeejin Ahn // unwind destination is not the same as the original CFG. (Case 1) 1116ed41945fSHeejin Ahn 1117ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) { 1118ed41945fSHeejin Ahn bool SeenThrowableInstInBB = false; 1119ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) { 1120ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 1121ed41945fSHeejin Ahn EHPadStack.pop_back(); 1122ed41945fSHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) 1123ed41945fSHeejin Ahn EHPadStack.push_back(MI.getParent()); 1124ed41945fSHeejin Ahn 1125ed41945fSHeejin Ahn // In this loop we only gather calls that have an EH pad to unwind. So 1126ed41945fSHeejin Ahn // there will be at most 1 such call (= invoke) in a BB, so after we've 1127ed41945fSHeejin Ahn // seen one, we can skip the rest of BB. Also if MBB has no EH pad 1128ed41945fSHeejin Ahn // successor or MI does not throw, this is not an invoke. 1129ed41945fSHeejin Ahn if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() || 1130ed41945fSHeejin Ahn !WebAssembly::mayThrow(MI)) 1131ed41945fSHeejin Ahn continue; 1132ed41945fSHeejin Ahn SeenThrowableInstInBB = true; 1133ed41945fSHeejin Ahn 1134ed41945fSHeejin Ahn // If the EH pad on the stack top is where this instruction should unwind 1135ed41945fSHeejin Ahn // next, we're good. 1136ed41945fSHeejin Ahn MachineBasicBlock *UnwindDest = getFakeCallerBlock(MF); 1137ed41945fSHeejin Ahn for (auto *Succ : MBB.successors()) { 1138ed41945fSHeejin Ahn // Even though semantically a BB can have multiple successors in case an 1139ed41945fSHeejin Ahn // exception is not caught by a catchpad, in our backend implementation 1140ed41945fSHeejin Ahn // it is guaranteed that a BB can have at most one EH pad successor. For 1141ed41945fSHeejin Ahn // details, refer to comments in findWasmUnwindDestinations function in 1142ed41945fSHeejin Ahn // SelectionDAGBuilder.cpp. 1143ed41945fSHeejin Ahn if (Succ->isEHPad()) { 1144ed41945fSHeejin Ahn UnwindDest = Succ; 1145ed41945fSHeejin Ahn break; 1146ed41945fSHeejin Ahn } 1147ed41945fSHeejin Ahn } 1148ed41945fSHeejin Ahn if (EHPadStack.back() == UnwindDest) 1149ed41945fSHeejin Ahn continue; 1150ed41945fSHeejin Ahn 1151ed41945fSHeejin Ahn // Include EH_LABELs in the range before and afer the invoke 1152ed41945fSHeejin Ahn MachineInstr *RangeBegin = &MI, *RangeEnd = &MI; 1153ed41945fSHeejin Ahn if (RangeBegin->getIterator() != MBB.begin() && 1154ed41945fSHeejin Ahn std::prev(RangeBegin->getIterator())->isEHLabel()) 1155ed41945fSHeejin Ahn RangeBegin = &*std::prev(RangeBegin->getIterator()); 1156ed41945fSHeejin Ahn if (std::next(RangeEnd->getIterator()) != MBB.end() && 1157ed41945fSHeejin Ahn std::next(RangeEnd->getIterator())->isEHLabel()) 1158ed41945fSHeejin Ahn RangeEnd = &*std::next(RangeEnd->getIterator()); 1159ed41945fSHeejin Ahn 1160ed41945fSHeejin Ahn // If not, record the range. 1161ed41945fSHeejin Ahn UnwindDestToTryRanges[UnwindDest].push_back( 1162ed41945fSHeejin Ahn TryRange(RangeBegin, RangeEnd)); 1163ed41945fSHeejin Ahn LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " << MBB.getName() 1164ed41945fSHeejin Ahn << "\nCall = " << MI 1165ed41945fSHeejin Ahn << "\nOriginal dest = " << UnwindDest->getName() 1166ed41945fSHeejin Ahn << " Current dest = " << EHPadStack.back()->getName() 1167ed41945fSHeejin Ahn << "\n\n"); 1168ed41945fSHeejin Ahn } 1169ed41945fSHeejin Ahn } 1170ed41945fSHeejin Ahn 1171ed41945fSHeejin Ahn assert(EHPadStack.empty()); 1172ed41945fSHeejin Ahn 1173ed41945fSHeejin Ahn // Gather possibly throwing calls that are supposed to unwind up to the caller 1174ed41945fSHeejin Ahn // if they throw, but currently unwind to an incorrect destination. Unlike the 1175ed41945fSHeejin Ahn // loop above, there can be multiple calls within a BB that unwind to the 1176ed41945fSHeejin Ahn // caller, which we should group together in a range. (Case 2) 1177ed41945fSHeejin Ahn 1178ed41945fSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive 1179ed41945fSHeejin Ahn 1180ed41945fSHeejin Ahn // Record the range. 1181ed41945fSHeejin Ahn auto RecordCallerMismatchRange = [&](const MachineBasicBlock *CurrentDest) { 1182ed41945fSHeejin Ahn UnwindDestToTryRanges[getFakeCallerBlock(MF)].push_back( 1183ed41945fSHeejin Ahn TryRange(RangeBegin, RangeEnd)); 1184ed41945fSHeejin Ahn LLVM_DEBUG(dbgs() << "- Call unwind mismatch: MBB = " 1185ed41945fSHeejin Ahn << RangeBegin->getParent()->getName() 1186ed41945fSHeejin Ahn << "\nRange begin = " << *RangeBegin 1187ed41945fSHeejin Ahn << "Range end = " << *RangeEnd 1188ed41945fSHeejin Ahn << "\nOriginal dest = caller Current dest = " 1189ed41945fSHeejin Ahn << CurrentDest->getName() << "\n\n"); 1190ed41945fSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers 1191ed41945fSHeejin Ahn }; 1192ed41945fSHeejin Ahn 1193ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) { 1194ed41945fSHeejin Ahn bool SeenThrowableInstInBB = false; 1195ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) { 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. 1201da01a9dbSHeejin Ahn if (MBB.hasEHPadSuccessor() && MayThrow && !SeenThrowableInstInBB) 1202ed41945fSHeejin Ahn SeenThrowableInstInBB = true; 1203ed41945fSHeejin Ahn 1204ed41945fSHeejin Ahn // We wrap up the current range when we see a marker even if we haven't 1205ed41945fSHeejin Ahn // finished a BB. 1206da01a9dbSHeejin Ahn else if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) 1207ed41945fSHeejin Ahn RecordCallerMismatchRange(EHPadStack.back()); 1208ed41945fSHeejin Ahn 1209ed41945fSHeejin Ahn // If EHPadStack is empty, that means it correctly unwinds to the caller 1210ed41945fSHeejin Ahn // if it throws, so we're good. If MI does not throw, we're good too. 1211da01a9dbSHeejin Ahn else if (EHPadStack.empty() || !MayThrow) { 1212da01a9dbSHeejin Ahn } 1213ed41945fSHeejin Ahn 1214ed41945fSHeejin Ahn // We found an instruction that unwinds to the caller but currently has an 1215ed41945fSHeejin Ahn // incorrect unwind destination. Create a new range or increment the 1216ed41945fSHeejin Ahn // currently existing range. 1217da01a9dbSHeejin Ahn else { 1218ed41945fSHeejin Ahn if (!RangeEnd) 1219ed41945fSHeejin Ahn RangeBegin = RangeEnd = &MI; 1220ed41945fSHeejin Ahn else 1221ed41945fSHeejin Ahn RangeBegin = &MI; 1222ed41945fSHeejin Ahn } 1223ed41945fSHeejin Ahn 1224da01a9dbSHeejin Ahn // Update EHPadStack. 1225da01a9dbSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 1226da01a9dbSHeejin Ahn EHPadStack.pop_back(); 1227da01a9dbSHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) 1228da01a9dbSHeejin Ahn EHPadStack.push_back(MI.getParent()); 1229da01a9dbSHeejin Ahn } 1230da01a9dbSHeejin Ahn 1231ed41945fSHeejin Ahn if (RangeEnd) 1232ed41945fSHeejin Ahn RecordCallerMismatchRange(EHPadStack.back()); 1233ed41945fSHeejin Ahn } 1234ed41945fSHeejin Ahn 1235ed41945fSHeejin Ahn assert(EHPadStack.empty()); 1236ed41945fSHeejin Ahn 1237ed41945fSHeejin Ahn // We don't have any unwind destination mismatches to resolve. 1238ed41945fSHeejin Ahn if (UnwindDestToTryRanges.empty()) 1239ed41945fSHeejin Ahn return false; 1240ed41945fSHeejin Ahn 1241ed41945fSHeejin Ahn // Now we fix the mismatches by wrapping calls with inner try-delegates. 1242ed41945fSHeejin Ahn for (auto &P : UnwindDestToTryRanges) { 1243ed41945fSHeejin Ahn NumCallUnwindMismatches += P.second.size(); 1244ed41945fSHeejin Ahn MachineBasicBlock *UnwindDest = P.first; 1245ed41945fSHeejin Ahn auto &TryRanges = P.second; 1246ed41945fSHeejin Ahn 1247ed41945fSHeejin Ahn for (auto Range : TryRanges) { 1248ed41945fSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; 1249ed41945fSHeejin Ahn std::tie(RangeBegin, RangeEnd) = Range; 1250ed41945fSHeejin Ahn auto *MBB = RangeBegin->getParent(); 1251ed41945fSHeejin Ahn 1252ed41945fSHeejin Ahn // If this BB has an EH pad successor, i.e., ends with an 'invoke', now we 1253ed41945fSHeejin Ahn // are going to wrap the invoke with try-delegate, making the 'delegate' 1254ed41945fSHeejin Ahn // BB the new successor instead, so remove the EH pad succesor here. The 1255ed41945fSHeejin Ahn // BB may not have an EH pad successor if calls in this BB throw to the 1256ed41945fSHeejin Ahn // caller. 1257ed41945fSHeejin Ahn MachineBasicBlock *EHPad = nullptr; 1258ed41945fSHeejin Ahn for (auto *Succ : MBB->successors()) { 1259ed41945fSHeejin Ahn if (Succ->isEHPad()) { 1260ed41945fSHeejin Ahn EHPad = Succ; 1261ed41945fSHeejin Ahn break; 1262ed41945fSHeejin Ahn } 1263ed41945fSHeejin Ahn } 1264ed41945fSHeejin Ahn if (EHPad) 1265ed41945fSHeejin Ahn MBB->removeSuccessor(EHPad); 1266ed41945fSHeejin Ahn 1267ed41945fSHeejin Ahn addTryDelegate(RangeBegin, RangeEnd, UnwindDest); 1268ed41945fSHeejin Ahn } 1269ed41945fSHeejin Ahn } 1270ed41945fSHeejin Ahn 1271ed41945fSHeejin Ahn return true; 1272ed41945fSHeejin Ahn } 1273ed41945fSHeejin Ahn 1274ed41945fSHeejin Ahn bool WebAssemblyCFGStackify::fixCatchUnwindMismatches(MachineFunction &MF) { 12759f770b36SHeejin Ahn // There is another kind of unwind destination mismatches besides call unwind 12769f770b36SHeejin Ahn // mismatches, which we will call "catch unwind mismatches". See this example 12779f770b36SHeejin Ahn // after the marker placement: 12789f770b36SHeejin Ahn // try 12799f770b36SHeejin Ahn // try 12809f770b36SHeejin Ahn // call @foo 12819f770b36SHeejin Ahn // catch __cpp_exception ;; ehpad A (next unwind dest: caller) 12829f770b36SHeejin Ahn // ... 12839f770b36SHeejin Ahn // end_try 12849f770b36SHeejin Ahn // catch_all ;; ehpad B 12859f770b36SHeejin Ahn // ... 12869f770b36SHeejin Ahn // end_try 12879f770b36SHeejin Ahn // 12889f770b36SHeejin Ahn // 'call @foo's unwind destination is the ehpad A. But suppose 'call @foo' 12899f770b36SHeejin Ahn // throws a foreign exception that is not caught by ehpad A, and its next 12909f770b36SHeejin Ahn // destination should be the caller. But after control flow linearization, 12919f770b36SHeejin Ahn // another EH pad can be placed in between (e.g. ehpad B here), making the 12929f770b36SHeejin Ahn // next unwind destination incorrect. In this case, the foreign exception 12939f770b36SHeejin Ahn // will instead go to ehpad B and will be caught there instead. In this 12949f770b36SHeejin Ahn // example the correct next unwind destination is the caller, but it can be 12959f770b36SHeejin Ahn // another outer catch in other cases. 12969f770b36SHeejin Ahn // 12979f770b36SHeejin Ahn // There is no specific 'call' or 'throw' instruction to wrap with a 12989f770b36SHeejin Ahn // try-delegate, so we wrap the whole try-catch-end with a try-delegate and 12999f770b36SHeejin Ahn // make it rethrow to the right destination, as in the example below: 13009f770b36SHeejin Ahn // try 13019f770b36SHeejin Ahn // try ;; (new) 13029f770b36SHeejin Ahn // try 13039f770b36SHeejin Ahn // call @foo 13049f770b36SHeejin Ahn // catch __cpp_exception ;; ehpad A (next unwind dest: caller) 13059f770b36SHeejin Ahn // ... 13069f770b36SHeejin Ahn // end_try 13079f770b36SHeejin Ahn // delegate 1 (caller) ;; (new) 13089f770b36SHeejin Ahn // catch_all ;; ehpad B 13099f770b36SHeejin Ahn // ... 13109f770b36SHeejin Ahn // end_try 13119f770b36SHeejin Ahn 13129f770b36SHeejin Ahn const auto *EHInfo = MF.getWasmEHFuncInfo(); 13139f770b36SHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 13149f770b36SHeejin Ahn // For EH pads that have catch unwind mismatches, a map of <EH pad, its 13159f770b36SHeejin Ahn // correct unwind destination>. 13169f770b36SHeejin Ahn DenseMap<MachineBasicBlock *, MachineBasicBlock *> EHPadToUnwindDest; 13179f770b36SHeejin Ahn 13189f770b36SHeejin Ahn for (auto &MBB : reverse(MF)) { 13199f770b36SHeejin Ahn for (auto &MI : reverse(MBB)) { 13209f770b36SHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 13219f770b36SHeejin Ahn EHPadStack.pop_back(); 13229f770b36SHeejin Ahn else if (MI.getOpcode() == WebAssembly::DELEGATE) 13239f770b36SHeejin Ahn EHPadStack.push_back(&MBB); 13249f770b36SHeejin Ahn else if (WebAssembly::isCatch(MI.getOpcode())) { 13259f770b36SHeejin Ahn auto *EHPad = &MBB; 13269f770b36SHeejin Ahn 13279f770b36SHeejin Ahn // catch_all always catches an exception, so we don't need to do 13289f770b36SHeejin Ahn // anything 13299f770b36SHeejin Ahn if (MI.getOpcode() == WebAssembly::CATCH_ALL) { 13309f770b36SHeejin Ahn } 13319f770b36SHeejin Ahn 13329f770b36SHeejin Ahn // This can happen when the unwind dest was removed during the 13339f770b36SHeejin Ahn // optimization, e.g. because it was unreachable. 1334a08e609dSHeejin Ahn else if (EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) { 13359f770b36SHeejin Ahn LLVM_DEBUG(dbgs() << "EHPad (" << EHPad->getName() 13369f770b36SHeejin Ahn << "'s unwind destination does not exist anymore" 13379f770b36SHeejin Ahn << "\n\n"); 13389f770b36SHeejin Ahn } 13399f770b36SHeejin Ahn 13409f770b36SHeejin Ahn // The EHPad's next unwind destination is the caller, but we incorrectly 13419f770b36SHeejin Ahn // unwind to another EH pad. 1342a08e609dSHeejin Ahn else if (!EHPadStack.empty() && !EHInfo->hasUnwindDest(EHPad)) { 13439f770b36SHeejin Ahn EHPadToUnwindDest[EHPad] = getFakeCallerBlock(MF); 13449f770b36SHeejin Ahn LLVM_DEBUG(dbgs() 13459f770b36SHeejin Ahn << "- Catch unwind mismatch:\nEHPad = " << EHPad->getName() 13469f770b36SHeejin Ahn << " Original dest = caller Current dest = " 13479f770b36SHeejin Ahn << EHPadStack.back()->getName() << "\n\n"); 13489f770b36SHeejin Ahn } 13499f770b36SHeejin Ahn 13509f770b36SHeejin Ahn // The EHPad's next unwind destination is an EH pad, whereas we 13519f770b36SHeejin Ahn // incorrectly unwind to another EH pad. 1352a08e609dSHeejin Ahn else if (!EHPadStack.empty() && EHInfo->hasUnwindDest(EHPad)) { 1353a08e609dSHeejin Ahn auto *UnwindDest = EHInfo->getUnwindDest(EHPad); 13549f770b36SHeejin Ahn if (EHPadStack.back() != UnwindDest) { 13559f770b36SHeejin Ahn EHPadToUnwindDest[EHPad] = UnwindDest; 13569f770b36SHeejin Ahn LLVM_DEBUG(dbgs() << "- Catch unwind mismatch:\nEHPad = " 13579f770b36SHeejin Ahn << EHPad->getName() << " Original dest = " 13589f770b36SHeejin Ahn << UnwindDest->getName() << " Current dest = " 13599f770b36SHeejin Ahn << EHPadStack.back()->getName() << "\n\n"); 13609f770b36SHeejin Ahn } 13619f770b36SHeejin Ahn } 13629f770b36SHeejin Ahn 13639f770b36SHeejin Ahn EHPadStack.push_back(EHPad); 13649f770b36SHeejin Ahn } 13659f770b36SHeejin Ahn } 13669f770b36SHeejin Ahn } 13679f770b36SHeejin Ahn 13689f770b36SHeejin Ahn assert(EHPadStack.empty()); 13699f770b36SHeejin Ahn if (EHPadToUnwindDest.empty()) 1370c4ac74fbSHeejin Ahn return false; 13719f770b36SHeejin Ahn NumCatchUnwindMismatches += EHPadToUnwindDest.size(); 1372d8b3dc5aSHeejin Ahn SmallPtrSet<MachineBasicBlock *, 4> NewEndTryBBs; 13739f770b36SHeejin Ahn 13749f770b36SHeejin Ahn for (auto &P : EHPadToUnwindDest) { 13759f770b36SHeejin Ahn MachineBasicBlock *EHPad = P.first; 13769f770b36SHeejin Ahn MachineBasicBlock *UnwindDest = P.second; 13779f770b36SHeejin Ahn MachineInstr *Try = EHPadToTry[EHPad]; 13789f770b36SHeejin Ahn MachineInstr *EndTry = BeginToEnd[Try]; 13799f770b36SHeejin Ahn addTryDelegate(Try, EndTry, UnwindDest); 1380d8b3dc5aSHeejin Ahn NewEndTryBBs.insert(EndTry->getParent()); 1381f47a654aSHeejin Ahn } 1382f47a654aSHeejin Ahn 1383f47a654aSHeejin Ahn // Adding a try-delegate wrapping an existing try-catch-end can make existing 1384f47a654aSHeejin Ahn // branch destination BBs invalid. For example, 1385f47a654aSHeejin Ahn // 1386f47a654aSHeejin Ahn // - Before: 1387f47a654aSHeejin Ahn // bb0: 1388f47a654aSHeejin Ahn // block 1389f47a654aSHeejin Ahn // br bb3 1390f47a654aSHeejin Ahn // bb1: 1391f47a654aSHeejin Ahn // try 1392f47a654aSHeejin Ahn // ... 1393f47a654aSHeejin Ahn // bb2: (ehpad) 1394f47a654aSHeejin Ahn // catch 1395f47a654aSHeejin Ahn // bb3: 1396f47a654aSHeejin Ahn // end_try 1397f47a654aSHeejin Ahn // end_block ;; 'br bb3' targets here 1398f47a654aSHeejin Ahn // 1399f47a654aSHeejin Ahn // Suppose this try-catch-end has a catch unwind mismatch, so we need to wrap 1400f47a654aSHeejin Ahn // this with a try-delegate. Then this becomes: 1401f47a654aSHeejin Ahn // 1402f47a654aSHeejin Ahn // - After: 1403f47a654aSHeejin Ahn // bb0: 1404f47a654aSHeejin Ahn // block 1405f47a654aSHeejin Ahn // br bb3 ;; invalid destination! 1406f47a654aSHeejin Ahn // bb1: 1407f47a654aSHeejin Ahn // try ;; (new instruction) 1408f47a654aSHeejin Ahn // try 1409f47a654aSHeejin Ahn // ... 1410f47a654aSHeejin Ahn // bb2: (ehpad) 1411f47a654aSHeejin Ahn // catch 1412f47a654aSHeejin Ahn // bb3: 1413f47a654aSHeejin Ahn // end_try ;; 'br bb3' still incorrectly targets here! 1414f47a654aSHeejin Ahn // delegate_bb: ;; (new BB) 1415f47a654aSHeejin Ahn // delegate ;; (new instruction) 1416f47a654aSHeejin Ahn // split_bb: ;; (new BB) 1417f47a654aSHeejin Ahn // end_block 1418f47a654aSHeejin Ahn // 1419f47a654aSHeejin Ahn // Now 'br bb3' incorrectly branches to an inner scope. 1420f47a654aSHeejin Ahn // 1421f47a654aSHeejin Ahn // As we can see in this case, when branches target a BB that has both 1422f47a654aSHeejin Ahn // 'end_try' and 'end_block' and the BB is split to insert a 'delegate', we 1423f47a654aSHeejin Ahn // have to remap existing branch destinations so that they target not the 1424d8b3dc5aSHeejin Ahn // 'end_try' BB but the new 'end_block' BB. There can be multiple 'delegate's 1425d8b3dc5aSHeejin Ahn // in between, so we try to find the next BB with 'end_block' instruction. In 1426d8b3dc5aSHeejin Ahn // this example, the 'br bb3' instruction should be remapped to 'br split_bb'. 1427f47a654aSHeejin Ahn for (auto &MBB : MF) { 1428f47a654aSHeejin Ahn for (auto &MI : MBB) { 1429f47a654aSHeejin Ahn if (MI.isTerminator()) { 1430f47a654aSHeejin Ahn for (auto &MO : MI.operands()) { 1431d8b3dc5aSHeejin Ahn if (MO.isMBB() && NewEndTryBBs.count(MO.getMBB())) { 1432d8b3dc5aSHeejin Ahn auto *BrDest = MO.getMBB(); 1433d8b3dc5aSHeejin Ahn bool FoundEndBlock = false; 1434d8b3dc5aSHeejin Ahn for (; std::next(BrDest->getIterator()) != MF.end(); 1435d8b3dc5aSHeejin Ahn BrDest = BrDest->getNextNode()) { 1436d8b3dc5aSHeejin Ahn for (const auto &MI : *BrDest) { 1437d8b3dc5aSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK) { 1438d8b3dc5aSHeejin Ahn FoundEndBlock = true; 1439d8b3dc5aSHeejin Ahn break; 1440d8b3dc5aSHeejin Ahn } 1441d8b3dc5aSHeejin Ahn } 1442d8b3dc5aSHeejin Ahn if (FoundEndBlock) 1443d8b3dc5aSHeejin Ahn break; 1444d8b3dc5aSHeejin Ahn } 1445d8b3dc5aSHeejin Ahn assert(FoundEndBlock); 1446d8b3dc5aSHeejin Ahn MO.setMBB(BrDest); 1447f47a654aSHeejin Ahn } 1448f47a654aSHeejin Ahn } 1449f47a654aSHeejin Ahn } 1450f47a654aSHeejin Ahn } 14519f770b36SHeejin Ahn } 14529f770b36SHeejin Ahn 14539f770b36SHeejin Ahn return true; 1454c4ac74fbSHeejin Ahn } 1455c4ac74fbSHeejin Ahn 1456ed41945fSHeejin Ahn void WebAssemblyCFGStackify::recalculateScopeTops(MachineFunction &MF) { 1457ed41945fSHeejin Ahn // Renumber BBs and recalculate ScopeTop info because new BBs might have been 1458ed41945fSHeejin Ahn // created and inserted during fixing unwind mismatches. 1459ed41945fSHeejin Ahn MF.RenumberBlocks(); 1460ed41945fSHeejin Ahn ScopeTops.clear(); 1461ed41945fSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs()); 1462ed41945fSHeejin Ahn for (auto &MBB : reverse(MF)) { 1463ed41945fSHeejin Ahn for (auto &MI : reverse(MBB)) { 1464ed41945fSHeejin Ahn if (ScopeTops[MBB.getNumber()]) 1465ed41945fSHeejin Ahn break; 1466ed41945fSHeejin Ahn switch (MI.getOpcode()) { 1467ed41945fSHeejin Ahn case WebAssembly::END_BLOCK: 1468ed41945fSHeejin Ahn case WebAssembly::END_LOOP: 1469ed41945fSHeejin Ahn case WebAssembly::END_TRY: 1470ed41945fSHeejin Ahn case WebAssembly::DELEGATE: 1471ed41945fSHeejin Ahn updateScopeTops(EndToBegin[&MI]->getParent(), &MBB); 1472ed41945fSHeejin Ahn break; 1473ed41945fSHeejin Ahn case WebAssembly::CATCH: 1474ed41945fSHeejin Ahn case WebAssembly::CATCH_ALL: 1475ed41945fSHeejin Ahn updateScopeTops(EHPadToTry[&MBB]->getParent(), &MBB); 1476ed41945fSHeejin Ahn break; 1477ed41945fSHeejin Ahn } 1478ed41945fSHeejin Ahn } 1479ed41945fSHeejin Ahn } 1480ed41945fSHeejin Ahn } 1481ed41945fSHeejin Ahn 14822726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 14832726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 14842726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 14852726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 14862726b88cSDan Gohman /// that end at the function end need to have a return type signature that 14872726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 14882726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 1489e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 1490e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 14912726b88cSDan Gohman 14922726b88cSDan Gohman if (MFI.getResults().empty()) 14932726b88cSDan Gohman return; 14942726b88cSDan Gohman 14952cb27072SThomas Lively // MCInstLower will add the proper types to multivalue signatures based on the 14962cb27072SThomas Lively // function return type 14972cb27072SThomas Lively WebAssembly::BlockType RetType = 14982cb27072SThomas Lively MFI.getResults().size() > 1 14992cb27072SThomas Lively ? WebAssembly::BlockType::Multivalue 15002cb27072SThomas Lively : WebAssembly::BlockType( 15012cb27072SThomas Lively WebAssembly::toValType(MFI.getResults().front())); 15022726b88cSDan Gohman 1503d25c17f3SHeejin Ahn SmallVector<MachineBasicBlock::reverse_iterator, 4> Worklist; 1504d25c17f3SHeejin Ahn Worklist.push_back(MF.rbegin()->rbegin()); 1505d25c17f3SHeejin Ahn 1506d25c17f3SHeejin Ahn auto Process = [&](MachineBasicBlock::reverse_iterator It) { 1507d25c17f3SHeejin Ahn auto *MBB = It->getParent(); 1508d25c17f3SHeejin Ahn while (It != MBB->rend()) { 1509d25c17f3SHeejin Ahn MachineInstr &MI = *It++; 1510801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 15112726b88cSDan Gohman continue; 15122cb27072SThomas Lively switch (MI.getOpcode()) { 1513d25c17f3SHeejin Ahn case WebAssembly::END_TRY: { 1514d25c17f3SHeejin Ahn // If a 'try''s return type is fixed, both its try body and catch body 1515d25c17f3SHeejin Ahn // should satisfy the return type, so we need to search 'end' 1516d25c17f3SHeejin Ahn // instructions before its corresponding 'catch' too. 1517d25c17f3SHeejin Ahn auto *EHPad = TryToEHPad.lookup(EndToBegin[&MI]); 1518d25c17f3SHeejin Ahn assert(EHPad); 15199f8b2576SHeejin Ahn auto NextIt = 15209f8b2576SHeejin Ahn std::next(WebAssembly::findCatch(EHPad)->getReverseIterator()); 15219f8b2576SHeejin Ahn if (NextIt != EHPad->rend()) 15229f8b2576SHeejin Ahn Worklist.push_back(NextIt); 1523d25c17f3SHeejin Ahn LLVM_FALLTHROUGH; 1524d25c17f3SHeejin Ahn } 15252cb27072SThomas Lively case WebAssembly::END_BLOCK: 15262cb27072SThomas Lively case WebAssembly::END_LOOP: 152718c56a07SHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 15282726b88cSDan Gohman continue; 15292cb27072SThomas Lively default: 1530d25c17f3SHeejin Ahn // Something other than an `end`. We're done for this BB. 15312726b88cSDan Gohman return; 15322726b88cSDan Gohman } 15332726b88cSDan Gohman } 1534d25c17f3SHeejin Ahn // We've reached the beginning of a BB. Continue the search in the previous 1535d25c17f3SHeejin Ahn // BB. 1536d25c17f3SHeejin Ahn Worklist.push_back(MBB->getPrevNode()->rbegin()); 1537d25c17f3SHeejin Ahn }; 1538d25c17f3SHeejin Ahn 1539d25c17f3SHeejin Ahn while (!Worklist.empty()) 1540d25c17f3SHeejin Ahn Process(Worklist.pop_back_val()); 15412cb27072SThomas Lively } 15422726b88cSDan Gohman 1543d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 1544d934cb88SDan Gohman // were a block. 154518c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF, 1546d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 154710b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 154810b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 1549d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 1550d934cb88SDan Gohman } 1551d934cb88SDan Gohman 1552e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 1553e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 1554e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 1555e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 1556e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 15578fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 1558e76fa9ecSHeejin Ahn for (auto &MBB : MF) 1559e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 156044a5a4b1SHeejin Ahn 1561d6f48786SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 156244a5a4b1SHeejin Ahn for (auto &MBB : MF) { 156344a5a4b1SHeejin Ahn if (MBB.isEHPad()) { 156444a5a4b1SHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 1565e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1566e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 1567e76fa9ecSHeejin Ahn placeTryMarker(MBB); 156844a5a4b1SHeejin Ahn } else { 156932807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 1570e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 1571950a13cfSDan Gohman } 157244a5a4b1SHeejin Ahn } 1573c4ac74fbSHeejin Ahn // Fix mismatches in unwind destinations induced by linearizing the code. 1574daeead4bSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1575ed41945fSHeejin Ahn MF.getFunction().hasPersonalityFn()) { 1576ed41945fSHeejin Ahn bool Changed = fixCallUnwindMismatches(MF); 1577ed41945fSHeejin Ahn Changed |= fixCatchUnwindMismatches(MF); 1578ed41945fSHeejin Ahn if (Changed) 1579ed41945fSHeejin Ahn recalculateScopeTops(MF); 1580ed41945fSHeejin Ahn } 158144a5a4b1SHeejin Ahn } 1582950a13cfSDan Gohman 15832968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getBranchDepth( 15842968611fSHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) { 15852968611fSHeejin Ahn unsigned Depth = 0; 15862968611fSHeejin Ahn for (auto X : reverse(Stack)) { 15872968611fSHeejin Ahn if (X.first == MBB) 15882968611fSHeejin Ahn break; 15892968611fSHeejin Ahn ++Depth; 15902968611fSHeejin Ahn } 15912968611fSHeejin Ahn assert(Depth < Stack.size() && "Branch destination should be in scope"); 15922968611fSHeejin Ahn return Depth; 15932968611fSHeejin Ahn } 15942968611fSHeejin Ahn 15952968611fSHeejin Ahn unsigned WebAssemblyCFGStackify::getDelegateDepth( 15962968611fSHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, const MachineBasicBlock *MBB) { 15972968611fSHeejin Ahn if (MBB == FakeCallerBB) 15982968611fSHeejin Ahn return Stack.size(); 15992968611fSHeejin Ahn // Delegate's destination is either a catch or a another delegate BB. When the 16002968611fSHeejin Ahn // destination is another delegate, we can compute the argument in the same 16012968611fSHeejin Ahn // way as branches, because the target delegate BB only contains the single 16022968611fSHeejin Ahn // delegate instruction. 16032968611fSHeejin Ahn if (!MBB->isEHPad()) // Target is a delegate BB 16042968611fSHeejin Ahn return getBranchDepth(Stack, MBB); 16052968611fSHeejin Ahn 16062968611fSHeejin Ahn // When the delegate's destination is a catch BB, we need to use its 16072968611fSHeejin Ahn // corresponding try's end_try BB because Stack contains each marker's end BB. 16082968611fSHeejin Ahn // Also we need to check if the end marker instruction matches, because a 16092968611fSHeejin Ahn // single BB can contain multiple end markers, like this: 16102968611fSHeejin Ahn // bb: 16112968611fSHeejin Ahn // END_BLOCK 16122968611fSHeejin Ahn // END_TRY 16132968611fSHeejin Ahn // END_BLOCK 16142968611fSHeejin Ahn // END_TRY 16152968611fSHeejin Ahn // ... 16162968611fSHeejin Ahn // 16172968611fSHeejin Ahn // In case of branches getting the immediate that targets any of these is 16182968611fSHeejin Ahn // fine, but delegate has to exactly target the correct try. 16192968611fSHeejin Ahn unsigned Depth = 0; 16202968611fSHeejin Ahn const MachineInstr *EndTry = BeginToEnd[EHPadToTry[MBB]]; 16212968611fSHeejin Ahn for (auto X : reverse(Stack)) { 16222968611fSHeejin Ahn if (X.first == EndTry->getParent() && X.second == EndTry) 16232968611fSHeejin Ahn break; 16242968611fSHeejin Ahn ++Depth; 16252968611fSHeejin Ahn } 16262968611fSHeejin Ahn assert(Depth < Stack.size() && "Delegate destination should be in scope"); 16272968611fSHeejin Ahn return Depth; 16282968611fSHeejin Ahn } 16292968611fSHeejin Ahn 163035f5f797SHeejin Ahn unsigned WebAssemblyCFGStackify::getRethrowDepth( 163135f5f797SHeejin Ahn const SmallVectorImpl<EndMarkerInfo> &Stack, 163235f5f797SHeejin Ahn const SmallVectorImpl<const MachineBasicBlock *> &EHPadStack) { 163335f5f797SHeejin Ahn unsigned Depth = 0; 163435f5f797SHeejin Ahn // In our current implementation, rethrows always rethrow the exception caught 163535f5f797SHeejin Ahn // by the innermost enclosing catch. This means while traversing Stack in the 163635f5f797SHeejin Ahn // reverse direction, when we encounter END_TRY, we should check if the 163735f5f797SHeejin Ahn // END_TRY corresponds to the current innermost EH pad. For example: 163835f5f797SHeejin Ahn // try 163935f5f797SHeejin Ahn // ... 164035f5f797SHeejin Ahn // catch ;; (a) 164135f5f797SHeejin Ahn // try 164235f5f797SHeejin Ahn // rethrow 1 ;; (b) 164335f5f797SHeejin Ahn // catch ;; (c) 164435f5f797SHeejin Ahn // rethrow 0 ;; (d) 164535f5f797SHeejin Ahn // end ;; (e) 164635f5f797SHeejin Ahn // end ;; (f) 164735f5f797SHeejin Ahn // 164835f5f797SHeejin Ahn // When we are at 'rethrow' (d), while reversely traversing Stack the first 164935f5f797SHeejin Ahn // 'end' we encounter is the 'end' (e), which corresponds to the 'catch' (c). 165035f5f797SHeejin Ahn // And 'rethrow' (d) rethrows the exception caught by 'catch' (c), so we stop 165135f5f797SHeejin Ahn // there and the depth should be 0. But when we are at 'rethrow' (b), it 165235f5f797SHeejin Ahn // rethrows the exception caught by 'catch' (a), so when traversing Stack 165335f5f797SHeejin Ahn // reversely, we should skip the 'end' (e) and choose 'end' (f), which 165435f5f797SHeejin Ahn // corresponds to 'catch' (a). 165535f5f797SHeejin Ahn for (auto X : reverse(Stack)) { 165635f5f797SHeejin Ahn const MachineInstr *End = X.second; 165735f5f797SHeejin Ahn if (End->getOpcode() == WebAssembly::END_TRY) { 165835f5f797SHeejin Ahn auto *EHPad = TryToEHPad[EndToBegin[End]]; 165935f5f797SHeejin Ahn if (EHPadStack.back() == EHPad) 166035f5f797SHeejin Ahn break; 166135f5f797SHeejin Ahn } 166235f5f797SHeejin Ahn ++Depth; 166335f5f797SHeejin Ahn } 166435f5f797SHeejin Ahn assert(Depth < Stack.size() && "Rethrow destination should be in scope"); 166535f5f797SHeejin Ahn return Depth; 166635f5f797SHeejin Ahn } 166735f5f797SHeejin Ahn 1668e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 16691d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 16702968611fSHeejin Ahn SmallVector<EndMarkerInfo, 8> Stack; 167135f5f797SHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 16721d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 1673e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 1674e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 16751d68e80fSDan Gohman switch (MI.getOpcode()) { 16761d68e80fSDan Gohman case WebAssembly::BLOCK: 1677e76fa9ecSHeejin Ahn case WebAssembly::TRY: 16782968611fSHeejin Ahn assert(ScopeTops[Stack.back().first->getNumber()]->getNumber() <= 1679e76fa9ecSHeejin Ahn MBB.getNumber() && 1680e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 1681e76fa9ecSHeejin Ahn Stack.pop_back(); 1682e76fa9ecSHeejin Ahn break; 1683e76fa9ecSHeejin Ahn 16841d68e80fSDan Gohman case WebAssembly::LOOP: 16852968611fSHeejin Ahn assert(Stack.back().first == &MBB && "Loop top should be balanced"); 16861d68e80fSDan Gohman Stack.pop_back(); 16871d68e80fSDan Gohman break; 1688e76fa9ecSHeejin Ahn 16891d68e80fSDan Gohman case WebAssembly::END_BLOCK: 16902968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI)); 1691ed41945fSHeejin Ahn break; 1692ed41945fSHeejin Ahn 169335f5f797SHeejin Ahn case WebAssembly::END_TRY: { 1694ed41945fSHeejin Ahn // We handle DELEGATE in the default level, because DELEGATE has 16952968611fSHeejin Ahn // immediate operands to rewrite. 16962968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI)); 169735f5f797SHeejin Ahn auto *EHPad = TryToEHPad[EndToBegin[&MI]]; 169835f5f797SHeejin Ahn EHPadStack.push_back(EHPad); 16991d68e80fSDan Gohman break; 170035f5f797SHeejin Ahn } 1701e76fa9ecSHeejin Ahn 17021d68e80fSDan Gohman case WebAssembly::END_LOOP: 17032968611fSHeejin Ahn Stack.push_back(std::make_pair(EndToBegin[&MI]->getParent(), &MI)); 17041d68e80fSDan Gohman break; 1705e76fa9ecSHeejin Ahn 170635f5f797SHeejin Ahn case WebAssembly::CATCH: 170735f5f797SHeejin Ahn case WebAssembly::CATCH_ALL: 170835f5f797SHeejin Ahn EHPadStack.pop_back(); 170935f5f797SHeejin Ahn break; 171035f5f797SHeejin Ahn 171135f5f797SHeejin Ahn case WebAssembly::RETHROW: 171235f5f797SHeejin Ahn MI.getOperand(0).setImm(getRethrowDepth(Stack, EHPadStack)); 171335f5f797SHeejin Ahn break; 171435f5f797SHeejin Ahn 17151d68e80fSDan Gohman default: 17161d68e80fSDan Gohman if (MI.isTerminator()) { 17171d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 17181d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 17191d68e80fSDan Gohman while (MI.getNumOperands() > 0) 17201d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 17211d68e80fSDan Gohman for (auto MO : Ops) { 1722ed41945fSHeejin Ahn if (MO.isMBB()) { 1723ed41945fSHeejin Ahn if (MI.getOpcode() == WebAssembly::DELEGATE) 1724ed41945fSHeejin Ahn MO = MachineOperand::CreateImm( 17252968611fSHeejin Ahn getDelegateDepth(Stack, MO.getMBB())); 1726ed41945fSHeejin Ahn else 17272968611fSHeejin Ahn MO = MachineOperand::CreateImm( 17282968611fSHeejin Ahn getBranchDepth(Stack, MO.getMBB())); 1729ed41945fSHeejin Ahn } 17301d68e80fSDan Gohman MI.addOperand(MF, MO); 173132807932SDan Gohman } 17321d68e80fSDan Gohman } 1733ed41945fSHeejin Ahn 17342968611fSHeejin Ahn if (MI.getOpcode() == WebAssembly::DELEGATE) 17352968611fSHeejin Ahn Stack.push_back(std::make_pair(&MBB, &MI)); 17361d68e80fSDan Gohman break; 17371d68e80fSDan Gohman } 17381d68e80fSDan Gohman } 17391d68e80fSDan Gohman } 17401d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 1741e76fa9ecSHeejin Ahn } 17422726b88cSDan Gohman 1743ed41945fSHeejin Ahn void WebAssemblyCFGStackify::cleanupFunctionData(MachineFunction &MF) { 1744ed41945fSHeejin Ahn if (FakeCallerBB) 1745ed41945fSHeejin Ahn MF.DeleteMachineBasicBlock(FakeCallerBB); 1746ed41945fSHeejin Ahn AppendixBB = FakeCallerBB = nullptr; 1747ed41945fSHeejin Ahn } 1748ed41945fSHeejin Ahn 1749e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 1750e76fa9ecSHeejin Ahn ScopeTops.clear(); 1751e76fa9ecSHeejin Ahn BeginToEnd.clear(); 1752e76fa9ecSHeejin Ahn EndToBegin.clear(); 1753e76fa9ecSHeejin Ahn TryToEHPad.clear(); 1754e76fa9ecSHeejin Ahn EHPadToTry.clear(); 17551d68e80fSDan Gohman } 175632807932SDan Gohman 1757950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 1758d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 1759950a13cfSDan Gohman "********** Function: " 1760950a13cfSDan Gohman << MF.getName() << '\n'); 1761cf699b45SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 1762950a13cfSDan Gohman 1763e76fa9ecSHeejin Ahn releaseMemory(); 1764e76fa9ecSHeejin Ahn 1765e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 17669c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 1767950a13cfSDan Gohman 1768e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 1769e76fa9ecSHeejin Ahn placeMarkers(MF); 1770e76fa9ecSHeejin Ahn 1771c4ac74fbSHeejin Ahn // Remove unnecessary instructions possibly introduced by try/end_trys. 1772cf699b45SHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1773cf699b45SHeejin Ahn MF.getFunction().hasPersonalityFn()) 1774cf699b45SHeejin Ahn removeUnnecessaryInstrs(MF); 1775cf699b45SHeejin Ahn 1776e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 1777e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 1778e76fa9ecSHeejin Ahn 1779e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 1780e76fa9ecSHeejin Ahn // WebAssembly's rules. 1781e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 1782e76fa9ecSHeejin Ahn 1783e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 1784e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 1785e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 1786e76fa9ecSHeejin Ahn .getTargetTriple() 1787e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 178818c56a07SHeejin Ahn appendEndToFunction(MF, TII); 178932807932SDan Gohman 1790ed41945fSHeejin Ahn cleanupFunctionData(MF); 1791ed41945fSHeejin Ahn 17921aaa481fSHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified(); 1793950a13cfSDan Gohman return true; 1794950a13cfSDan Gohman } 1795