1950a13cfSDan Gohman //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===// 2950a13cfSDan Gohman // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6950a13cfSDan Gohman // 7950a13cfSDan Gohman //===----------------------------------------------------------------------===// 8950a13cfSDan Gohman /// 9950a13cfSDan Gohman /// \file 105f8f34e4SAdrian Prantl /// This file implements a CFG stacking pass. 11950a13cfSDan Gohman /// 12e76fa9ecSHeejin Ahn /// This pass inserts BLOCK, LOOP, and TRY markers to mark the start of scopes, 13e76fa9ecSHeejin Ahn /// since scope boundaries serve as the labels for WebAssembly's control 14e76fa9ecSHeejin Ahn /// transfers. 15950a13cfSDan Gohman /// 16950a13cfSDan Gohman /// This is sufficient to convert arbitrary CFGs into a form that works on 17950a13cfSDan Gohman /// WebAssembly, provided that all loops are single-entry. 18950a13cfSDan Gohman /// 19e76fa9ecSHeejin Ahn /// In case we use exceptions, this pass also fixes mismatches in unwind 20e76fa9ecSHeejin Ahn /// destinations created during transforming CFG into wasm structured format. 21e76fa9ecSHeejin Ahn /// 22950a13cfSDan Gohman //===----------------------------------------------------------------------===// 23950a13cfSDan Gohman 246bda14b3SChandler Carruth #include "WebAssembly.h" 25e76fa9ecSHeejin Ahn #include "WebAssemblyExceptionInfo.h" 26ed0f1138SDan Gohman #include "WebAssemblyMachineFunctionInfo.h" 27950a13cfSDan Gohman #include "WebAssemblySubtarget.h" 284fc4e42dSDan Gohman #include "WebAssemblyUtilities.h" 29c4ac74fbSHeejin Ahn #include "llvm/ADT/Statistic.h" 3032807932SDan Gohman #include "llvm/CodeGen/MachineDominators.h" 31950a13cfSDan Gohman #include "llvm/CodeGen/MachineInstrBuilder.h" 32904cd3e0SReid Kleckner #include "llvm/CodeGen/MachineLoopInfo.h" 33e76fa9ecSHeejin Ahn #include "llvm/MC/MCAsmInfo.h" 34fe0006c8SSimon Pilgrim #include "llvm/Target/TargetMachine.h" 35950a13cfSDan Gohman using namespace llvm; 36950a13cfSDan Gohman 37950a13cfSDan Gohman #define DEBUG_TYPE "wasm-cfg-stackify" 38950a13cfSDan Gohman 39c4ac74fbSHeejin Ahn STATISTIC(NumUnwindMismatches, "Number of EH pad unwind mismatches found"); 40c4ac74fbSHeejin Ahn 41950a13cfSDan Gohman namespace { 42950a13cfSDan Gohman class WebAssemblyCFGStackify final : public MachineFunctionPass { 43117296c0SMehdi Amini StringRef getPassName() const override { return "WebAssembly CFG Stackify"; } 44950a13cfSDan Gohman 45950a13cfSDan Gohman void getAnalysisUsage(AnalysisUsage &AU) const override { 4632807932SDan Gohman AU.addRequired<MachineDominatorTree>(); 47950a13cfSDan Gohman AU.addRequired<MachineLoopInfo>(); 48e76fa9ecSHeejin Ahn AU.addRequired<WebAssemblyExceptionInfo>(); 49950a13cfSDan Gohman MachineFunctionPass::getAnalysisUsage(AU); 50950a13cfSDan Gohman } 51950a13cfSDan Gohman 52950a13cfSDan Gohman bool runOnMachineFunction(MachineFunction &MF) override; 53950a13cfSDan Gohman 54e76fa9ecSHeejin Ahn // For each block whose label represents the end of a scope, record the block 55e76fa9ecSHeejin Ahn // which holds the beginning of the scope. This will allow us to quickly skip 56e76fa9ecSHeejin Ahn // over scoped regions when walking blocks. 57e76fa9ecSHeejin Ahn SmallVector<MachineBasicBlock *, 8> ScopeTops; 58e76fa9ecSHeejin Ahn 59c4ac74fbSHeejin Ahn // Placing markers. 60e76fa9ecSHeejin Ahn void placeMarkers(MachineFunction &MF); 61e76fa9ecSHeejin Ahn void placeBlockMarker(MachineBasicBlock &MBB); 62e76fa9ecSHeejin Ahn void placeLoopMarker(MachineBasicBlock &MBB); 63e76fa9ecSHeejin Ahn void placeTryMarker(MachineBasicBlock &MBB); 64cf699b45SHeejin Ahn void removeUnnecessaryInstrs(MachineFunction &MF); 65c4ac74fbSHeejin Ahn bool fixUnwindMismatches(MachineFunction &MF); 66e76fa9ecSHeejin Ahn void rewriteDepthImmediates(MachineFunction &MF); 67e76fa9ecSHeejin Ahn void fixEndsAtEndOfFunction(MachineFunction &MF); 68e76fa9ecSHeejin Ahn 69e76fa9ecSHeejin Ahn // For each BLOCK|LOOP|TRY, the corresponding END_(BLOCK|LOOP|TRY). 70e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> BeginToEnd; 71e76fa9ecSHeejin Ahn // For each END_(BLOCK|LOOP|TRY), the corresponding BLOCK|LOOP|TRY. 72e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineInstr *> EndToBegin; 73e76fa9ecSHeejin Ahn // <TRY marker, EH pad> map 74e76fa9ecSHeejin Ahn DenseMap<const MachineInstr *, MachineBasicBlock *> TryToEHPad; 75e76fa9ecSHeejin Ahn // <EH pad, TRY marker> map 76e76fa9ecSHeejin Ahn DenseMap<const MachineBasicBlock *, MachineInstr *> EHPadToTry; 77e76fa9ecSHeejin Ahn 78c4ac74fbSHeejin Ahn // There can be an appendix block at the end of each function, shared for: 79c4ac74fbSHeejin Ahn // - creating a correct signature for fallthrough returns 80c4ac74fbSHeejin Ahn // - target for rethrows that need to unwind to the caller, but are trapped 81c4ac74fbSHeejin Ahn // inside another try/catch 82c4ac74fbSHeejin Ahn MachineBasicBlock *AppendixBB = nullptr; 83c4ac74fbSHeejin Ahn MachineBasicBlock *getAppendixBlock(MachineFunction &MF) { 84c4ac74fbSHeejin Ahn if (!AppendixBB) { 85c4ac74fbSHeejin Ahn AppendixBB = MF.CreateMachineBasicBlock(); 86c4ac74fbSHeejin Ahn // Give it a fake predecessor so that AsmPrinter prints its label. 87c4ac74fbSHeejin Ahn AppendixBB->addSuccessor(AppendixBB); 88c4ac74fbSHeejin Ahn MF.push_back(AppendixBB); 89c4ac74fbSHeejin Ahn } 90c4ac74fbSHeejin Ahn return AppendixBB; 91c4ac74fbSHeejin Ahn } 92c4ac74fbSHeejin Ahn 93cf699b45SHeejin Ahn // Helper functions to register / unregister scope information created by 94cf699b45SHeejin Ahn // marker instructions. 95e76fa9ecSHeejin Ahn void registerScope(MachineInstr *Begin, MachineInstr *End); 96e76fa9ecSHeejin Ahn void registerTryScope(MachineInstr *Begin, MachineInstr *End, 97e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad); 98cf699b45SHeejin Ahn void unregisterScope(MachineInstr *Begin); 99e76fa9ecSHeejin Ahn 100950a13cfSDan Gohman public: 101950a13cfSDan Gohman static char ID; // Pass identification, replacement for typeid 102950a13cfSDan Gohman WebAssemblyCFGStackify() : MachineFunctionPass(ID) {} 103e76fa9ecSHeejin Ahn ~WebAssemblyCFGStackify() override { releaseMemory(); } 104e76fa9ecSHeejin Ahn void releaseMemory() override; 105950a13cfSDan Gohman }; 106950a13cfSDan Gohman } // end anonymous namespace 107950a13cfSDan Gohman 108950a13cfSDan Gohman char WebAssemblyCFGStackify::ID = 0; 10940926451SJacob Gravelle INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, 110c4ac74fbSHeejin Ahn "Insert BLOCK/LOOP/TRY markers for WebAssembly scopes", false, 111f208f631SHeejin Ahn false) 11240926451SJacob Gravelle 113950a13cfSDan Gohman FunctionPass *llvm::createWebAssemblyCFGStackify() { 114950a13cfSDan Gohman return new WebAssemblyCFGStackify(); 115950a13cfSDan Gohman } 116950a13cfSDan Gohman 117b3aa1ecaSDan Gohman /// Test whether Pred has any terminators explicitly branching to MBB, as 118b3aa1ecaSDan Gohman /// opposed to falling through. Note that it's possible (eg. in unoptimized 119b3aa1ecaSDan Gohman /// code) for a branch instruction to both branch to a block and fallthrough 120b3aa1ecaSDan Gohman /// to it, so we check the actual branch operands to see if there are any 121b3aa1ecaSDan Gohman /// explicit mentions. 12218c56a07SHeejin Ahn static bool explicitlyBranchesTo(MachineBasicBlock *Pred, 12335e4a289SDan Gohman MachineBasicBlock *MBB) { 124b3aa1ecaSDan Gohman for (MachineInstr &MI : Pred->terminators()) 125b3aa1ecaSDan Gohman for (MachineOperand &MO : MI.explicit_operands()) 126b3aa1ecaSDan Gohman if (MO.isMBB() && MO.getMBB() == MBB) 127b3aa1ecaSDan Gohman return true; 128b3aa1ecaSDan Gohman return false; 129b3aa1ecaSDan Gohman } 130b3aa1ecaSDan Gohman 131e76fa9ecSHeejin Ahn // Returns an iterator to the earliest position possible within the MBB, 132e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 133e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 134e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, AfterSet is only 135e76fa9ecSHeejin Ahn // used for sanity checking. 136e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 13718c56a07SHeejin Ahn getEarliestInsertPos(MachineBasicBlock *MBB, 138e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 139e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 140e76fa9ecSHeejin Ahn auto InsertPos = MBB->end(); 141e76fa9ecSHeejin Ahn while (InsertPos != MBB->begin()) { 142e76fa9ecSHeejin Ahn if (BeforeSet.count(&*std::prev(InsertPos))) { 143e76fa9ecSHeejin Ahn #ifndef NDEBUG 144e76fa9ecSHeejin Ahn // Sanity check 145e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->begin(); Pos != E; --Pos) 146e76fa9ecSHeejin Ahn assert(!AfterSet.count(&*std::prev(Pos))); 147e76fa9ecSHeejin Ahn #endif 148e76fa9ecSHeejin Ahn break; 149e76fa9ecSHeejin Ahn } 150e76fa9ecSHeejin Ahn --InsertPos; 151e76fa9ecSHeejin Ahn } 152e76fa9ecSHeejin Ahn return InsertPos; 153e76fa9ecSHeejin Ahn } 154e76fa9ecSHeejin Ahn 155e76fa9ecSHeejin Ahn // Returns an iterator to the latest position possible within the MBB, 156e76fa9ecSHeejin Ahn // satisfying the restrictions given by BeforeSet and AfterSet. BeforeSet 157e76fa9ecSHeejin Ahn // contains instructions that should go before the marker, and AfterSet contains 158e76fa9ecSHeejin Ahn // ones that should go after the marker. In this function, BeforeSet is only 159e76fa9ecSHeejin Ahn // used for sanity checking. 160e76fa9ecSHeejin Ahn static MachineBasicBlock::iterator 16118c56a07SHeejin Ahn getLatestInsertPos(MachineBasicBlock *MBB, 162e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &BeforeSet, 163e76fa9ecSHeejin Ahn const SmallPtrSet<const MachineInstr *, 4> &AfterSet) { 164e76fa9ecSHeejin Ahn auto InsertPos = MBB->begin(); 165e76fa9ecSHeejin Ahn while (InsertPos != MBB->end()) { 166e76fa9ecSHeejin Ahn if (AfterSet.count(&*InsertPos)) { 167e76fa9ecSHeejin Ahn #ifndef NDEBUG 168e76fa9ecSHeejin Ahn // Sanity check 169e76fa9ecSHeejin Ahn for (auto Pos = InsertPos, E = MBB->end(); Pos != E; ++Pos) 170e76fa9ecSHeejin Ahn assert(!BeforeSet.count(&*Pos)); 171e76fa9ecSHeejin Ahn #endif 172e76fa9ecSHeejin Ahn break; 173e76fa9ecSHeejin Ahn } 174e76fa9ecSHeejin Ahn ++InsertPos; 175e76fa9ecSHeejin Ahn } 176e76fa9ecSHeejin Ahn return InsertPos; 177e76fa9ecSHeejin Ahn } 178e76fa9ecSHeejin Ahn 179e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerScope(MachineInstr *Begin, 180e76fa9ecSHeejin Ahn MachineInstr *End) { 181e76fa9ecSHeejin Ahn BeginToEnd[Begin] = End; 182e76fa9ecSHeejin Ahn EndToBegin[End] = Begin; 183e76fa9ecSHeejin Ahn } 184e76fa9ecSHeejin Ahn 185e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::registerTryScope(MachineInstr *Begin, 186e76fa9ecSHeejin Ahn MachineInstr *End, 187e76fa9ecSHeejin Ahn MachineBasicBlock *EHPad) { 188e76fa9ecSHeejin Ahn registerScope(Begin, End); 189e76fa9ecSHeejin Ahn TryToEHPad[Begin] = EHPad; 190e76fa9ecSHeejin Ahn EHPadToTry[EHPad] = Begin; 191e76fa9ecSHeejin Ahn } 192e76fa9ecSHeejin Ahn 193cf699b45SHeejin Ahn void WebAssemblyCFGStackify::unregisterScope(MachineInstr *Begin) { 194cf699b45SHeejin Ahn assert(BeginToEnd.count(Begin)); 195cf699b45SHeejin Ahn MachineInstr *End = BeginToEnd[Begin]; 196cf699b45SHeejin Ahn assert(EndToBegin.count(End)); 197cf699b45SHeejin Ahn BeginToEnd.erase(Begin); 198cf699b45SHeejin Ahn EndToBegin.erase(End); 199cf699b45SHeejin Ahn MachineBasicBlock *EHPad = TryToEHPad.lookup(Begin); 200cf699b45SHeejin Ahn if (EHPad) { 201cf699b45SHeejin Ahn assert(EHPadToTry.count(EHPad)); 202cf699b45SHeejin Ahn TryToEHPad.erase(Begin); 203cf699b45SHeejin Ahn EHPadToTry.erase(EHPad); 204cf699b45SHeejin Ahn } 205cf699b45SHeejin Ahn } 206cf699b45SHeejin Ahn 20732807932SDan Gohman /// Insert a BLOCK marker for branches to MBB (if needed). 208c4ac74fbSHeejin Ahn // TODO Consider a more generalized way of handling block (and also loop and 209c4ac74fbSHeejin Ahn // try) signatures when we implement the multi-value proposal later. 210e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeBlockMarker(MachineBasicBlock &MBB) { 21144a5a4b1SHeejin Ahn assert(!MBB.isEHPad()); 212e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 213e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 214e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 215e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 216e76fa9ecSHeejin Ahn 2178fe7e86bSDan Gohman // First compute the nearest common dominator of all forward non-fallthrough 2188fe7e86bSDan Gohman // predecessors so that we minimize the time that the BLOCK is on the stack, 2198fe7e86bSDan Gohman // which reduces overall stack height. 22032807932SDan Gohman MachineBasicBlock *Header = nullptr; 22132807932SDan Gohman bool IsBranchedTo = false; 222d6f48786SHeejin Ahn bool IsBrOnExn = false; 223d6f48786SHeejin Ahn MachineInstr *BrOnExn = nullptr; 22432807932SDan Gohman int MBBNumber = MBB.getNumber(); 225e76fa9ecSHeejin Ahn for (MachineBasicBlock *Pred : MBB.predecessors()) { 22632807932SDan Gohman if (Pred->getNumber() < MBBNumber) { 22732807932SDan Gohman Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 22818c56a07SHeejin Ahn if (explicitlyBranchesTo(Pred, &MBB)) { 22932807932SDan Gohman IsBranchedTo = true; 230d6f48786SHeejin Ahn if (Pred->getFirstTerminator()->getOpcode() == WebAssembly::BR_ON_EXN) { 231d6f48786SHeejin Ahn IsBrOnExn = true; 232d6f48786SHeejin Ahn assert(!BrOnExn && "There should be only one br_on_exn per block"); 233d6f48786SHeejin Ahn BrOnExn = &*Pred->getFirstTerminator(); 234d6f48786SHeejin Ahn } 235d6f48786SHeejin Ahn } 23632807932SDan Gohman } 237e76fa9ecSHeejin Ahn } 23832807932SDan Gohman if (!Header) 23932807932SDan Gohman return; 24032807932SDan Gohman if (!IsBranchedTo) 24132807932SDan Gohman return; 24232807932SDan Gohman 2438fe7e86bSDan Gohman assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors"); 2445c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = MBB.getPrevNode(); 2458fe7e86bSDan Gohman 2468fe7e86bSDan Gohman // If the nearest common dominator is inside a more deeply nested context, 2478fe7e86bSDan Gohman // walk out to the nearest scope which isn't more deeply nested. 2488fe7e86bSDan Gohman for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 2498fe7e86bSDan Gohman if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 2508fe7e86bSDan Gohman if (ScopeTop->getNumber() > Header->getNumber()) { 2518fe7e86bSDan Gohman // Skip over an intervening scope. 2525c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 2538fe7e86bSDan Gohman } else { 2548fe7e86bSDan Gohman // We found a scope level at an appropriate depth. 2558fe7e86bSDan Gohman Header = ScopeTop; 2568fe7e86bSDan Gohman break; 2578fe7e86bSDan Gohman } 2588fe7e86bSDan Gohman } 2598fe7e86bSDan Gohman } 2608fe7e86bSDan Gohman 2618fe7e86bSDan Gohman // Decide where in Header to put the BLOCK. 262e76fa9ecSHeejin Ahn 263e76fa9ecSHeejin Ahn // Instructions that should go before the BLOCK. 264e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 265e76fa9ecSHeejin Ahn // Instructions that should go after the BLOCK. 266e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 267e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 26844a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 26944a5a4b1SHeejin Ahn // loop is above MBB, it should be after the BLOCK, because the loop is 27044a5a4b1SHeejin Ahn // nested in this BLOCK. Otherwise it should be before the BLOCK. 27144a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 27244a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 27344a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 274e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 275e76fa9ecSHeejin Ahn #ifndef NDEBUG 276e76fa9ecSHeejin Ahn else 277e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 278e76fa9ecSHeejin Ahn #endif 279e76fa9ecSHeejin Ahn } 280e76fa9ecSHeejin Ahn 281834debffSHeejin Ahn // If there is a previously placed BLOCK/TRY marker and its corresponding 282834debffSHeejin Ahn // END marker is before the current BLOCK's END marker, that should be 283834debffSHeejin Ahn // placed after this BLOCK. Otherwise it should be placed before this BLOCK 284834debffSHeejin Ahn // marker. 28544a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 286834debffSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) { 287834debffSHeejin Ahn if (BeginToEnd[&MI]->getParent()->getNumber() <= MBB.getNumber()) 288e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 289834debffSHeejin Ahn #ifndef NDEBUG 290834debffSHeejin Ahn else 291834debffSHeejin Ahn BeforeSet.insert(&MI); 292834debffSHeejin Ahn #endif 293834debffSHeejin Ahn } 294e76fa9ecSHeejin Ahn 295e76fa9ecSHeejin Ahn #ifndef NDEBUG 296e76fa9ecSHeejin Ahn // All END_(BLOCK|LOOP|TRY) markers should be before the BLOCK. 297e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 298e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 299e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 300e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 301e76fa9ecSHeejin Ahn #endif 302e76fa9ecSHeejin Ahn 303e76fa9ecSHeejin Ahn // Terminators should go after the BLOCK. 304e76fa9ecSHeejin Ahn if (MI.isTerminator()) 305e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 306e76fa9ecSHeejin Ahn } 307e76fa9ecSHeejin Ahn 308e76fa9ecSHeejin Ahn // Local expression tree should go after the BLOCK. 309e76fa9ecSHeejin Ahn for (auto I = Header->getFirstTerminator(), E = Header->begin(); I != E; 310e76fa9ecSHeejin Ahn --I) { 311409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 312409b4391SYury Delendik continue; 313e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 314e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 315e76fa9ecSHeejin Ahn else 316e76fa9ecSHeejin Ahn break; 31732807932SDan Gohman } 31832807932SDan Gohman 3198fe7e86bSDan Gohman // Add the BLOCK. 320d6f48786SHeejin Ahn 3219f96a58cSHeejin Ahn // 'br_on_exn' extracts exnref object and pushes variable number of values 322d6f48786SHeejin Ahn // depending on its tag. For C++ exception, its a single i32 value, and the 323d6f48786SHeejin Ahn // generated code will be in the form of: 324d6f48786SHeejin Ahn // block i32 325d6f48786SHeejin Ahn // br_on_exn 0, $__cpp_exception 326d6f48786SHeejin Ahn // rethrow 327d6f48786SHeejin Ahn // end_block 3282cb27072SThomas Lively WebAssembly::BlockType ReturnType = WebAssembly::BlockType::Void; 329d6f48786SHeejin Ahn if (IsBrOnExn) { 330d6f48786SHeejin Ahn const char *TagName = BrOnExn->getOperand(1).getSymbolName(); 331d6f48786SHeejin Ahn if (std::strcmp(TagName, "__cpp_exception") != 0) 332d6f48786SHeejin Ahn llvm_unreachable("Only C++ exception is supported"); 3332cb27072SThomas Lively ReturnType = WebAssembly::BlockType::I32; 334d6f48786SHeejin Ahn } 335d6f48786SHeejin Ahn 33618c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 33792401cc1SHeejin Ahn MachineInstr *Begin = 33892401cc1SHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 3392726b88cSDan Gohman TII.get(WebAssembly::BLOCK)) 340d6f48786SHeejin Ahn .addImm(int64_t(ReturnType)); 3411d68e80fSDan Gohman 342e76fa9ecSHeejin Ahn // Decide where in Header to put the END_BLOCK. 343e76fa9ecSHeejin Ahn BeforeSet.clear(); 344e76fa9ecSHeejin Ahn AfterSet.clear(); 345e76fa9ecSHeejin Ahn for (auto &MI : MBB) { 346e76fa9ecSHeejin Ahn #ifndef NDEBUG 347e76fa9ecSHeejin Ahn // END_BLOCK should precede existing LOOP and TRY markers. 348e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 349e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 350e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 351e76fa9ecSHeejin Ahn #endif 352e76fa9ecSHeejin Ahn 353e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and the header of the 354e76fa9ecSHeejin Ahn // loop is above this block's header, the END_LOOP should be placed after 355e76fa9ecSHeejin Ahn // the BLOCK, because the loop contains this block. Otherwise the END_LOOP 356e76fa9ecSHeejin Ahn // should be placed before the BLOCK. The same for END_TRY. 357e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP || 358e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) { 359e76fa9ecSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() >= Header->getNumber()) 360e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 361e76fa9ecSHeejin Ahn #ifndef NDEBUG 362e76fa9ecSHeejin Ahn else 363e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 364e76fa9ecSHeejin Ahn #endif 365e76fa9ecSHeejin Ahn } 366e76fa9ecSHeejin Ahn } 367e76fa9ecSHeejin Ahn 3681d68e80fSDan Gohman // Mark the end of the block. 36918c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 37010b31358SDerek Schuff MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos), 3712726b88cSDan Gohman TII.get(WebAssembly::END_BLOCK)); 372e76fa9ecSHeejin Ahn registerScope(Begin, End); 3738fe7e86bSDan Gohman 3748fe7e86bSDan Gohman // Track the farthest-spanning scope that ends at this point. 3758fe7e86bSDan Gohman int Number = MBB.getNumber(); 3768fe7e86bSDan Gohman if (!ScopeTops[Number] || 3778fe7e86bSDan Gohman ScopeTops[Number]->getNumber() > Header->getNumber()) 3788fe7e86bSDan Gohman ScopeTops[Number] = Header; 379950a13cfSDan Gohman } 380950a13cfSDan Gohman 3818fe7e86bSDan Gohman /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header). 382e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeLoopMarker(MachineBasicBlock &MBB) { 383e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 384e76fa9ecSHeejin Ahn const auto &MLI = getAnalysis<MachineLoopInfo>(); 385e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 386e76fa9ecSHeejin Ahn 3878fe7e86bSDan Gohman MachineLoop *Loop = MLI.getLoopFor(&MBB); 3888fe7e86bSDan Gohman if (!Loop || Loop->getHeader() != &MBB) 3898fe7e86bSDan Gohman return; 3908fe7e86bSDan Gohman 3918fe7e86bSDan Gohman // The operand of a LOOP is the first block after the loop. If the loop is the 3928fe7e86bSDan Gohman // bottom of the function, insert a dummy block at the end. 393817811caSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(Loop); 3945c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 395e3e4a5ffSDan Gohman if (Iter == MF.end()) { 396c4ac74fbSHeejin Ahn getAppendixBlock(MF); 3975c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 398e3e4a5ffSDan Gohman } 3998fe7e86bSDan Gohman MachineBasicBlock *AfterLoop = &*Iter; 400f6857223SDan Gohman 401e76fa9ecSHeejin Ahn // Decide where in Header to put the LOOP. 402e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 403e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 404e76fa9ecSHeejin Ahn for (const auto &MI : MBB) { 405e76fa9ecSHeejin Ahn // LOOP marker should be after any existing loop that ends here. Otherwise 406e76fa9ecSHeejin Ahn // we assume the instruction belongs to the loop. 407e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 408e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 409e76fa9ecSHeejin Ahn #ifndef NDEBUG 410e76fa9ecSHeejin Ahn else 411e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 412e76fa9ecSHeejin Ahn #endif 413e76fa9ecSHeejin Ahn } 414e76fa9ecSHeejin Ahn 415e76fa9ecSHeejin Ahn // Mark the beginning of the loop. 41618c56a07SHeejin Ahn auto InsertPos = getEarliestInsertPos(&MBB, BeforeSet, AfterSet); 41710b31358SDerek Schuff MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos), 4182726b88cSDan Gohman TII.get(WebAssembly::LOOP)) 4192cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 4201d68e80fSDan Gohman 421e76fa9ecSHeejin Ahn // Decide where in Header to put the END_LOOP. 422e76fa9ecSHeejin Ahn BeforeSet.clear(); 423e76fa9ecSHeejin Ahn AfterSet.clear(); 424e76fa9ecSHeejin Ahn #ifndef NDEBUG 425e76fa9ecSHeejin Ahn for (const auto &MI : MBB) 426e76fa9ecSHeejin Ahn // Existing END_LOOP markers belong to parent loops of this loop 427e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) 428e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 429e76fa9ecSHeejin Ahn #endif 430e76fa9ecSHeejin Ahn 431e76fa9ecSHeejin Ahn // Mark the end of the loop (using arbitrary debug location that branched to 432e76fa9ecSHeejin Ahn // the loop end as its location). 43318c56a07SHeejin Ahn InsertPos = getEarliestInsertPos(AfterLoop, BeforeSet, AfterSet); 43467f74aceSHeejin Ahn DebugLoc EndDL = AfterLoop->pred_empty() 43567f74aceSHeejin Ahn ? DebugLoc() 43667f74aceSHeejin Ahn : (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 437e76fa9ecSHeejin Ahn MachineInstr *End = 438e76fa9ecSHeejin Ahn BuildMI(*AfterLoop, InsertPos, EndDL, TII.get(WebAssembly::END_LOOP)); 439e76fa9ecSHeejin Ahn registerScope(Begin, End); 4408fe7e86bSDan Gohman 4418fe7e86bSDan Gohman assert((!ScopeTops[AfterLoop->getNumber()] || 4428fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 443442bfcecSDan Gohman "With block sorting the outermost loop for a block should be first."); 4448fe7e86bSDan Gohman if (!ScopeTops[AfterLoop->getNumber()]) 4458fe7e86bSDan Gohman ScopeTops[AfterLoop->getNumber()] = &MBB; 446e3e4a5ffSDan Gohman } 447950a13cfSDan Gohman 448e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeTryMarker(MachineBasicBlock &MBB) { 44944a5a4b1SHeejin Ahn assert(MBB.isEHPad()); 450e76fa9ecSHeejin Ahn MachineFunction &MF = *MBB.getParent(); 451e76fa9ecSHeejin Ahn auto &MDT = getAnalysis<MachineDominatorTree>(); 452e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 453e76fa9ecSHeejin Ahn const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>(); 454e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 455e76fa9ecSHeejin Ahn 456e76fa9ecSHeejin Ahn // Compute the nearest common dominator of all unwind predecessors 457e76fa9ecSHeejin Ahn MachineBasicBlock *Header = nullptr; 458e76fa9ecSHeejin Ahn int MBBNumber = MBB.getNumber(); 459e76fa9ecSHeejin Ahn for (auto *Pred : MBB.predecessors()) { 460e76fa9ecSHeejin Ahn if (Pred->getNumber() < MBBNumber) { 461e76fa9ecSHeejin Ahn Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred; 46218c56a07SHeejin Ahn assert(!explicitlyBranchesTo(Pred, &MBB) && 463e76fa9ecSHeejin Ahn "Explicit branch to an EH pad!"); 464e76fa9ecSHeejin Ahn } 465e76fa9ecSHeejin Ahn } 466e76fa9ecSHeejin Ahn if (!Header) 467e76fa9ecSHeejin Ahn return; 468e76fa9ecSHeejin Ahn 469e76fa9ecSHeejin Ahn // If this try is at the bottom of the function, insert a dummy block at the 470e76fa9ecSHeejin Ahn // end. 471e76fa9ecSHeejin Ahn WebAssemblyException *WE = WEI.getExceptionFor(&MBB); 472e76fa9ecSHeejin Ahn assert(WE); 473e76fa9ecSHeejin Ahn MachineBasicBlock *Bottom = WebAssembly::getBottom(WE); 474e76fa9ecSHeejin Ahn 4755c644c9bSHeejin Ahn auto Iter = std::next(Bottom->getIterator()); 476e76fa9ecSHeejin Ahn if (Iter == MF.end()) { 477c4ac74fbSHeejin Ahn getAppendixBlock(MF); 4785c644c9bSHeejin Ahn Iter = std::next(Bottom->getIterator()); 479e76fa9ecSHeejin Ahn } 48020cf0749SHeejin Ahn MachineBasicBlock *Cont = &*Iter; 481e76fa9ecSHeejin Ahn 48220cf0749SHeejin Ahn assert(Cont != &MF.front()); 4835c644c9bSHeejin Ahn MachineBasicBlock *LayoutPred = Cont->getPrevNode(); 484e76fa9ecSHeejin Ahn 485e76fa9ecSHeejin Ahn // If the nearest common dominator is inside a more deeply nested context, 486e76fa9ecSHeejin Ahn // walk out to the nearest scope which isn't more deeply nested. 487e76fa9ecSHeejin Ahn for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) { 488e76fa9ecSHeejin Ahn if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) { 489e76fa9ecSHeejin Ahn if (ScopeTop->getNumber() > Header->getNumber()) { 490e76fa9ecSHeejin Ahn // Skip over an intervening scope. 4915c644c9bSHeejin Ahn I = std::next(ScopeTop->getIterator()); 492e76fa9ecSHeejin Ahn } else { 493e76fa9ecSHeejin Ahn // We found a scope level at an appropriate depth. 494e76fa9ecSHeejin Ahn Header = ScopeTop; 495e76fa9ecSHeejin Ahn break; 496e76fa9ecSHeejin Ahn } 497e76fa9ecSHeejin Ahn } 498e76fa9ecSHeejin Ahn } 499e76fa9ecSHeejin Ahn 500e76fa9ecSHeejin Ahn // Decide where in Header to put the TRY. 501e76fa9ecSHeejin Ahn 50244a5a4b1SHeejin Ahn // Instructions that should go before the TRY. 503e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> BeforeSet; 50444a5a4b1SHeejin Ahn // Instructions that should go after the TRY. 505e76fa9ecSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 506e76fa9ecSHeejin Ahn for (const auto &MI : *Header) { 50744a5a4b1SHeejin Ahn // If there is a previously placed LOOP marker and the bottom block of the 50844a5a4b1SHeejin Ahn // loop is above MBB, it should be after the TRY, because the loop is nested 50944a5a4b1SHeejin Ahn // in this TRY. Otherwise it should be before the TRY. 510e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP) { 51144a5a4b1SHeejin Ahn auto *LoopBottom = BeginToEnd[&MI]->getParent()->getPrevNode(); 51244a5a4b1SHeejin Ahn if (MBB.getNumber() > LoopBottom->getNumber()) 513e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 514e76fa9ecSHeejin Ahn #ifndef NDEBUG 515e76fa9ecSHeejin Ahn else 516e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 517e76fa9ecSHeejin Ahn #endif 518e76fa9ecSHeejin Ahn } 519e76fa9ecSHeejin Ahn 52044a5a4b1SHeejin Ahn // All previously inserted BLOCK/TRY markers should be after the TRY because 52144a5a4b1SHeejin Ahn // they are all nested trys. 52244a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::BLOCK || 52344a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::TRY) 524e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 525e76fa9ecSHeejin Ahn 526e76fa9ecSHeejin Ahn #ifndef NDEBUG 52744a5a4b1SHeejin Ahn // All END_(BLOCK/LOOP/TRY) markers should be before the TRY. 52844a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::END_BLOCK || 52944a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::END_LOOP || 530e76fa9ecSHeejin Ahn MI.getOpcode() == WebAssembly::END_TRY) 531e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 532e76fa9ecSHeejin Ahn #endif 533e76fa9ecSHeejin Ahn 534e76fa9ecSHeejin Ahn // Terminators should go after the TRY. 535e76fa9ecSHeejin Ahn if (MI.isTerminator()) 536e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 537e76fa9ecSHeejin Ahn } 538e76fa9ecSHeejin Ahn 5396a37c5d6SHeejin Ahn // If Header unwinds to MBB (= Header contains 'invoke'), the try block should 5406a37c5d6SHeejin Ahn // contain the call within it. So the call should go after the TRY. The 5416a37c5d6SHeejin Ahn // exception is when the header's terminator is a rethrow instruction, in 5426a37c5d6SHeejin Ahn // which case that instruction, not a call instruction before it, is gonna 5436a37c5d6SHeejin Ahn // throw. 5446a37c5d6SHeejin Ahn MachineInstr *ThrowingCall = nullptr; 5456a37c5d6SHeejin Ahn if (MBB.isPredecessor(Header)) { 5466a37c5d6SHeejin Ahn auto TermPos = Header->getFirstTerminator(); 5476a37c5d6SHeejin Ahn if (TermPos == Header->end() || 5486a37c5d6SHeejin Ahn TermPos->getOpcode() != WebAssembly::RETHROW) { 5496a37c5d6SHeejin Ahn for (auto &MI : reverse(*Header)) { 5506a37c5d6SHeejin Ahn if (MI.isCall()) { 5516a37c5d6SHeejin Ahn AfterSet.insert(&MI); 5526a37c5d6SHeejin Ahn ThrowingCall = &MI; 5536a37c5d6SHeejin Ahn // Possibly throwing calls are usually wrapped by EH_LABEL 5546a37c5d6SHeejin Ahn // instructions. We don't want to split them and the call. 5556a37c5d6SHeejin Ahn if (MI.getIterator() != Header->begin() && 5566a37c5d6SHeejin Ahn std::prev(MI.getIterator())->isEHLabel()) { 5576a37c5d6SHeejin Ahn AfterSet.insert(&*std::prev(MI.getIterator())); 5586a37c5d6SHeejin Ahn ThrowingCall = &*std::prev(MI.getIterator()); 5596a37c5d6SHeejin Ahn } 5606a37c5d6SHeejin Ahn break; 5616a37c5d6SHeejin Ahn } 5626a37c5d6SHeejin Ahn } 5636a37c5d6SHeejin Ahn } 5646a37c5d6SHeejin Ahn } 5656a37c5d6SHeejin Ahn 566e76fa9ecSHeejin Ahn // Local expression tree should go after the TRY. 5676a37c5d6SHeejin Ahn // For BLOCK placement, we start the search from the previous instruction of a 5686a37c5d6SHeejin Ahn // BB's terminator, but in TRY's case, we should start from the previous 5696a37c5d6SHeejin Ahn // instruction of a call that can throw, or a EH_LABEL that precedes the call, 5706a37c5d6SHeejin Ahn // because the return values of the call's previous instructions can be 5716a37c5d6SHeejin Ahn // stackified and consumed by the throwing call. 5726a37c5d6SHeejin Ahn auto SearchStartPt = ThrowingCall ? MachineBasicBlock::iterator(ThrowingCall) 5736a37c5d6SHeejin Ahn : Header->getFirstTerminator(); 5746a37c5d6SHeejin Ahn for (auto I = SearchStartPt, E = Header->begin(); I != E; --I) { 575409b4391SYury Delendik if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 576409b4391SYury Delendik continue; 577e76fa9ecSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 578e76fa9ecSHeejin Ahn AfterSet.insert(&*std::prev(I)); 579e76fa9ecSHeejin Ahn else 580e76fa9ecSHeejin Ahn break; 581e76fa9ecSHeejin Ahn } 582e76fa9ecSHeejin Ahn 583e76fa9ecSHeejin Ahn // Add the TRY. 58418c56a07SHeejin Ahn auto InsertPos = getLatestInsertPos(Header, BeforeSet, AfterSet); 585e76fa9ecSHeejin Ahn MachineInstr *Begin = 586e76fa9ecSHeejin Ahn BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos), 587e76fa9ecSHeejin Ahn TII.get(WebAssembly::TRY)) 5882cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 589e76fa9ecSHeejin Ahn 590e76fa9ecSHeejin Ahn // Decide where in Header to put the END_TRY. 591e76fa9ecSHeejin Ahn BeforeSet.clear(); 592e76fa9ecSHeejin Ahn AfterSet.clear(); 59320cf0749SHeejin Ahn for (const auto &MI : *Cont) { 594e76fa9ecSHeejin Ahn #ifndef NDEBUG 59544a5a4b1SHeejin Ahn // END_TRY should precede existing LOOP and BLOCK markers. 59644a5a4b1SHeejin Ahn if (MI.getOpcode() == WebAssembly::LOOP || 59744a5a4b1SHeejin Ahn MI.getOpcode() == WebAssembly::BLOCK) 598e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 599e76fa9ecSHeejin Ahn 600e76fa9ecSHeejin Ahn // All END_TRY markers placed earlier belong to exceptions that contains 601e76fa9ecSHeejin Ahn // this one. 602e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_TRY) 603e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 604e76fa9ecSHeejin Ahn #endif 605e76fa9ecSHeejin Ahn 606e76fa9ecSHeejin Ahn // If there is a previously placed END_LOOP marker and its header is after 607e76fa9ecSHeejin Ahn // where TRY marker is, this loop is contained within the 'catch' part, so 608e76fa9ecSHeejin Ahn // the END_TRY marker should go after that. Otherwise, the whole try-catch 609e76fa9ecSHeejin Ahn // is contained within this loop, so the END_TRY should go before that. 610e76fa9ecSHeejin Ahn if (MI.getOpcode() == WebAssembly::END_LOOP) { 611222718fdSHeejin Ahn // For a LOOP to be after TRY, LOOP's BB should be after TRY's BB; if they 612222718fdSHeejin Ahn // are in the same BB, LOOP is always before TRY. 613222718fdSHeejin Ahn if (EndToBegin[&MI]->getParent()->getNumber() > Header->getNumber()) 614e76fa9ecSHeejin Ahn BeforeSet.insert(&MI); 615e76fa9ecSHeejin Ahn #ifndef NDEBUG 616e76fa9ecSHeejin Ahn else 617e76fa9ecSHeejin Ahn AfterSet.insert(&MI); 618e76fa9ecSHeejin Ahn #endif 619e76fa9ecSHeejin Ahn } 62044a5a4b1SHeejin Ahn 62144a5a4b1SHeejin Ahn // It is not possible for an END_BLOCK to be already in this block. 622e76fa9ecSHeejin Ahn } 623e76fa9ecSHeejin Ahn 624e76fa9ecSHeejin Ahn // Mark the end of the TRY. 62520cf0749SHeejin Ahn InsertPos = getEarliestInsertPos(Cont, BeforeSet, AfterSet); 626e76fa9ecSHeejin Ahn MachineInstr *End = 62720cf0749SHeejin Ahn BuildMI(*Cont, InsertPos, Bottom->findBranchDebugLoc(), 628e76fa9ecSHeejin Ahn TII.get(WebAssembly::END_TRY)); 629e76fa9ecSHeejin Ahn registerTryScope(Begin, End, &MBB); 630e76fa9ecSHeejin Ahn 63182da1ffcSHeejin Ahn // Track the farthest-spanning scope that ends at this point. We create two 63282da1ffcSHeejin Ahn // mappings: (BB with 'end_try' -> BB with 'try') and (BB with 'catch' -> BB 63382da1ffcSHeejin Ahn // with 'try'). We need to create 'catch' -> 'try' mapping here too because 63482da1ffcSHeejin Ahn // markers should not span across 'catch'. For example, this should not 63582da1ffcSHeejin Ahn // happen: 63682da1ffcSHeejin Ahn // 63782da1ffcSHeejin Ahn // try 63882da1ffcSHeejin Ahn // block --| (X) 63982da1ffcSHeejin Ahn // catch | 64082da1ffcSHeejin Ahn // end_block --| 64182da1ffcSHeejin Ahn // end_try 64282da1ffcSHeejin Ahn for (int Number : {Cont->getNumber(), MBB.getNumber()}) { 643e76fa9ecSHeejin Ahn if (!ScopeTops[Number] || 644e76fa9ecSHeejin Ahn ScopeTops[Number]->getNumber() > Header->getNumber()) 645e76fa9ecSHeejin Ahn ScopeTops[Number] = Header; 646e76fa9ecSHeejin Ahn } 64782da1ffcSHeejin Ahn } 648e76fa9ecSHeejin Ahn 649cf699b45SHeejin Ahn void WebAssemblyCFGStackify::removeUnnecessaryInstrs(MachineFunction &MF) { 650cf699b45SHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 651cf699b45SHeejin Ahn 652cf699b45SHeejin Ahn // When there is an unconditional branch right before a catch instruction and 653cf699b45SHeejin Ahn // it branches to the end of end_try marker, we don't need the branch, because 654cf699b45SHeejin Ahn // it there is no exception, the control flow transfers to that point anyway. 655cf699b45SHeejin Ahn // bb0: 656cf699b45SHeejin Ahn // try 657cf699b45SHeejin Ahn // ... 658cf699b45SHeejin Ahn // br bb2 <- Not necessary 659cf699b45SHeejin Ahn // bb1: 660cf699b45SHeejin Ahn // catch 661cf699b45SHeejin Ahn // ... 662cf699b45SHeejin Ahn // bb2: 663cf699b45SHeejin Ahn // end 664cf699b45SHeejin Ahn for (auto &MBB : MF) { 665cf699b45SHeejin Ahn if (!MBB.isEHPad()) 666cf699b45SHeejin Ahn continue; 667cf699b45SHeejin Ahn 668cf699b45SHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 669cf699b45SHeejin Ahn SmallVector<MachineOperand, 4> Cond; 6705c644c9bSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = MBB.getPrevNode(); 671cf699b45SHeejin Ahn MachineBasicBlock *Cont = BeginToEnd[EHPadToTry[&MBB]]->getParent(); 672cf699b45SHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 673*3fe6ea46SHeejin Ahn // This condition means either 674*3fe6ea46SHeejin Ahn // 1. This BB ends with a single unconditional branch whose destinaion is 675*3fe6ea46SHeejin Ahn // Cont. 676*3fe6ea46SHeejin Ahn // 2. This BB ends with a conditional branch followed by an unconditional 677*3fe6ea46SHeejin Ahn // branch, and the unconditional branch's destination is Cont. 678*3fe6ea46SHeejin Ahn // In both cases, we want to remove the last (= unconditional) branch. 679cf699b45SHeejin Ahn if (Analyzable && ((Cond.empty() && TBB && TBB == Cont) || 680*3fe6ea46SHeejin Ahn (!Cond.empty() && FBB && FBB == Cont))) { 681*3fe6ea46SHeejin Ahn bool ErasedUncondBr = false; 682*3fe6ea46SHeejin Ahn for (auto I = EHPadLayoutPred->end(), E = EHPadLayoutPred->begin(); 683*3fe6ea46SHeejin Ahn I != E; --I) { 684*3fe6ea46SHeejin Ahn auto PrevI = std::prev(I); 685*3fe6ea46SHeejin Ahn if (PrevI->isTerminator()) { 686*3fe6ea46SHeejin Ahn assert(PrevI->getOpcode() == WebAssembly::BR); 687*3fe6ea46SHeejin Ahn PrevI->eraseFromParent(); 688*3fe6ea46SHeejin Ahn ErasedUncondBr = true; 689*3fe6ea46SHeejin Ahn break; 690*3fe6ea46SHeejin Ahn } 691*3fe6ea46SHeejin Ahn } 692*3fe6ea46SHeejin Ahn assert(ErasedUncondBr && "Unconditional branch not erased!"); 693*3fe6ea46SHeejin Ahn } 694cf699b45SHeejin Ahn } 695cf699b45SHeejin Ahn 696cf699b45SHeejin Ahn // When there are block / end_block markers that overlap with try / end_try 697cf699b45SHeejin Ahn // markers, and the block and try markers' return types are the same, the 698cf699b45SHeejin Ahn // block /end_block markers are not necessary, because try / end_try markers 699cf699b45SHeejin Ahn // also can serve as boundaries for branches. 700cf699b45SHeejin Ahn // block <- Not necessary 701cf699b45SHeejin Ahn // try 702cf699b45SHeejin Ahn // ... 703cf699b45SHeejin Ahn // catch 704cf699b45SHeejin Ahn // ... 705cf699b45SHeejin Ahn // end 706cf699b45SHeejin Ahn // end <- Not necessary 707cf699b45SHeejin Ahn SmallVector<MachineInstr *, 32> ToDelete; 708cf699b45SHeejin Ahn for (auto &MBB : MF) { 709cf699b45SHeejin Ahn for (auto &MI : MBB) { 710cf699b45SHeejin Ahn if (MI.getOpcode() != WebAssembly::TRY) 711cf699b45SHeejin Ahn continue; 712cf699b45SHeejin Ahn 713cf699b45SHeejin Ahn MachineInstr *Try = &MI, *EndTry = BeginToEnd[Try]; 714cf699b45SHeejin Ahn MachineBasicBlock *TryBB = Try->getParent(); 715cf699b45SHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent(); 716cf699b45SHeejin Ahn int64_t RetType = Try->getOperand(0).getImm(); 7175c644c9bSHeejin Ahn for (auto B = Try->getIterator(), E = std::next(EndTry->getIterator()); 718cf699b45SHeejin Ahn B != TryBB->begin() && E != Cont->end() && 719cf699b45SHeejin Ahn std::prev(B)->getOpcode() == WebAssembly::BLOCK && 720cf699b45SHeejin Ahn E->getOpcode() == WebAssembly::END_BLOCK && 721cf699b45SHeejin Ahn std::prev(B)->getOperand(0).getImm() == RetType; 722cf699b45SHeejin Ahn --B, ++E) { 723cf699b45SHeejin Ahn ToDelete.push_back(&*std::prev(B)); 724cf699b45SHeejin Ahn ToDelete.push_back(&*E); 725cf699b45SHeejin Ahn } 726cf699b45SHeejin Ahn } 727cf699b45SHeejin Ahn } 728cf699b45SHeejin Ahn for (auto *MI : ToDelete) { 729cf699b45SHeejin Ahn if (MI->getOpcode() == WebAssembly::BLOCK) 730cf699b45SHeejin Ahn unregisterScope(MI); 731cf699b45SHeejin Ahn MI->eraseFromParent(); 732cf699b45SHeejin Ahn } 733cf699b45SHeejin Ahn } 734cf699b45SHeejin Ahn 73561d5c76aSHeejin Ahn // When MBB is split into MBB and Split, we should unstackify defs in MBB that 73661d5c76aSHeejin Ahn // have their uses in Split. 73761d5c76aSHeejin Ahn static void unstackifyVRegsUsedInSplitBB(MachineBasicBlock &MBB, 73861d5c76aSHeejin Ahn MachineBasicBlock &Split, 73961d5c76aSHeejin Ahn WebAssemblyFunctionInfo &MFI, 74061d5c76aSHeejin Ahn MachineRegisterInfo &MRI) { 74161d5c76aSHeejin Ahn for (auto &MI : Split) { 74261d5c76aSHeejin Ahn for (auto &MO : MI.explicit_uses()) { 74361d5c76aSHeejin Ahn if (!MO.isReg() || Register::isPhysicalRegister(MO.getReg())) 74461d5c76aSHeejin Ahn continue; 74561d5c76aSHeejin Ahn if (MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg())) 74661d5c76aSHeejin Ahn if (Def->getParent() == &MBB) 74761d5c76aSHeejin Ahn MFI.unstackifyVReg(MO.getReg()); 74861d5c76aSHeejin Ahn } 74961d5c76aSHeejin Ahn } 75061d5c76aSHeejin Ahn } 75161d5c76aSHeejin Ahn 752c4ac74fbSHeejin Ahn bool WebAssemblyCFGStackify::fixUnwindMismatches(MachineFunction &MF) { 753c4ac74fbSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 75461d5c76aSHeejin Ahn auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 755c4ac74fbSHeejin Ahn MachineRegisterInfo &MRI = MF.getRegInfo(); 756c4ac74fbSHeejin Ahn 757c4ac74fbSHeejin Ahn // Linearizing the control flow by placing TRY / END_TRY markers can create 758c4ac74fbSHeejin Ahn // mismatches in unwind destinations. There are two kinds of mismatches we 759c4ac74fbSHeejin Ahn // try to solve here. 760c4ac74fbSHeejin Ahn 761c4ac74fbSHeejin Ahn // 1. When an instruction may throw, but the EH pad it will unwind to can be 762c4ac74fbSHeejin Ahn // different from the original CFG. 763c4ac74fbSHeejin Ahn // 764c4ac74fbSHeejin Ahn // Example: we have the following CFG: 765c4ac74fbSHeejin Ahn // bb0: 766c4ac74fbSHeejin Ahn // call @foo (if it throws, unwind to bb2) 767c4ac74fbSHeejin Ahn // bb1: 768c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to bb3) 769c4ac74fbSHeejin Ahn // bb2 (ehpad): 770c4ac74fbSHeejin Ahn // catch 771c4ac74fbSHeejin Ahn // ... 772c4ac74fbSHeejin Ahn // bb3 (ehpad) 773c4ac74fbSHeejin Ahn // catch 774c4ac74fbSHeejin Ahn // handler body 775c4ac74fbSHeejin Ahn // 776c4ac74fbSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 777c4ac74fbSHeejin Ahn // will look like: (BB markers are omitted) 778c4ac74fbSHeejin Ahn // try $label1 779c4ac74fbSHeejin Ahn // try 780c4ac74fbSHeejin Ahn // call @foo 781c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to bb3) 782c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 783c4ac74fbSHeejin Ahn // ... 784c4ac74fbSHeejin Ahn // end_try 785c4ac74fbSHeejin Ahn // catch <- ehpad (bb3) 786c4ac74fbSHeejin Ahn // handler body 787c4ac74fbSHeejin Ahn // end_try 788c4ac74fbSHeejin Ahn // 789c4ac74fbSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, not bb3, where it 790c4ac74fbSHeejin Ahn // is supposed to end up. We solve this problem by 791c4ac74fbSHeejin Ahn // a. Split the target unwind EH pad (here bb3) so that the handler body is 792c4ac74fbSHeejin Ahn // right after 'end_try', which means we extract the handler body out of 793c4ac74fbSHeejin Ahn // the catch block. We do this because this handler body should be 794c4ac74fbSHeejin Ahn // somewhere branch-eable from the inner scope. 795c4ac74fbSHeejin Ahn // b. Wrap the call that has an incorrect unwind destination ('call @bar' 796c4ac74fbSHeejin Ahn // here) with a nested try/catch/end_try scope, and within the new catch 797c4ac74fbSHeejin Ahn // block, branches to the handler body. 798c4ac74fbSHeejin Ahn // c. Place a branch after the newly inserted nested end_try so it can bypass 799c4ac74fbSHeejin Ahn // the handler body, which is now outside of a catch block. 800c4ac74fbSHeejin Ahn // 801c4ac74fbSHeejin Ahn // The result will like as follows. (new: a) means this instruction is newly 802c4ac74fbSHeejin Ahn // created in the process of doing 'a' above. 803c4ac74fbSHeejin Ahn // 804c4ac74fbSHeejin Ahn // block $label0 (new: placeBlockMarker) 805c4ac74fbSHeejin Ahn // try $label1 806c4ac74fbSHeejin Ahn // try 807c4ac74fbSHeejin Ahn // call @foo 808c4ac74fbSHeejin Ahn // try (new: b) 809c4ac74fbSHeejin Ahn // call @bar 810c4ac74fbSHeejin Ahn // catch (new: b) 811c4ac74fbSHeejin Ahn // local.set n / drop (new: b) 812c4ac74fbSHeejin Ahn // br $label1 (new: b) 813c4ac74fbSHeejin Ahn // end_try (new: b) 814c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 815c4ac74fbSHeejin Ahn // end_try 816c4ac74fbSHeejin Ahn // br $label0 (new: c) 817c4ac74fbSHeejin Ahn // catch <- ehpad (bb3) 818c4ac74fbSHeejin Ahn // end_try (hoisted: a) 819c4ac74fbSHeejin Ahn // handler body 820c4ac74fbSHeejin Ahn // end_block (new: placeBlockMarker) 821c4ac74fbSHeejin Ahn // 822c4ac74fbSHeejin Ahn // Note that the new wrapping block/end_block will be generated later in 823c4ac74fbSHeejin Ahn // placeBlockMarker. 824c4ac74fbSHeejin Ahn // 8259f96a58cSHeejin Ahn // TODO Currently local.set and local.gets are generated to move exnref value 8269f96a58cSHeejin Ahn // created by catches. That's because we don't support yielding values from a 8279f96a58cSHeejin Ahn // block in LLVM machine IR yet, even though it is supported by wasm. Delete 8289f96a58cSHeejin Ahn // unnecessary local.get/local.sets once yielding values from a block is 8299f96a58cSHeejin Ahn // supported. The full EH spec requires multi-value support to do this, but 830c4ac74fbSHeejin Ahn // for C++ we don't yet need it because we only throw a single i32. 831c4ac74fbSHeejin Ahn // 832c4ac74fbSHeejin Ahn // --- 833c4ac74fbSHeejin Ahn // 2. The same as 1, but in this case an instruction unwinds to a caller 834c4ac74fbSHeejin Ahn // function and not another EH pad. 835c4ac74fbSHeejin Ahn // 836c4ac74fbSHeejin Ahn // Example: we have the following CFG: 837c4ac74fbSHeejin Ahn // bb0: 838c4ac74fbSHeejin Ahn // call @foo (if it throws, unwind to bb2) 839c4ac74fbSHeejin Ahn // bb1: 840c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to caller) 841c4ac74fbSHeejin Ahn // bb2 (ehpad): 842c4ac74fbSHeejin Ahn // catch 843c4ac74fbSHeejin Ahn // ... 844c4ac74fbSHeejin Ahn // 845c4ac74fbSHeejin Ahn // And the CFG is sorted in this order. Then after placing TRY markers, it 846c4ac74fbSHeejin Ahn // will look like: 847c4ac74fbSHeejin Ahn // try 848c4ac74fbSHeejin Ahn // call @foo 849c4ac74fbSHeejin Ahn // call @bar (if it throws, unwind to caller) 850c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 851c4ac74fbSHeejin Ahn // ... 852c4ac74fbSHeejin Ahn // end_try 853c4ac74fbSHeejin Ahn // 854c4ac74fbSHeejin Ahn // Now if bar() throws, it is going to end up ip in bb2, when it is supposed 855c4ac74fbSHeejin Ahn // throw up to the caller. 856c4ac74fbSHeejin Ahn // We solve this problem by 857c4ac74fbSHeejin Ahn // a. Create a new 'appendix' BB at the end of the function and put a single 858c4ac74fbSHeejin Ahn // 'rethrow' instruction (+ local.get) in there. 859c4ac74fbSHeejin Ahn // b. Wrap the call that has an incorrect unwind destination ('call @bar' 860c4ac74fbSHeejin Ahn // here) with a nested try/catch/end_try scope, and within the new catch 861c4ac74fbSHeejin Ahn // block, branches to the new appendix block. 862c4ac74fbSHeejin Ahn // 863c4ac74fbSHeejin Ahn // block $label0 (new: placeBlockMarker) 864c4ac74fbSHeejin Ahn // try 865c4ac74fbSHeejin Ahn // call @foo 866c4ac74fbSHeejin Ahn // try (new: b) 867c4ac74fbSHeejin Ahn // call @bar 868c4ac74fbSHeejin Ahn // catch (new: b) 869c4ac74fbSHeejin Ahn // local.set n (new: b) 870c4ac74fbSHeejin Ahn // br $label0 (new: b) 871c4ac74fbSHeejin Ahn // end_try (new: b) 872c4ac74fbSHeejin Ahn // catch <- ehpad (bb2) 873c4ac74fbSHeejin Ahn // ... 874c4ac74fbSHeejin Ahn // end_try 875c4ac74fbSHeejin Ahn // ... 876c4ac74fbSHeejin Ahn // end_block (new: placeBlockMarker) 877c4ac74fbSHeejin Ahn // local.get n (new: a) <- appendix block 878c4ac74fbSHeejin Ahn // rethrow (new: a) 879c4ac74fbSHeejin Ahn // 880c4ac74fbSHeejin Ahn // In case there are multiple calls in a BB that may throw to the caller, they 881c4ac74fbSHeejin Ahn // can be wrapped together in one nested try scope. (In 1, this couldn't 882c4ac74fbSHeejin Ahn // happen, because may-throwing instruction there had an unwind destination, 883c4ac74fbSHeejin Ahn // i.e., it was an invoke before, and there could be only one invoke within a 884c4ac74fbSHeejin Ahn // BB.) 885c4ac74fbSHeejin Ahn 886c4ac74fbSHeejin Ahn SmallVector<const MachineBasicBlock *, 8> EHPadStack; 887c4ac74fbSHeejin Ahn // Range of intructions to be wrapped in a new nested try/catch 888c4ac74fbSHeejin Ahn using TryRange = std::pair<MachineInstr *, MachineInstr *>; 889daeead4bSHeejin Ahn // In original CFG, <unwind destination BB, a vector of try ranges> 890c4ac74fbSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> UnwindDestToTryRanges; 891c4ac74fbSHeejin Ahn // In new CFG, <destination to branch to, a vector of try ranges> 892c4ac74fbSHeejin Ahn DenseMap<MachineBasicBlock *, SmallVector<TryRange, 4>> BrDestToTryRanges; 8939f96a58cSHeejin Ahn // In new CFG, <destination to branch to, register containing exnref> 894c4ac74fbSHeejin Ahn DenseMap<MachineBasicBlock *, unsigned> BrDestToExnReg; 895c4ac74fbSHeejin Ahn 896834debffSHeejin Ahn // Destinations for branches that will be newly added, for which a new 897834debffSHeejin Ahn // BLOCK/END_BLOCK markers are necessary. 898834debffSHeejin Ahn SmallVector<MachineBasicBlock *, 8> BrDests; 899834debffSHeejin Ahn 900c4ac74fbSHeejin Ahn // Gather possibly throwing calls (i.e., previously invokes) whose current 901c4ac74fbSHeejin Ahn // unwind destination is not the same as the original CFG. 902c4ac74fbSHeejin Ahn for (auto &MBB : reverse(MF)) { 903c4ac74fbSHeejin Ahn bool SeenThrowableInstInBB = false; 904c4ac74fbSHeejin Ahn for (auto &MI : reverse(MBB)) { 905c4ac74fbSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 906c4ac74fbSHeejin Ahn EHPadStack.pop_back(); 907c4ac74fbSHeejin Ahn else if (MI.getOpcode() == WebAssembly::CATCH) 908c4ac74fbSHeejin Ahn EHPadStack.push_back(MI.getParent()); 909c4ac74fbSHeejin Ahn 910c4ac74fbSHeejin Ahn // In this loop we only gather calls that have an EH pad to unwind. So 911c4ac74fbSHeejin Ahn // there will be at most 1 such call (= invoke) in a BB, so after we've 912c4ac74fbSHeejin Ahn // seen one, we can skip the rest of BB. Also if MBB has no EH pad 913c4ac74fbSHeejin Ahn // successor or MI does not throw, this is not an invoke. 914c4ac74fbSHeejin Ahn if (SeenThrowableInstInBB || !MBB.hasEHPadSuccessor() || 915c4ac74fbSHeejin Ahn !WebAssembly::mayThrow(MI)) 916c4ac74fbSHeejin Ahn continue; 917c4ac74fbSHeejin Ahn SeenThrowableInstInBB = true; 918c4ac74fbSHeejin Ahn 919c4ac74fbSHeejin Ahn // If the EH pad on the stack top is where this instruction should unwind 920c4ac74fbSHeejin Ahn // next, we're good. 921c4ac74fbSHeejin Ahn MachineBasicBlock *UnwindDest = nullptr; 922c4ac74fbSHeejin Ahn for (auto *Succ : MBB.successors()) { 923c4ac74fbSHeejin Ahn if (Succ->isEHPad()) { 924c4ac74fbSHeejin Ahn UnwindDest = Succ; 925c4ac74fbSHeejin Ahn break; 926c4ac74fbSHeejin Ahn } 927c4ac74fbSHeejin Ahn } 928c4ac74fbSHeejin Ahn if (EHPadStack.back() == UnwindDest) 929c4ac74fbSHeejin Ahn continue; 930c4ac74fbSHeejin Ahn 931c4ac74fbSHeejin Ahn // If not, record the range. 932c4ac74fbSHeejin Ahn UnwindDestToTryRanges[UnwindDest].push_back(TryRange(&MI, &MI)); 933c4ac74fbSHeejin Ahn } 934c4ac74fbSHeejin Ahn } 935c4ac74fbSHeejin Ahn 936c4ac74fbSHeejin Ahn assert(EHPadStack.empty()); 937c4ac74fbSHeejin Ahn 938c4ac74fbSHeejin Ahn // Gather possibly throwing calls that are supposed to unwind up to the caller 939c4ac74fbSHeejin Ahn // if they throw, but currently unwind to an incorrect destination. Unlike the 940c4ac74fbSHeejin Ahn // loop above, there can be multiple calls within a BB that unwind to the 941c4ac74fbSHeejin Ahn // caller, which we should group together in a range. 942c4ac74fbSHeejin Ahn bool NeedAppendixBlock = false; 943c4ac74fbSHeejin Ahn for (auto &MBB : reverse(MF)) { 944c4ac74fbSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; // inclusive 945c4ac74fbSHeejin Ahn for (auto &MI : reverse(MBB)) { 946c4ac74fbSHeejin Ahn if (MI.getOpcode() == WebAssembly::TRY) 947c4ac74fbSHeejin Ahn EHPadStack.pop_back(); 948c4ac74fbSHeejin Ahn else if (MI.getOpcode() == WebAssembly::CATCH) 949c4ac74fbSHeejin Ahn EHPadStack.push_back(MI.getParent()); 950c4ac74fbSHeejin Ahn 951c4ac74fbSHeejin Ahn // If MBB has an EH pad successor, this inst does not unwind to caller. 952c4ac74fbSHeejin Ahn if (MBB.hasEHPadSuccessor()) 953c4ac74fbSHeejin Ahn continue; 954c4ac74fbSHeejin Ahn 955c4ac74fbSHeejin Ahn // We wrap up the current range when we see a marker even if we haven't 956c4ac74fbSHeejin Ahn // finished a BB. 957d8ddf839SWouter van Oortmerssen if (RangeEnd && WebAssembly::isMarker(MI.getOpcode())) { 958c4ac74fbSHeejin Ahn NeedAppendixBlock = true; 959c4ac74fbSHeejin Ahn // Record the range. nullptr here means the unwind destination is the 960c4ac74fbSHeejin Ahn // caller. 961c4ac74fbSHeejin Ahn UnwindDestToTryRanges[nullptr].push_back( 962c4ac74fbSHeejin Ahn TryRange(RangeBegin, RangeEnd)); 963c4ac74fbSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers 964c4ac74fbSHeejin Ahn } 965c4ac74fbSHeejin Ahn 966c4ac74fbSHeejin Ahn // If EHPadStack is empty, that means it is correctly unwind to caller if 967c4ac74fbSHeejin Ahn // it throws, so we're good. If MI does not throw, we're good too. 968c4ac74fbSHeejin Ahn if (EHPadStack.empty() || !WebAssembly::mayThrow(MI)) 969c4ac74fbSHeejin Ahn continue; 970c4ac74fbSHeejin Ahn 971c4ac74fbSHeejin Ahn // We found an instruction that unwinds to the caller but currently has an 972c4ac74fbSHeejin Ahn // incorrect unwind destination. Create a new range or increment the 973c4ac74fbSHeejin Ahn // currently existing range. 974c4ac74fbSHeejin Ahn if (!RangeEnd) 975c4ac74fbSHeejin Ahn RangeBegin = RangeEnd = &MI; 976c4ac74fbSHeejin Ahn else 977c4ac74fbSHeejin Ahn RangeBegin = &MI; 978c4ac74fbSHeejin Ahn } 979c4ac74fbSHeejin Ahn 980c4ac74fbSHeejin Ahn if (RangeEnd) { 981c4ac74fbSHeejin Ahn NeedAppendixBlock = true; 982c4ac74fbSHeejin Ahn // Record the range. nullptr here means the unwind destination is the 983c4ac74fbSHeejin Ahn // caller. 984c4ac74fbSHeejin Ahn UnwindDestToTryRanges[nullptr].push_back(TryRange(RangeBegin, RangeEnd)); 985c4ac74fbSHeejin Ahn RangeBegin = RangeEnd = nullptr; // Reset range pointers 986c4ac74fbSHeejin Ahn } 987c4ac74fbSHeejin Ahn } 988c4ac74fbSHeejin Ahn 989c4ac74fbSHeejin Ahn assert(EHPadStack.empty()); 990c4ac74fbSHeejin Ahn // We don't have any unwind destination mismatches to resolve. 991c4ac74fbSHeejin Ahn if (UnwindDestToTryRanges.empty()) 992c4ac74fbSHeejin Ahn return false; 993c4ac74fbSHeejin Ahn 994c4ac74fbSHeejin Ahn // If we found instructions that should unwind to the caller but currently 995c4ac74fbSHeejin Ahn // have incorrect unwind destination, we create an appendix block at the end 996c4ac74fbSHeejin Ahn // of the function with a local.get and a rethrow instruction. 997c4ac74fbSHeejin Ahn if (NeedAppendixBlock) { 998c4ac74fbSHeejin Ahn auto *AppendixBB = getAppendixBlock(MF); 99905c145d6SDaniel Sanders Register ExnReg = MRI.createVirtualRegister(&WebAssembly::EXNREFRegClass); 1000c4ac74fbSHeejin Ahn BuildMI(AppendixBB, DebugLoc(), TII.get(WebAssembly::RETHROW)) 1001c4ac74fbSHeejin Ahn .addReg(ExnReg); 1002c4ac74fbSHeejin Ahn // These instruction ranges should branch to this appendix BB. 1003c4ac74fbSHeejin Ahn for (auto Range : UnwindDestToTryRanges[nullptr]) 1004c4ac74fbSHeejin Ahn BrDestToTryRanges[AppendixBB].push_back(Range); 1005c4ac74fbSHeejin Ahn BrDestToExnReg[AppendixBB] = ExnReg; 1006c4ac74fbSHeejin Ahn } 1007c4ac74fbSHeejin Ahn 1008c4ac74fbSHeejin Ahn // We loop through unwind destination EH pads that are targeted from some 1009c4ac74fbSHeejin Ahn // inner scopes. Because these EH pads are destination of more than one scope 1010c4ac74fbSHeejin Ahn // now, we split them so that the handler body is after 'end_try'. 1011c4ac74fbSHeejin Ahn // - Before 1012c4ac74fbSHeejin Ahn // ehpad: 1013c4ac74fbSHeejin Ahn // catch 1014c4ac74fbSHeejin Ahn // local.set n / drop 1015c4ac74fbSHeejin Ahn // handler body 1016c4ac74fbSHeejin Ahn // ... 1017c4ac74fbSHeejin Ahn // cont: 1018c4ac74fbSHeejin Ahn // end_try 1019c4ac74fbSHeejin Ahn // 1020c4ac74fbSHeejin Ahn // - After 1021c4ac74fbSHeejin Ahn // ehpad: 1022c4ac74fbSHeejin Ahn // catch 1023c4ac74fbSHeejin Ahn // local.set n / drop 1024c4ac74fbSHeejin Ahn // brdest: (new) 1025c4ac74fbSHeejin Ahn // end_try (hoisted from 'cont' BB) 1026c4ac74fbSHeejin Ahn // handler body (taken from 'ehpad') 1027c4ac74fbSHeejin Ahn // ... 1028c4ac74fbSHeejin Ahn // cont: 1029c4ac74fbSHeejin Ahn for (auto &P : UnwindDestToTryRanges) { 1030daeead4bSHeejin Ahn NumUnwindMismatches += P.second.size(); 1031c4ac74fbSHeejin Ahn 1032c4ac74fbSHeejin Ahn // This means the destination is the appendix BB, which was separately 1033c4ac74fbSHeejin Ahn // handled above. 1034c4ac74fbSHeejin Ahn if (!P.first) 1035c4ac74fbSHeejin Ahn continue; 1036c4ac74fbSHeejin Ahn 1037c4ac74fbSHeejin Ahn MachineBasicBlock *EHPad = P.first; 1038c4ac74fbSHeejin Ahn 1039c4ac74fbSHeejin Ahn // Find 'catch' and 'local.set' or 'drop' instruction that follows the 1040c4ac74fbSHeejin Ahn // 'catch'. If -wasm-disable-explicit-locals is not set, 'catch' should be 1041c4ac74fbSHeejin Ahn // always followed by either 'local.set' or a 'drop', because 'br_on_exn' is 1042c4ac74fbSHeejin Ahn // generated after 'catch' in LateEHPrepare and we don't support blocks 1043c4ac74fbSHeejin Ahn // taking values yet. 1044c4ac74fbSHeejin Ahn MachineInstr *Catch = nullptr; 1045c4ac74fbSHeejin Ahn unsigned ExnReg = 0; 1046c4ac74fbSHeejin Ahn for (auto &MI : *EHPad) { 1047c4ac74fbSHeejin Ahn switch (MI.getOpcode()) { 1048c4ac74fbSHeejin Ahn case WebAssembly::CATCH: 1049c4ac74fbSHeejin Ahn Catch = &MI; 1050c4ac74fbSHeejin Ahn ExnReg = Catch->getOperand(0).getReg(); 1051c4ac74fbSHeejin Ahn break; 1052c4ac74fbSHeejin Ahn } 1053c4ac74fbSHeejin Ahn } 1054c4ac74fbSHeejin Ahn assert(Catch && "EH pad does not have a catch"); 1055c4ac74fbSHeejin Ahn assert(ExnReg != 0 && "Invalid register"); 1056c4ac74fbSHeejin Ahn 1057c4ac74fbSHeejin Ahn auto SplitPos = std::next(Catch->getIterator()); 1058c4ac74fbSHeejin Ahn 1059c4ac74fbSHeejin Ahn // Create a new BB that's gonna be the destination for branches from the 1060c4ac74fbSHeejin Ahn // inner mismatched scope. 1061c4ac74fbSHeejin Ahn MachineInstr *BeginTry = EHPadToTry[EHPad]; 1062c4ac74fbSHeejin Ahn MachineInstr *EndTry = BeginToEnd[BeginTry]; 1063c4ac74fbSHeejin Ahn MachineBasicBlock *Cont = EndTry->getParent(); 1064c4ac74fbSHeejin Ahn auto *BrDest = MF.CreateMachineBasicBlock(); 1065c4ac74fbSHeejin Ahn MF.insert(std::next(EHPad->getIterator()), BrDest); 1066c4ac74fbSHeejin Ahn // Hoist up the existing 'end_try'. 1067c4ac74fbSHeejin Ahn BrDest->insert(BrDest->end(), EndTry->removeFromParent()); 1068c4ac74fbSHeejin Ahn // Take out the handler body from EH pad to the new branch destination BB. 1069c4ac74fbSHeejin Ahn BrDest->splice(BrDest->end(), EHPad, SplitPos, EHPad->end()); 107061d5c76aSHeejin Ahn unstackifyVRegsUsedInSplitBB(*EHPad, *BrDest, MFI, MRI); 1071c4ac74fbSHeejin Ahn // Fix predecessor-successor relationship. 1072c4ac74fbSHeejin Ahn BrDest->transferSuccessors(EHPad); 1073c4ac74fbSHeejin Ahn EHPad->addSuccessor(BrDest); 1074c4ac74fbSHeejin Ahn 1075c4ac74fbSHeejin Ahn // All try ranges that were supposed to unwind to this EH pad now have to 1076c4ac74fbSHeejin Ahn // branch to this new branch dest BB. 1077c4ac74fbSHeejin Ahn for (auto Range : UnwindDestToTryRanges[EHPad]) 1078c4ac74fbSHeejin Ahn BrDestToTryRanges[BrDest].push_back(Range); 1079c4ac74fbSHeejin Ahn BrDestToExnReg[BrDest] = ExnReg; 1080c4ac74fbSHeejin Ahn 1081c4ac74fbSHeejin Ahn // In case we fall through to the continuation BB after the catch block, we 1082c4ac74fbSHeejin Ahn // now have to add a branch to it. 1083c4ac74fbSHeejin Ahn // - Before 1084c4ac74fbSHeejin Ahn // try 1085c4ac74fbSHeejin Ahn // ... 1086c4ac74fbSHeejin Ahn // (falls through to 'cont') 1087c4ac74fbSHeejin Ahn // catch 1088c4ac74fbSHeejin Ahn // handler body 1089c4ac74fbSHeejin Ahn // end 1090c4ac74fbSHeejin Ahn // <-- cont 1091c4ac74fbSHeejin Ahn // 1092c4ac74fbSHeejin Ahn // - After 1093c4ac74fbSHeejin Ahn // try 1094c4ac74fbSHeejin Ahn // ... 1095c4ac74fbSHeejin Ahn // br %cont (new) 1096c4ac74fbSHeejin Ahn // catch 1097c4ac74fbSHeejin Ahn // end 1098c4ac74fbSHeejin Ahn // handler body 1099c4ac74fbSHeejin Ahn // <-- cont 1100c4ac74fbSHeejin Ahn MachineBasicBlock *EHPadLayoutPred = &*std::prev(EHPad->getIterator()); 1101c4ac74fbSHeejin Ahn MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1102c4ac74fbSHeejin Ahn SmallVector<MachineOperand, 4> Cond; 1103c4ac74fbSHeejin Ahn bool Analyzable = !TII.analyzeBranch(*EHPadLayoutPred, TBB, FBB, Cond); 1104c4ac74fbSHeejin Ahn if (Analyzable && !TBB && !FBB) { 1105c4ac74fbSHeejin Ahn DebugLoc DL = EHPadLayoutPred->empty() 1106c4ac74fbSHeejin Ahn ? DebugLoc() 1107c4ac74fbSHeejin Ahn : EHPadLayoutPred->rbegin()->getDebugLoc(); 1108c4ac74fbSHeejin Ahn BuildMI(EHPadLayoutPred, DL, TII.get(WebAssembly::BR)).addMBB(Cont); 1109834debffSHeejin Ahn BrDests.push_back(Cont); 1110c4ac74fbSHeejin Ahn } 1111c4ac74fbSHeejin Ahn } 1112c4ac74fbSHeejin Ahn 1113c4ac74fbSHeejin Ahn // For possibly throwing calls whose unwind destinations are currently 1114c4ac74fbSHeejin Ahn // incorrect because of CFG linearization, we wrap them with a nested 1115c4ac74fbSHeejin Ahn // try/catch/end_try, and within the new catch block, we branch to the correct 1116c4ac74fbSHeejin Ahn // handler. 1117c4ac74fbSHeejin Ahn // - Before 1118c4ac74fbSHeejin Ahn // mbb: 1119c4ac74fbSHeejin Ahn // call @foo <- Unwind destination mismatch! 1120c4ac74fbSHeejin Ahn // ehpad: 1121c4ac74fbSHeejin Ahn // ... 1122c4ac74fbSHeejin Ahn // 1123c4ac74fbSHeejin Ahn // - After 1124c4ac74fbSHeejin Ahn // mbb: 1125c4ac74fbSHeejin Ahn // try (new) 1126c4ac74fbSHeejin Ahn // call @foo 1127c4ac74fbSHeejin Ahn // nested-ehpad: (new) 1128c4ac74fbSHeejin Ahn // catch (new) 1129c4ac74fbSHeejin Ahn // local.set n / drop (new) 1130c4ac74fbSHeejin Ahn // br %brdest (new) 1131c4ac74fbSHeejin Ahn // nested-end: (new) 1132c4ac74fbSHeejin Ahn // end_try (new) 1133c4ac74fbSHeejin Ahn // ehpad: 1134c4ac74fbSHeejin Ahn // ... 1135c4ac74fbSHeejin Ahn for (auto &P : BrDestToTryRanges) { 1136c4ac74fbSHeejin Ahn MachineBasicBlock *BrDest = P.first; 1137c4ac74fbSHeejin Ahn auto &TryRanges = P.second; 1138c4ac74fbSHeejin Ahn unsigned ExnReg = BrDestToExnReg[BrDest]; 1139c4ac74fbSHeejin Ahn 1140c4ac74fbSHeejin Ahn for (auto Range : TryRanges) { 1141c4ac74fbSHeejin Ahn MachineInstr *RangeBegin = nullptr, *RangeEnd = nullptr; 1142c4ac74fbSHeejin Ahn std::tie(RangeBegin, RangeEnd) = Range; 1143c4ac74fbSHeejin Ahn auto *MBB = RangeBegin->getParent(); 1144ba40896fSHeejin Ahn // Store the first function call from this range, because RangeBegin can 1145ba40896fSHeejin Ahn // be moved to point EH_LABEL before the call 1146ba40896fSHeejin Ahn MachineInstr *RangeBeginCall = RangeBegin; 1147c4ac74fbSHeejin Ahn 1148c4ac74fbSHeejin Ahn // Include possible EH_LABELs in the range 1149c4ac74fbSHeejin Ahn if (RangeBegin->getIterator() != MBB->begin() && 1150c4ac74fbSHeejin Ahn std::prev(RangeBegin->getIterator())->isEHLabel()) 1151c4ac74fbSHeejin Ahn RangeBegin = &*std::prev(RangeBegin->getIterator()); 1152c4ac74fbSHeejin Ahn if (std::next(RangeEnd->getIterator()) != MBB->end() && 1153c4ac74fbSHeejin Ahn std::next(RangeEnd->getIterator())->isEHLabel()) 1154c4ac74fbSHeejin Ahn RangeEnd = &*std::next(RangeEnd->getIterator()); 1155c4ac74fbSHeejin Ahn 1156c4ac74fbSHeejin Ahn MachineBasicBlock *EHPad = nullptr; 1157c4ac74fbSHeejin Ahn for (auto *Succ : MBB->successors()) { 1158c4ac74fbSHeejin Ahn if (Succ->isEHPad()) { 1159c4ac74fbSHeejin Ahn EHPad = Succ; 1160c4ac74fbSHeejin Ahn break; 1161c4ac74fbSHeejin Ahn } 1162c4ac74fbSHeejin Ahn } 1163c4ac74fbSHeejin Ahn 1164ba40896fSHeejin Ahn // Local expression tree before the first call of this range should go 1165ba40896fSHeejin Ahn // after the nested TRY. 1166ba40896fSHeejin Ahn SmallPtrSet<const MachineInstr *, 4> AfterSet; 1167ba40896fSHeejin Ahn AfterSet.insert(RangeBegin); 1168ba40896fSHeejin Ahn AfterSet.insert(RangeBeginCall); 1169ba40896fSHeejin Ahn for (auto I = MachineBasicBlock::iterator(RangeBeginCall), 1170ba40896fSHeejin Ahn E = MBB->begin(); 1171ba40896fSHeejin Ahn I != E; --I) { 1172ba40896fSHeejin Ahn if (std::prev(I)->isDebugInstr() || std::prev(I)->isPosition()) 1173ba40896fSHeejin Ahn continue; 1174ba40896fSHeejin Ahn if (WebAssembly::isChild(*std::prev(I), MFI)) 1175ba40896fSHeejin Ahn AfterSet.insert(&*std::prev(I)); 1176ba40896fSHeejin Ahn else 1177ba40896fSHeejin Ahn break; 1178ba40896fSHeejin Ahn } 1179ba40896fSHeejin Ahn 1180c4ac74fbSHeejin Ahn // Create the nested try instruction. 1181ba40896fSHeejin Ahn auto InsertPos = getLatestInsertPos( 1182ba40896fSHeejin Ahn MBB, SmallPtrSet<const MachineInstr *, 4>(), AfterSet); 1183c4ac74fbSHeejin Ahn MachineInstr *NestedTry = 1184ba40896fSHeejin Ahn BuildMI(*MBB, InsertPos, RangeBegin->getDebugLoc(), 1185c4ac74fbSHeejin Ahn TII.get(WebAssembly::TRY)) 11862cb27072SThomas Lively .addImm(int64_t(WebAssembly::BlockType::Void)); 1187c4ac74fbSHeejin Ahn 1188c4ac74fbSHeejin Ahn // Create the nested EH pad and fill instructions in. 1189c4ac74fbSHeejin Ahn MachineBasicBlock *NestedEHPad = MF.CreateMachineBasicBlock(); 1190c4ac74fbSHeejin Ahn MF.insert(std::next(MBB->getIterator()), NestedEHPad); 1191c4ac74fbSHeejin Ahn NestedEHPad->setIsEHPad(); 1192c4ac74fbSHeejin Ahn NestedEHPad->setIsEHScopeEntry(); 1193c4ac74fbSHeejin Ahn BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::CATCH), 1194c4ac74fbSHeejin Ahn ExnReg); 1195c4ac74fbSHeejin Ahn BuildMI(NestedEHPad, RangeEnd->getDebugLoc(), TII.get(WebAssembly::BR)) 1196c4ac74fbSHeejin Ahn .addMBB(BrDest); 1197c4ac74fbSHeejin Ahn 1198c4ac74fbSHeejin Ahn // Create the nested continuation BB and end_try instruction. 1199c4ac74fbSHeejin Ahn MachineBasicBlock *NestedCont = MF.CreateMachineBasicBlock(); 1200c4ac74fbSHeejin Ahn MF.insert(std::next(NestedEHPad->getIterator()), NestedCont); 1201c4ac74fbSHeejin Ahn MachineInstr *NestedEndTry = 1202c4ac74fbSHeejin Ahn BuildMI(*NestedCont, NestedCont->begin(), RangeEnd->getDebugLoc(), 1203c4ac74fbSHeejin Ahn TII.get(WebAssembly::END_TRY)); 1204c4ac74fbSHeejin Ahn // In case MBB has more instructions after the try range, move them to the 1205c4ac74fbSHeejin Ahn // new nested continuation BB. 1206c4ac74fbSHeejin Ahn NestedCont->splice(NestedCont->end(), MBB, 1207c4ac74fbSHeejin Ahn std::next(RangeEnd->getIterator()), MBB->end()); 120861d5c76aSHeejin Ahn unstackifyVRegsUsedInSplitBB(*MBB, *NestedCont, MFI, MRI); 1209c4ac74fbSHeejin Ahn registerTryScope(NestedTry, NestedEndTry, NestedEHPad); 1210c4ac74fbSHeejin Ahn 1211c4ac74fbSHeejin Ahn // Fix predecessor-successor relationship. 1212c4ac74fbSHeejin Ahn NestedCont->transferSuccessors(MBB); 1213834debffSHeejin Ahn if (EHPad) { 1214c4ac74fbSHeejin Ahn NestedCont->removeSuccessor(EHPad); 1215834debffSHeejin Ahn // If EHPad does not have any predecessors left after removing 1216834debffSHeejin Ahn // NextedCont predecessor, remove its successor too, because this EHPad 1217834debffSHeejin Ahn // is not reachable from the entry BB anyway. We can't remove EHPad BB 1218834debffSHeejin Ahn // itself because it can contain 'catch' or 'end', which are necessary 1219834debffSHeejin Ahn // for keeping try-catch-end structure. 1220834debffSHeejin Ahn if (EHPad->pred_empty()) 1221834debffSHeejin Ahn EHPad->removeSuccessor(BrDest); 1222834debffSHeejin Ahn } 1223c4ac74fbSHeejin Ahn MBB->addSuccessor(NestedEHPad); 1224c4ac74fbSHeejin Ahn MBB->addSuccessor(NestedCont); 1225c4ac74fbSHeejin Ahn NestedEHPad->addSuccessor(BrDest); 1226c4ac74fbSHeejin Ahn } 1227c4ac74fbSHeejin Ahn } 1228c4ac74fbSHeejin Ahn 1229c4ac74fbSHeejin Ahn // Renumber BBs and recalculate ScopeTop info because new BBs might have been 1230c4ac74fbSHeejin Ahn // created and inserted above. 1231c4ac74fbSHeejin Ahn MF.RenumberBlocks(); 1232c4ac74fbSHeejin Ahn ScopeTops.clear(); 1233c4ac74fbSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs()); 1234c4ac74fbSHeejin Ahn for (auto &MBB : reverse(MF)) { 1235c4ac74fbSHeejin Ahn for (auto &MI : reverse(MBB)) { 1236c4ac74fbSHeejin Ahn if (ScopeTops[MBB.getNumber()]) 1237c4ac74fbSHeejin Ahn break; 1238c4ac74fbSHeejin Ahn switch (MI.getOpcode()) { 1239c4ac74fbSHeejin Ahn case WebAssembly::END_BLOCK: 1240c4ac74fbSHeejin Ahn case WebAssembly::END_LOOP: 1241c4ac74fbSHeejin Ahn case WebAssembly::END_TRY: 1242c4ac74fbSHeejin Ahn ScopeTops[MBB.getNumber()] = EndToBegin[&MI]->getParent(); 1243c4ac74fbSHeejin Ahn break; 1244c4ac74fbSHeejin Ahn case WebAssembly::CATCH: 1245c4ac74fbSHeejin Ahn ScopeTops[MBB.getNumber()] = EHPadToTry[&MBB]->getParent(); 1246c4ac74fbSHeejin Ahn break; 1247c4ac74fbSHeejin Ahn } 1248c4ac74fbSHeejin Ahn } 1249c4ac74fbSHeejin Ahn } 1250c4ac74fbSHeejin Ahn 1251c4ac74fbSHeejin Ahn // Recompute the dominator tree. 1252c4ac74fbSHeejin Ahn getAnalysis<MachineDominatorTree>().runOnMachineFunction(MF); 1253c4ac74fbSHeejin Ahn 1254834debffSHeejin Ahn // Place block markers for newly added branches, if necessary. 1255834debffSHeejin Ahn 1256834debffSHeejin Ahn // If we've created an appendix BB and a branch to it, place a block/end_block 1257834debffSHeejin Ahn // marker for that. For some new branches, those branch destination BBs start 1258834debffSHeejin Ahn // with a hoisted end_try marker, so we don't need a new marker there. 1259834debffSHeejin Ahn if (AppendixBB) 1260834debffSHeejin Ahn BrDests.push_back(AppendixBB); 1261834debffSHeejin Ahn 1262c4ac74fbSHeejin Ahn llvm::sort(BrDests, 1263c4ac74fbSHeejin Ahn [&](const MachineBasicBlock *A, const MachineBasicBlock *B) { 1264c4ac74fbSHeejin Ahn auto ANum = A->getNumber(); 1265c4ac74fbSHeejin Ahn auto BNum = B->getNumber(); 1266c4ac74fbSHeejin Ahn return ANum < BNum; 1267c4ac74fbSHeejin Ahn }); 1268c4ac74fbSHeejin Ahn for (auto *Dest : BrDests) 1269c4ac74fbSHeejin Ahn placeBlockMarker(*Dest); 1270c4ac74fbSHeejin Ahn 1271c4ac74fbSHeejin Ahn return true; 1272c4ac74fbSHeejin Ahn } 1273c4ac74fbSHeejin Ahn 12741d68e80fSDan Gohman static unsigned 127518c56a07SHeejin Ahn getDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 12761d68e80fSDan Gohman const MachineBasicBlock *MBB) { 12771d68e80fSDan Gohman unsigned Depth = 0; 12781d68e80fSDan Gohman for (auto X : reverse(Stack)) { 12791d68e80fSDan Gohman if (X == MBB) 12801d68e80fSDan Gohman break; 12811d68e80fSDan Gohman ++Depth; 12821d68e80fSDan Gohman } 12831d68e80fSDan Gohman assert(Depth < Stack.size() && "Branch destination should be in scope"); 12841d68e80fSDan Gohman return Depth; 12851d68e80fSDan Gohman } 12861d68e80fSDan Gohman 12872726b88cSDan Gohman /// In normal assembly languages, when the end of a function is unreachable, 12882726b88cSDan Gohman /// because the function ends in an infinite loop or a noreturn call or similar, 12892726b88cSDan Gohman /// it isn't necessary to worry about the function return type at the end of 12902726b88cSDan Gohman /// the function, because it's never reached. However, in WebAssembly, blocks 12912726b88cSDan Gohman /// that end at the function end need to have a return type signature that 12922726b88cSDan Gohman /// matches the function signature, even though it's unreachable. This function 12932726b88cSDan Gohman /// checks for such cases and fixes up the signatures. 1294e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::fixEndsAtEndOfFunction(MachineFunction &MF) { 1295e76fa9ecSHeejin Ahn const auto &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 12962726b88cSDan Gohman 12972726b88cSDan Gohman if (MFI.getResults().empty()) 12982726b88cSDan Gohman return; 12992726b88cSDan Gohman 13002cb27072SThomas Lively // MCInstLower will add the proper types to multivalue signatures based on the 13012cb27072SThomas Lively // function return type 13022cb27072SThomas Lively WebAssembly::BlockType RetType = 13032cb27072SThomas Lively MFI.getResults().size() > 1 13042cb27072SThomas Lively ? WebAssembly::BlockType::Multivalue 13052cb27072SThomas Lively : WebAssembly::BlockType( 13062cb27072SThomas Lively WebAssembly::toValType(MFI.getResults().front())); 13072726b88cSDan Gohman 13082726b88cSDan Gohman for (MachineBasicBlock &MBB : reverse(MF)) { 13092726b88cSDan Gohman for (MachineInstr &MI : reverse(MBB)) { 1310801bf7ebSShiva Chen if (MI.isPosition() || MI.isDebugInstr()) 13112726b88cSDan Gohman continue; 13122cb27072SThomas Lively switch (MI.getOpcode()) { 13132cb27072SThomas Lively case WebAssembly::END_BLOCK: 13142cb27072SThomas Lively case WebAssembly::END_LOOP: 13152cb27072SThomas Lively case WebAssembly::END_TRY: 131618c56a07SHeejin Ahn EndToBegin[&MI]->getOperand(0).setImm(int32_t(RetType)); 13172726b88cSDan Gohman continue; 13182cb27072SThomas Lively default: 13192726b88cSDan Gohman // Something other than an `end`. We're done. 13202726b88cSDan Gohman return; 13212726b88cSDan Gohman } 13222726b88cSDan Gohman } 13232726b88cSDan Gohman } 13242cb27072SThomas Lively } 13252726b88cSDan Gohman 1326d934cb88SDan Gohman // WebAssembly functions end with an end instruction, as if the function body 1327d934cb88SDan Gohman // were a block. 132818c56a07SHeejin Ahn static void appendEndToFunction(MachineFunction &MF, 1329d934cb88SDan Gohman const WebAssemblyInstrInfo &TII) { 133010b31358SDerek Schuff BuildMI(MF.back(), MF.back().end(), 133110b31358SDerek Schuff MF.back().findPrevDebugLoc(MF.back().end()), 1332d934cb88SDan Gohman TII.get(WebAssembly::END_FUNCTION)); 1333d934cb88SDan Gohman } 1334d934cb88SDan Gohman 1335e76fa9ecSHeejin Ahn /// Insert LOOP/TRY/BLOCK markers at appropriate places. 1336e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::placeMarkers(MachineFunction &MF) { 1337e76fa9ecSHeejin Ahn // We allocate one more than the number of blocks in the function to 1338e76fa9ecSHeejin Ahn // accommodate for the possible fake block we may insert at the end. 1339e76fa9ecSHeejin Ahn ScopeTops.resize(MF.getNumBlockIDs() + 1); 13408fe7e86bSDan Gohman // Place the LOOP for MBB if MBB is the header of a loop. 1341e76fa9ecSHeejin Ahn for (auto &MBB : MF) 1342e76fa9ecSHeejin Ahn placeLoopMarker(MBB); 134344a5a4b1SHeejin Ahn 1344d6f48786SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 134544a5a4b1SHeejin Ahn for (auto &MBB : MF) { 134644a5a4b1SHeejin Ahn if (MBB.isEHPad()) { 134744a5a4b1SHeejin Ahn // Place the TRY for MBB if MBB is the EH pad of an exception. 1348e76fa9ecSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1349e76fa9ecSHeejin Ahn MF.getFunction().hasPersonalityFn()) 1350e76fa9ecSHeejin Ahn placeTryMarker(MBB); 135144a5a4b1SHeejin Ahn } else { 135232807932SDan Gohman // Place the BLOCK for MBB if MBB is branched to from above. 1353e76fa9ecSHeejin Ahn placeBlockMarker(MBB); 1354950a13cfSDan Gohman } 135544a5a4b1SHeejin Ahn } 1356c4ac74fbSHeejin Ahn // Fix mismatches in unwind destinations induced by linearizing the code. 1357daeead4bSHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1358daeead4bSHeejin Ahn MF.getFunction().hasPersonalityFn()) 1359c4ac74fbSHeejin Ahn fixUnwindMismatches(MF); 136044a5a4b1SHeejin Ahn } 1361950a13cfSDan Gohman 1362e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::rewriteDepthImmediates(MachineFunction &MF) { 13631d68e80fSDan Gohman // Now rewrite references to basic blocks to be depth immediates. 13641d68e80fSDan Gohman SmallVector<const MachineBasicBlock *, 8> Stack; 13651d68e80fSDan Gohman for (auto &MBB : reverse(MF)) { 1366e76fa9ecSHeejin Ahn for (auto I = MBB.rbegin(), E = MBB.rend(); I != E; ++I) { 1367e76fa9ecSHeejin Ahn MachineInstr &MI = *I; 13681d68e80fSDan Gohman switch (MI.getOpcode()) { 13691d68e80fSDan Gohman case WebAssembly::BLOCK: 1370e76fa9ecSHeejin Ahn case WebAssembly::TRY: 1371e76fa9ecSHeejin Ahn assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= 1372e76fa9ecSHeejin Ahn MBB.getNumber() && 1373e76fa9ecSHeejin Ahn "Block/try marker should be balanced"); 1374e76fa9ecSHeejin Ahn Stack.pop_back(); 1375e76fa9ecSHeejin Ahn break; 1376e76fa9ecSHeejin Ahn 13771d68e80fSDan Gohman case WebAssembly::LOOP: 13781d68e80fSDan Gohman assert(Stack.back() == &MBB && "Loop top should be balanced"); 13791d68e80fSDan Gohman Stack.pop_back(); 13801d68e80fSDan Gohman break; 1381e76fa9ecSHeejin Ahn 13821d68e80fSDan Gohman case WebAssembly::END_BLOCK: 1383e76fa9ecSHeejin Ahn case WebAssembly::END_TRY: 13841d68e80fSDan Gohman Stack.push_back(&MBB); 13851d68e80fSDan Gohman break; 1386e76fa9ecSHeejin Ahn 13871d68e80fSDan Gohman case WebAssembly::END_LOOP: 1388e76fa9ecSHeejin Ahn Stack.push_back(EndToBegin[&MI]->getParent()); 13891d68e80fSDan Gohman break; 1390e76fa9ecSHeejin Ahn 13911d68e80fSDan Gohman default: 13921d68e80fSDan Gohman if (MI.isTerminator()) { 13931d68e80fSDan Gohman // Rewrite MBB operands to be depth immediates. 13941d68e80fSDan Gohman SmallVector<MachineOperand, 4> Ops(MI.operands()); 13951d68e80fSDan Gohman while (MI.getNumOperands() > 0) 13961d68e80fSDan Gohman MI.RemoveOperand(MI.getNumOperands() - 1); 13971d68e80fSDan Gohman for (auto MO : Ops) { 13981d68e80fSDan Gohman if (MO.isMBB()) 139918c56a07SHeejin Ahn MO = MachineOperand::CreateImm(getDepth(Stack, MO.getMBB())); 14001d68e80fSDan Gohman MI.addOperand(MF, MO); 140132807932SDan Gohman } 14021d68e80fSDan Gohman } 14031d68e80fSDan Gohman break; 14041d68e80fSDan Gohman } 14051d68e80fSDan Gohman } 14061d68e80fSDan Gohman } 14071d68e80fSDan Gohman assert(Stack.empty() && "Control flow should be balanced"); 1408e76fa9ecSHeejin Ahn } 14092726b88cSDan Gohman 1410e76fa9ecSHeejin Ahn void WebAssemblyCFGStackify::releaseMemory() { 1411e76fa9ecSHeejin Ahn ScopeTops.clear(); 1412e76fa9ecSHeejin Ahn BeginToEnd.clear(); 1413e76fa9ecSHeejin Ahn EndToBegin.clear(); 1414e76fa9ecSHeejin Ahn TryToEHPad.clear(); 1415e76fa9ecSHeejin Ahn EHPadToTry.clear(); 1416c4ac74fbSHeejin Ahn AppendixBB = nullptr; 14171d68e80fSDan Gohman } 141832807932SDan Gohman 1419950a13cfSDan Gohman bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 1420d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n" 1421950a13cfSDan Gohman "********** Function: " 1422950a13cfSDan Gohman << MF.getName() << '\n'); 1423cf699b45SHeejin Ahn const MCAsmInfo *MCAI = MF.getTarget().getMCAsmInfo(); 1424950a13cfSDan Gohman 1425e76fa9ecSHeejin Ahn releaseMemory(); 1426e76fa9ecSHeejin Ahn 1427e040533eSDan Gohman // Liveness is not tracked for VALUE_STACK physreg. 14289c3bf318SDerek Schuff MF.getRegInfo().invalidateLiveness(); 1429950a13cfSDan Gohman 1430e76fa9ecSHeejin Ahn // Place the BLOCK/LOOP/TRY markers to indicate the beginnings of scopes. 1431e76fa9ecSHeejin Ahn placeMarkers(MF); 1432e76fa9ecSHeejin Ahn 1433c4ac74fbSHeejin Ahn // Remove unnecessary instructions possibly introduced by try/end_trys. 1434cf699b45SHeejin Ahn if (MCAI->getExceptionHandlingType() == ExceptionHandling::Wasm && 1435cf699b45SHeejin Ahn MF.getFunction().hasPersonalityFn()) 1436cf699b45SHeejin Ahn removeUnnecessaryInstrs(MF); 1437cf699b45SHeejin Ahn 1438e76fa9ecSHeejin Ahn // Convert MBB operands in terminators to relative depth immediates. 1439e76fa9ecSHeejin Ahn rewriteDepthImmediates(MF); 1440e76fa9ecSHeejin Ahn 1441e76fa9ecSHeejin Ahn // Fix up block/loop/try signatures at the end of the function to conform to 1442e76fa9ecSHeejin Ahn // WebAssembly's rules. 1443e76fa9ecSHeejin Ahn fixEndsAtEndOfFunction(MF); 1444e76fa9ecSHeejin Ahn 1445e76fa9ecSHeejin Ahn // Add an end instruction at the end of the function body. 1446e76fa9ecSHeejin Ahn const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 1447e76fa9ecSHeejin Ahn if (!MF.getSubtarget<WebAssemblySubtarget>() 1448e76fa9ecSHeejin Ahn .getTargetTriple() 1449e76fa9ecSHeejin Ahn .isOSBinFormatELF()) 145018c56a07SHeejin Ahn appendEndToFunction(MF, TII); 145132807932SDan Gohman 14521aaa481fSHeejin Ahn MF.getInfo<WebAssemblyFunctionInfo>()->setCFGStackified(); 1453950a13cfSDan Gohman return true; 1454950a13cfSDan Gohman } 1455